Compare commits

...

5 Commits

Author SHA1 Message Date
William Cheng
f2e2b30f23 fix some tests, update default generator 2020-12-08 14:50:05 +08:00
William Cheng
37cec1695c better code format 2020-12-08 01:57:47 +08:00
William Cheng
4a275b24f7 update tests, generators and more 2020-12-08 01:56:42 +08:00
William Cheng
8c06f96529 refactor modelutils (partial) 2020-12-08 00:21:37 +08:00
William Cheng
36d366b19b refactor isAnyTypeSchema, isFreeFormType 2020-12-07 23:09:05 +08:00
124 changed files with 1658 additions and 1614 deletions

View File

@ -150,9 +150,9 @@ public interface CodegenConfig {
Map<String, String> reservedWordsMappings(); Map<String, String> reservedWordsMappings();
void preprocessOpenAPI(OpenAPI openAPI); void preprocessOpenAPI();
void processOpenAPI(OpenAPI openAPI); void processOpenAPI();
Compiler processCompiler(Compiler compiler); Compiler processCompiler(Compiler compiler);

View File

@ -111,8 +111,8 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
/** /**
* True if this property is an array of items or a map container. * True if this property is an array of items or a map container.
* See: * See:
* - ModelUtils.isArraySchema() * - modelUtils.isArraySchema()
* - ModelUtils.isMapSchema() * - modelUtils.isMapSchema()
*/ */
public boolean isContainer; public boolean isContainer;
public boolean isString; public boolean isString;

View File

@ -18,6 +18,7 @@
package org.openapitools.codegen; package org.openapitools.codegen;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import io.swagger.models.Model;
import io.swagger.v3.core.util.Json; import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.Operation;
@ -76,6 +77,7 @@ public class DefaultGenerator implements Generator {
protected CodegenConfig config; protected CodegenConfig config;
protected ClientOptInput opts; protected ClientOptInput opts;
protected OpenAPI openAPI; protected OpenAPI openAPI;
protected ModelUtils modelUtils;
protected CodegenIgnoreProcessor ignoreProcessor; protected CodegenIgnoreProcessor ignoreProcessor;
private Boolean generateApis = null; private Boolean generateApis = null;
private Boolean generateModels = null; private Boolean generateModels = null;
@ -108,7 +110,10 @@ public class DefaultGenerator implements Generator {
public Generator opts(ClientOptInput opts) { public Generator opts(ClientOptInput opts) {
this.opts = opts; this.opts = opts;
this.openAPI = opts.getOpenAPI(); this.openAPI = opts.getOpenAPI();
this.modelUtils = new ModelUtils(openAPI);
this.config = opts.getConfig(); this.config = opts.getConfig();
this.config.setOpenAPI(this.openAPI);
List<TemplateDefinition> userFiles = opts.getUserDefinedTemplates(); List<TemplateDefinition> userFiles = opts.getUserDefinedTemplates();
if (userFiles != null) { if (userFiles != null) {
this.userDefinedTemplates = ImmutableList.copyOf(userFiles); this.userDefinedTemplates = ImmutableList.copyOf(userFiles);
@ -152,6 +157,10 @@ public class DefaultGenerator implements Generator {
return this; return this;
} }
public ModelUtils getModelUtils() {
return modelUtils;
}
/** /**
* Retrieves an instance to the configured template processor, available after user-defined options are * Retrieves an instance to the configured template processor, available after user-defined options are
* applied via {@link DefaultGenerator#opts(ClientOptInput)}. * applied via {@link DefaultGenerator#opts(ClientOptInput)}.
@ -248,10 +257,7 @@ public class DefaultGenerator implements Generator {
} }
config.processOpts(); config.processOpts();
config.preprocessOpenAPI(openAPI); config.preprocessOpenAPI();
// set OpenAPI to make these available to all methods
config.setOpenAPI(openAPI);
config.additionalProperties().put("generatorVersion", ImplementationVersion.read()); config.additionalProperties().put("generatorVersion", ImplementationVersion.read());
config.additionalProperties().put("generatedDate", ZonedDateTime.now().toString()); config.additionalProperties().put("generatedDate", ZonedDateTime.now().toString());
@ -397,7 +403,7 @@ public class DefaultGenerator implements Generator {
return; return;
} }
final Map<String, Schema> schemas = ModelUtils.getSchemas(this.openAPI); final Map<String, Schema> schemas = modelUtils.getSchemas();
if (schemas == null) { if (schemas == null) {
LOGGER.warn("Skipping generation of models because specification document has no schemas."); LOGGER.warn("Skipping generation of models because specification document has no schemas.");
return; return;
@ -458,7 +464,7 @@ public class DefaultGenerator implements Generator {
Schema schema = schemas.get(name); Schema schema = schemas.get(name);
if (ModelUtils.isFreeFormObject(this.openAPI, schema)) { // check to see if it'a a free-form object if (modelUtils.isFreeFormObject(schema)) { // check to see if it'a a free-form object
// there are 3 free form use cases // there are 3 free form use cases
// 1. free form with no validation that is not allOf included in any composed schemas // 1. free form with no validation that is not allOf included in any composed schemas
// 2. free form with validation // 2. free form with validation
@ -472,17 +478,17 @@ public class DefaultGenerator implements Generator {
LOGGER.info("Model {} not generated since it's a free-form object", name); LOGGER.info("Model {} not generated since it's a free-form object", name);
continue; continue;
} }
} else if (ModelUtils.isMapSchema(schema)) { // check to see if it's a "map" model } else if (modelUtils.isMapSchema(schema)) { // check to see if it's a "map" model
// A composed schema (allOf, oneOf, anyOf) is considered a Map schema if the additionalproperties attribute is set // A composed schema (allOf, oneOf, anyOf) is considered a Map schema if the additionalproperties attribute is set
// for that composed schema. However, in the case of a composed schema, the properties are defined or referenced // for that composed schema. However, in the case of a composed schema, the properties are defined or referenced
// in the inner schemas, and the outer schema does not have properties. // in the inner schemas, and the outer schema does not have properties.
if (!ModelUtils.isGenerateAliasAsModel(schema) && !ModelUtils.isComposedSchema(schema) && (schema.getProperties() == null || schema.getProperties().isEmpty())) { if (!modelUtils.isGenerateAliasAsModel(schema) && !modelUtils.isComposedSchema(schema) && (schema.getProperties() == null || schema.getProperties().isEmpty())) {
// schema without property, i.e. alias to map // schema without property, i.e. alias to map
LOGGER.info("Model {} not generated since it's an alias to map (without property) and `generateAliasAsModel` is set to false (default)", name); LOGGER.info("Model {} not generated since it's an alias to map (without property) and `generateAliasAsModel` is set to false (default)", name);
continue; continue;
} }
} else if (ModelUtils.isArraySchema(schema)) { // check to see if it's an "array" model } else if (modelUtils.isArraySchema(schema)) { // check to see if it's an "array" model
if (!ModelUtils.isGenerateAliasAsModel(schema) && (schema.getProperties() == null || schema.getProperties().isEmpty())) { if (!modelUtils.isGenerateAliasAsModel(schema) && (schema.getProperties() == null || schema.getProperties().isEmpty())) {
// schema without property, i.e. alias to array // schema without property, i.e. alias to array
LOGGER.info("Model {} not generated since it's an alias to array (without property) and `generateAliasAsModel` is set to false (default)", name); LOGGER.info("Model {} not generated since it's an alias to array (without property) and `generateAliasAsModel` is set to false (default)", name);
continue; continue;
@ -856,19 +862,19 @@ public class DefaultGenerator implements Generator {
} }
// resolve inline models // resolve inline models
InlineModelResolver inlineModelResolver = new InlineModelResolver(); InlineModelResolver inlineModelResolver = new InlineModelResolver(openAPI);
inlineModelResolver.flatten(openAPI); inlineModelResolver.flatten();
configureGeneratorProperties(); configureGeneratorProperties();
configureOpenAPIInfo(); configureOpenAPIInfo();
config.processOpenAPI(openAPI); config.processOpenAPI();
processUserDefinedTemplates(); processUserDefinedTemplates();
List<File> files = new ArrayList<>(); List<File> files = new ArrayList<>();
// models // models
List<String> filteredSchemas = ModelUtils.getSchemasUsedOnlyInFormParam(openAPI); List<String> filteredSchemas = modelUtils.getSchemasUsedOnlyInFormParam();
List<Object> allModels = new ArrayList<>(); List<Object> allModels = new ArrayList<>();
generateModels(files, allModels, filteredSchemas); generateModels(files, allModels, filteredSchemas);
// apis // apis

View File

@ -38,7 +38,8 @@ import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class InlineModelResolver { public class InlineModelResolver {
private OpenAPI openapi; private OpenAPI openAPI;
private ModelUtils modelUtils;
private Map<String, Schema> addedModels = new HashMap<String, Schema>(); private Map<String, Schema> addedModels = new HashMap<String, Schema>();
private Map<String, String> generatedSignature = new HashMap<String, String>(); private Map<String, String> generatedSignature = new HashMap<String, String>();
@ -54,27 +55,36 @@ public class InlineModelResolver {
static final Logger LOGGER = LoggerFactory.getLogger(InlineModelResolver.class); static final Logger LOGGER = LoggerFactory.getLogger(InlineModelResolver.class);
void flatten(OpenAPI openapi) { public InlineModelResolver(OpenAPI openAPI) {
this.openapi = openapi; this.openAPI = openAPI;
this.modelUtils = new ModelUtils(openAPI);
}
if (openapi.getComponents() == null) { public OpenAPI getOpenAPI() {
openapi.setComponents(new Components()); return this.openAPI;
}
public ModelUtils getModelUtils() {
return this.modelUtils;
}
void flatten() {
if (openAPI.getComponents() == null) {
openAPI.setComponents(new Components());
} }
if (openapi.getComponents().getSchemas() == null) { if (openAPI.getComponents().getSchemas() == null) {
openapi.getComponents().setSchemas(new HashMap<String, Schema>()); openAPI.getComponents().setSchemas(new HashMap<String, Schema>());
} }
flattenPaths(openapi); flattenPaths();
flattenComponents(openapi); flattenComponents();
} }
/** /**
* Flatten inline models in Paths * Flatten inline models in Paths
*
* @param openAPI target spec
*/ */
private void flattenPaths(OpenAPI openAPI) { private void flattenPaths() {
Paths paths = openAPI.getPaths(); Paths paths = openAPI.getPaths();
if (paths == null) { if (paths == null) {
return; return;
@ -96,9 +106,9 @@ public class InlineModelResolver {
} }
for (Operation operation : operations) { for (Operation operation : operations) {
flattenRequestBody(openAPI, pathname, operation); flattenRequestBody(pathname, operation);
flattenParameters(openAPI, pathname, operation); flattenParameters(pathname, operation);
flattenResponses(openAPI, pathname, operation); flattenResponses(pathname, operation);
} }
} }
} }
@ -106,22 +116,21 @@ public class InlineModelResolver {
/** /**
* Flatten inline models in RequestBody * Flatten inline models in RequestBody
* *
* @param openAPI target spec * @param pathname target pathname
* @param pathname target pathname
* @param operation target operation * @param operation target operation
*/ */
private void flattenRequestBody(OpenAPI openAPI, String pathname, Operation operation) { private void flattenRequestBody(String pathname, Operation operation) {
RequestBody requestBody = operation.getRequestBody(); RequestBody requestBody = operation.getRequestBody();
if (requestBody == null) { if (requestBody == null) {
return; return;
} }
Schema model = ModelUtils.getSchemaFromRequestBody(requestBody); Schema model = modelUtils.getSchemaFromRequestBody(requestBody);
if (model instanceof ObjectSchema) { if (model instanceof ObjectSchema) {
Schema obj = (Schema) model; Schema obj = (Schema) model;
if (obj.getType() == null || "object".equals(obj.getType())) { if (obj.getType() == null || "object".equals(obj.getType())) {
if (obj.getProperties() != null && obj.getProperties().size() > 0) { if (obj.getProperties() != null && obj.getProperties().size() > 0) {
flattenProperties(openAPI, obj.getProperties(), pathname); flattenProperties(obj.getProperties(), pathname);
// for model name, use "title" if defined, otherwise default to 'inline_object' // for model name, use "title" if defined, otherwise default to 'inline_object'
String modelName = resolveModelName(obj.getTitle(), "inline_object"); String modelName = resolveModelName(obj.getTitle(), "inline_object");
addGenerated(modelName, model); addGenerated(modelName, model);
@ -163,7 +172,6 @@ public class InlineModelResolver {
// update requestBody to use $ref instead of inline def // update requestBody to use $ref instead of inline def
requestBody.set$ref(modelName); requestBody.set$ref(modelName);
} }
} }
} else if (model instanceof ArraySchema) { } else if (model instanceof ArraySchema) {
@ -172,10 +180,10 @@ public class InlineModelResolver {
if (inner instanceof ObjectSchema) { if (inner instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) inner; ObjectSchema op = (ObjectSchema) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) { if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(openAPI, op.getProperties(), pathname); flattenProperties(op.getProperties(), pathname);
// Generate a unique model name based on the title. // Generate a unique model name based on the title.
String modelName = resolveModelName(op.getTitle(), null); String modelName = resolveModelName(op.getTitle(), null);
Schema innerModel = modelFromProperty(openAPI, op, modelName); Schema innerModel = modelFromProperty(op, modelName);
String existing = matchGenerated(innerModel); String existing = matchGenerated(innerModel);
if (existing != null) { if (existing != null) {
Schema schema = new Schema().$ref(existing); Schema schema = new Schema().$ref(existing);
@ -196,11 +204,10 @@ public class InlineModelResolver {
/** /**
* Flatten inline models in parameters * Flatten inline models in parameters
* *
* @param openAPI target spec * @param pathname target pathname
* @param pathname target pathname
* @param operation target operation * @param operation target operation
*/ */
private void flattenParameters(OpenAPI openAPI, String pathname, Operation operation) { private void flattenParameters(String pathname, Operation operation) {
List<Parameter> parameters = operation.getParameters(); List<Parameter> parameters = operation.getParameters();
if (parameters == null) { if (parameters == null) {
return; return;
@ -216,7 +223,7 @@ public class InlineModelResolver {
Schema obj = (Schema) model; Schema obj = (Schema) model;
if (obj.getType() == null || "object".equals(obj.getType())) { if (obj.getType() == null || "object".equals(obj.getType())) {
if (obj.getProperties() != null && obj.getProperties().size() > 0) { if (obj.getProperties() != null && obj.getProperties().size() > 0) {
flattenProperties(openAPI, obj.getProperties(), pathname); flattenProperties(obj.getProperties(), pathname);
String modelName = resolveModelName(obj.getTitle(), parameter.getName()); String modelName = resolveModelName(obj.getTitle(), parameter.getName());
parameter.$ref(modelName); parameter.$ref(modelName);
@ -230,9 +237,9 @@ public class InlineModelResolver {
if (inner instanceof ObjectSchema) { if (inner instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) inner; ObjectSchema op = (ObjectSchema) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) { if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(openAPI, op.getProperties(), pathname); flattenProperties(op.getProperties(), pathname);
String modelName = resolveModelName(op.getTitle(), parameter.getName()); String modelName = resolveModelName(op.getTitle(), parameter.getName());
Schema innerModel = modelFromProperty(openAPI, op, modelName); Schema innerModel = modelFromProperty(op, modelName);
String existing = matchGenerated(innerModel); String existing = matchGenerated(innerModel);
if (existing != null) { if (existing != null) {
Schema schema = new Schema().$ref(existing); Schema schema = new Schema().$ref(existing);
@ -254,11 +261,10 @@ public class InlineModelResolver {
/** /**
* Flatten inline models in ApiResponses * Flatten inline models in ApiResponses
* *
* @param openAPI target spec * @param pathname target pathname
* @param pathname target pathname
* @param operation target operation * @param operation target operation
*/ */
private void flattenResponses(OpenAPI openAPI, String pathname, Operation operation) { private void flattenResponses(String pathname, Operation operation) {
ApiResponses responses = operation.getResponses(); ApiResponses responses = operation.getResponses();
if (responses == null) { if (responses == null) {
return; return;
@ -266,16 +272,16 @@ public class InlineModelResolver {
for (String key : responses.keySet()) { for (String key : responses.keySet()) {
ApiResponse response = responses.get(key); ApiResponse response = responses.get(key);
if (ModelUtils.getSchemaFromResponse(response) == null) { if (modelUtils.getSchemaFromResponse(response) == null) {
continue; continue;
} }
Schema property = ModelUtils.getSchemaFromResponse(response); Schema property = modelUtils.getSchemaFromResponse(response);
if (property instanceof ObjectSchema) { if (property instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) property; ObjectSchema op = (ObjectSchema) property;
if (op.getProperties() != null && op.getProperties().size() > 0) { if (op.getProperties() != null && op.getProperties().size() > 0) {
String modelName = resolveModelName(op.getTitle(), "inline_response_" + key); String modelName = resolveModelName(op.getTitle(), "inline_response_" + key);
Schema model = modelFromProperty(openAPI, op, modelName); Schema model = modelFromProperty(op, modelName);
String existing = matchGenerated(model); String existing = matchGenerated(model);
Content content = response.getContent(); Content content = response.getContent();
for (MediaType mediaType : content.values()) { for (MediaType mediaType : content.values()) {
@ -298,10 +304,10 @@ public class InlineModelResolver {
if (inner instanceof ObjectSchema) { if (inner instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) inner; ObjectSchema op = (ObjectSchema) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) { if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(openAPI, op.getProperties(), pathname); flattenProperties(op.getProperties(), pathname);
String modelName = resolveModelName(op.getTitle(), String modelName = resolveModelName(op.getTitle(),
"inline_response_" + key); "inline_response_" + key);
Schema innerModel = modelFromProperty(openAPI, op, modelName); Schema innerModel = modelFromProperty(op, modelName);
String existing = matchGenerated(innerModel); String existing = matchGenerated(innerModel);
if (existing != null) { if (existing != null) {
Schema schema = this.makeSchema(existing, op); Schema schema = this.makeSchema(existing, op);
@ -318,14 +324,14 @@ public class InlineModelResolver {
} }
} else if (property instanceof MapSchema) { } else if (property instanceof MapSchema) {
MapSchema mp = (MapSchema) property; MapSchema mp = (MapSchema) property;
Schema innerProperty = ModelUtils.getAdditionalProperties(openAPI, mp); Schema innerProperty = modelUtils.getAdditionalProperties(mp);
if (innerProperty instanceof ObjectSchema) { if (innerProperty instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) innerProperty; ObjectSchema op = (ObjectSchema) innerProperty;
if (op.getProperties() != null && op.getProperties().size() > 0) { if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(openAPI, op.getProperties(), pathname); flattenProperties(op.getProperties(), pathname);
String modelName = resolveModelName(op.getTitle(), String modelName = resolveModelName(op.getTitle(),
"inline_response_" + key); "inline_response_" + key);
Schema innerModel = modelFromProperty(openAPI, op, modelName); Schema innerModel = modelFromProperty(op, modelName);
String existing = matchGenerated(innerModel); String existing = matchGenerated(innerModel);
if (existing != null) { if (existing != null) {
Schema schema = new Schema().$ref(existing); Schema schema = new Schema().$ref(existing);
@ -348,30 +354,29 @@ public class InlineModelResolver {
* Flattens properties of inline object schemas that belong to a composed schema into a * Flattens properties of inline object schemas that belong to a composed schema into a
* single flat list of properties. This is useful to generate a single or multiple * single flat list of properties. This is useful to generate a single or multiple
* inheritance model. * inheritance model.
* * <p>
* In the example below, codegen may generate a 'Dog' class that extends from the * In the example below, codegen may generate a 'Dog' class that extends from the
* generated 'Animal' class. 'Dog' has additional properties 'name', 'age' and 'breed' that * generated 'Animal' class. 'Dog' has additional properties 'name', 'age' and 'breed' that
* are flattened as a single list of properties. * are flattened as a single list of properties.
* * <p>
* Dog: * Dog:
* allOf: * allOf:
* - $ref: '#/components/schemas/Animal' * - $ref: '#/components/schemas/Animal'
* - type: object * - type: object
* properties: * properties:
* name: * name:
* type: string * type: string
* age: * age:
* type: string * type: string
* - type: object * - type: object
* properties: * properties:
* breed: * breed:
* type: string * type: string
* *
* @param openAPI the OpenAPI document * @param key a unique name ofr the composed schema.
* @param key a unique name ofr the composed schema.
* @param children the list of nested schemas within a composed schema (allOf, anyOf, oneOf). * @param children the list of nested schemas within a composed schema (allOf, anyOf, oneOf).
*/ */
private void flattenComposedChildren(OpenAPI openAPI, String key, List<Schema> children) { private void flattenComposedChildren(String key, List<Schema> children) {
if (children == null || children.isEmpty()) { if (children == null || children.isEmpty()) {
return; return;
} }
@ -394,7 +399,7 @@ public class InlineModelResolver {
// To have complete control of the model naming, one can define the model separately // To have complete control of the model naming, one can define the model separately
// instead of inline. // instead of inline.
String innerModelName = resolveModelName(op.getTitle(), key); String innerModelName = resolveModelName(op.getTitle(), key);
Schema innerModel = modelFromProperty(openAPI, op, innerModelName); Schema innerModel = modelFromProperty(op, innerModelName);
String existing = matchGenerated(innerModel); String existing = matchGenerated(innerModel);
if (existing == null) { if (existing == null) {
openAPI.getComponents().addSchemas(innerModelName, innerModel); openAPI.getComponents().addSchemas(innerModelName, innerModel);
@ -416,10 +421,8 @@ public class InlineModelResolver {
/** /**
* Flatten inline models in components * Flatten inline models in components
*
* @param openAPI target spec
*/ */
private void flattenComponents(OpenAPI openAPI) { private void flattenComponents() {
Map<String, Schema> models = openAPI.getComponents().getSchemas(); Map<String, Schema> models = openAPI.getComponents().getSchemas();
if (models == null) { if (models == null) {
return; return;
@ -428,25 +431,25 @@ public class InlineModelResolver {
List<String> modelNames = new ArrayList<String>(models.keySet()); List<String> modelNames = new ArrayList<String>(models.keySet());
for (String modelName : modelNames) { for (String modelName : modelNames) {
Schema model = models.get(modelName); Schema model = models.get(modelName);
if (ModelUtils.isComposedSchema(model)) { if (modelUtils.isComposedSchema(model)) {
ComposedSchema m = (ComposedSchema) model; ComposedSchema m = (ComposedSchema) model;
// inline child schemas // inline child schemas
flattenComposedChildren(openAPI, modelName + "_allOf", m.getAllOf()); flattenComposedChildren(modelName + "_allOf", m.getAllOf());
flattenComposedChildren(openAPI, modelName + "_anyOf", m.getAnyOf()); flattenComposedChildren(modelName + "_anyOf", m.getAnyOf());
flattenComposedChildren(openAPI, modelName + "_oneOf", m.getOneOf()); flattenComposedChildren(modelName + "_oneOf", m.getOneOf());
} else if (model instanceof Schema) { } else if (model instanceof Schema) {
Schema m = (Schema) model; Schema m = (Schema) model;
Map<String, Schema> properties = m.getProperties(); Map<String, Schema> properties = m.getProperties();
flattenProperties(openAPI, properties, modelName); flattenProperties(properties, modelName);
fixStringModel(m); fixStringModel(m);
} else if (ModelUtils.isArraySchema(model)) { } else if (modelUtils.isArraySchema(model)) {
ArraySchema m = (ArraySchema) model; ArraySchema m = (ArraySchema) model;
Schema inner = m.getItems(); Schema inner = m.getItems();
if (inner instanceof ObjectSchema) { if (inner instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) inner; ObjectSchema op = (ObjectSchema) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) { if (op.getProperties() != null && op.getProperties().size() > 0) {
String innerModelName = resolveModelName(op.getTitle(), modelName + "_inner"); String innerModelName = resolveModelName(op.getTitle(), modelName + "_inner");
Schema innerModel = modelFromProperty(openAPI, op, innerModelName); Schema innerModel = modelFromProperty(op, innerModelName);
String existing = matchGenerated(innerModel); String existing = matchGenerated(innerModel);
if (existing == null) { if (existing == null) {
openAPI.getComponents().addSchemas(innerModelName, innerModel); openAPI.getComponents().addSchemas(innerModelName, innerModel);
@ -483,12 +486,11 @@ public class InlineModelResolver {
/** /**
* Generates a unique model name. Non-alphanumeric characters will be replaced * Generates a unique model name. Non-alphanumeric characters will be replaced
* with underscores * with underscores
* * <p>
* e.g. io.schema.User_name => io_schema_User_name * e.g. io.schema.User_name => io_schema_User_name
* *
* @param title String title field in the schema if present * @param title String title field in the schema if present
* @param key String model name * @param key String model name
*
* @return if provided the sanitized {@code title}, else the sanitized {@code key} * @return if provided the sanitized {@code title}, else the sanitized {@code key}
*/ */
private String resolveModelName(String title, String key) { private String resolveModelName(String title, String key) {
@ -527,24 +529,24 @@ public class InlineModelResolver {
/** /**
* Sanitizes the input so that it's valid name for a class or interface * Sanitizes the input so that it's valid name for a class or interface
* * <p>
* e.g. 12.schema.User name => _2_schema_User_name * e.g. 12.schema.User name => _2_schema_User_name
*/ */
private String sanitizeName(final String name) { private String sanitizeName(final String name) {
return name return name
.replaceAll("^[0-9]", "_") // e.g. 12object => _2object .replaceAll("^[0-9]", "_") // e.g. 12object => _2object
.replaceAll("[^A-Za-z0-9]", "_"); // e.g. io.schema.User name => io_schema_User_name .replaceAll("[^A-Za-z0-9]", "_"); // e.g. io.schema.User name => io_schema_User_name
} }
private String uniqueName(final String name) { private String uniqueName(final String name) {
if (openapi.getComponents().getSchemas() == null) { if (openAPI.getComponents().getSchemas() == null) {
return name; return name;
} }
String uniqueName = name; String uniqueName = name;
int count = 0; int count = 0;
while (true) { while (true) {
if (!openapi.getComponents().getSchemas().containsKey(uniqueName)) { if (!openAPI.getComponents().getSchemas().containsKey(uniqueName)) {
return uniqueName; return uniqueName;
} }
uniqueName = name + "_" + ++count; uniqueName = name + "_" + ++count;
@ -552,7 +554,7 @@ public class InlineModelResolver {
// TODO it would probably be a good idea to check against a list of used uniqueNames to make sure there are no collisions // TODO it would probably be a good idea to check against a list of used uniqueNames to make sure there are no collisions
} }
private void flattenProperties(OpenAPI openAPI, Map<String, Schema> properties, String path) { private void flattenProperties(Map<String, Schema> properties, String path) {
if (properties == null) { if (properties == null) {
return; return;
} }
@ -564,7 +566,7 @@ public class InlineModelResolver {
&& ((ObjectSchema) property).getProperties().size() > 0) { && ((ObjectSchema) property).getProperties().size() > 0) {
ObjectSchema op = (ObjectSchema) property; ObjectSchema op = (ObjectSchema) property;
String modelName = resolveModelName(op.getTitle(), path + "_" + key); String modelName = resolveModelName(op.getTitle(), path + "_" + key);
Schema model = modelFromProperty(openAPI, op, modelName); Schema model = modelFromProperty(op, modelName);
String existing = matchGenerated(model); String existing = matchGenerated(model);
if (existing != null) { if (existing != null) {
Schema schema = new Schema().$ref(existing); Schema schema = new Schema().$ref(existing);
@ -576,7 +578,7 @@ public class InlineModelResolver {
propsToUpdate.put(key, schema); propsToUpdate.put(key, schema);
modelsToAdd.put(modelName, model); modelsToAdd.put(modelName, model);
addGenerated(modelName, model); addGenerated(modelName, model);
openapi.getComponents().addSchemas(modelName, model); openAPI.getComponents().addSchemas(modelName, model);
} }
} else if (property instanceof ArraySchema) { } else if (property instanceof ArraySchema) {
ArraySchema ap = (ArraySchema) property; ArraySchema ap = (ArraySchema) property;
@ -584,9 +586,9 @@ public class InlineModelResolver {
if (inner instanceof ObjectSchema) { if (inner instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) inner; ObjectSchema op = (ObjectSchema) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) { if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(openAPI, op.getProperties(), path); flattenProperties(op.getProperties(), path);
String modelName = resolveModelName(op.getTitle(), path + "_" + key); String modelName = resolveModelName(op.getTitle(), path + "_" + key);
Schema innerModel = modelFromProperty(openAPI, op, modelName); Schema innerModel = modelFromProperty(op, modelName);
String existing = matchGenerated(innerModel); String existing = matchGenerated(innerModel);
if (existing != null) { if (existing != null) {
Schema schema = new Schema().$ref(existing); Schema schema = new Schema().$ref(existing);
@ -597,19 +599,19 @@ public class InlineModelResolver {
schema.setRequired(op.getRequired()); schema.setRequired(op.getRequired());
ap.setItems(schema); ap.setItems(schema);
addGenerated(modelName, innerModel); addGenerated(modelName, innerModel);
openapi.getComponents().addSchemas(modelName, innerModel); openAPI.getComponents().addSchemas(modelName, innerModel);
} }
} }
} }
} }
if (ModelUtils.isMapSchema(property)) { if (modelUtils.isMapSchema(property)) {
Schema inner = ModelUtils.getAdditionalProperties(openAPI, property); Schema inner = modelUtils.getAdditionalProperties(property);
if (inner instanceof ObjectSchema) { if (inner instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) inner; ObjectSchema op = (ObjectSchema) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) { if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(openAPI, op.getProperties(), path); flattenProperties(op.getProperties(), path);
String modelName = resolveModelName(op.getTitle(), path + "_" + key); String modelName = resolveModelName(op.getTitle(), path + "_" + key);
Schema innerModel = modelFromProperty(openAPI, op, modelName); Schema innerModel = modelFromProperty(op, modelName);
String existing = matchGenerated(innerModel); String existing = matchGenerated(innerModel);
if (existing != null) { if (existing != null) {
Schema schema = new Schema().$ref(existing); Schema schema = new Schema().$ref(existing);
@ -620,7 +622,7 @@ public class InlineModelResolver {
schema.setRequired(op.getRequired()); schema.setRequired(op.getRequired());
property.setAdditionalProperties(schema); property.setAdditionalProperties(schema);
addGenerated(modelName, innerModel); addGenerated(modelName, innerModel);
openapi.getComponents().addSchemas(modelName, innerModel); openAPI.getComponents().addSchemas(modelName, innerModel);
} }
} }
} }
@ -632,12 +634,12 @@ public class InlineModelResolver {
} }
} }
for (String key : modelsToAdd.keySet()) { for (String key : modelsToAdd.keySet()) {
openapi.getComponents().addSchemas(key, modelsToAdd.get(key)); openAPI.getComponents().addSchemas(key, modelsToAdd.get(key));
this.addedModels.put(key, modelsToAdd.get(key)); this.addedModels.put(key, modelsToAdd.get(key));
} }
} }
private Schema modelFromProperty(OpenAPI openAPI, Schema object, String path) { private Schema modelFromProperty(Schema object, String path) {
String description = object.getDescription(); String description = object.getDescription();
String example = null; String example = null;
Object obj = object.getExample(); Object obj = object.getExample();
@ -686,7 +688,7 @@ public class InlineModelResolver {
model.setDeprecated(object.getDeprecated()); model.setDeprecated(object.getDeprecated());
if (properties != null) { if (properties != null) {
flattenProperties(openAPI, properties, path); flattenProperties(properties, path);
model.setProperties(properties); model.setProperties(properties);
} }
return model; return model;
@ -715,7 +717,7 @@ public class InlineModelResolver {
private void copyVendorExtensions(Schema source, Schema target) { private void copyVendorExtensions(Schema source, Schema target) {
Map<String, Object> vendorExtensions = source.getExtensions(); Map<String, Object> vendorExtensions = source.getExtensions();
if (vendorExtensions == null) { if (vendorExtensions == null) {
return; return;
} }
for (String extName : vendorExtensions.keySet()) { for (String extName : vendorExtensions.keySet()) {
target.addExtension(extName, vendorExtensions.get(extName)); target.addExtension(extName, vendorExtensions.get(extName));

View File

@ -264,7 +264,7 @@ public class CodegenConfigurator {
public CodegenConfigurator setGenerateAliasAsModel(boolean generateAliasAsModel) { public CodegenConfigurator setGenerateAliasAsModel(boolean generateAliasAsModel) {
workflowSettingsBuilder.withGenerateAliasAsModel(generateAliasAsModel); workflowSettingsBuilder.withGenerateAliasAsModel(generateAliasAsModel);
ModelUtils.setGenerateAliasAsModel(generateAliasAsModel); GlobalSettings.setProperty("generateAliasAsModelKey", String.valueOf(generateAliasAsModel));
return this; return this;
} }
@ -508,9 +508,6 @@ public class CodegenConfigurator {
GlobalSettings.setProperty(entry.getKey(), entry.getValue()); GlobalSettings.setProperty(entry.getKey(), entry.getValue());
} }
// if caller resets GlobalSettings, we'll need to reset generateAliasAsModel. As noted in this method, this should be moved.
ModelUtils.setGenerateAliasAsModel(workflowSettings.isGenerateAliasAsModel());
// TODO: Support custom spec loader implementations (https://github.com/OpenAPITools/openapi-generator/issues/844) // TODO: Support custom spec loader implementations (https://github.com/OpenAPITools/openapi-generator/issues/844)
final List<AuthorizationValue> authorizationValues = AuthParser.parse(this.auth); final List<AuthorizationValue> authorizationValues = AuthParser.parse(this.auth);
ParseOptions options = new ParseOptions(); ParseOptions options = new ParseOptions();
@ -523,13 +520,18 @@ public class CodegenConfigurator {
// TODO: The line below could be removed when at least one of the issue below has been resolved. // TODO: The line below could be removed when at least one of the issue below has been resolved.
// https://github.com/swagger-api/swagger-parser/issues/1369 // https://github.com/swagger-api/swagger-parser/issues/1369
// https://github.com/swagger-api/swagger-parser/pull/1374 // https://github.com/swagger-api/swagger-parser/pull/1374
//ModelUtils.getOpenApiVersion(specification, inputSpec, authorizationValues); //modelUtils.getOpenApiVersion(specification, inputSpec, authorizationValues);
ModelUtils modelUtils = new ModelUtils(specification);
// if caller resets GlobalSettings, we'll need to reset generateAliasAsModel. As noted in this method, this should be moved.
modelUtils.setGenerateAliasAsModel(workflowSettings.isGenerateAliasAsModel());
// NOTE: We will only expose errors+warnings if there are already errors in the spec. // NOTE: We will only expose errors+warnings if there are already errors in the spec.
if (validationMessages.size() > 0) { if (validationMessages.size() > 0) {
Set<String> warnings = new HashSet<>(); Set<String> warnings = new HashSet<>();
if (specification != null) { if (specification != null) {
List<String> unusedModels = ModelUtils.getUnusedSchemas(specification); List<String> unusedModels = modelUtils.getUnusedSchemas();
if (unusedModels != null) { if (unusedModels != null) {
unusedModels.forEach(name -> warnings.add("Unused model: " + name)); unusedModels.forEach(name -> warnings.add("Unused model: " + name));
} }

View File

@ -17,6 +17,7 @@
package org.openapitools.codegen.examples; package org.openapitools.codegen.examples;
import com.sun.org.apache.xpath.internal.operations.Mod;
import io.swagger.v3.core.util.Json; import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.ArraySchema;
@ -46,11 +47,13 @@ public class ExampleGenerator {
protected Map<String, Schema> examples; protected Map<String, Schema> examples;
private OpenAPI openAPI; private OpenAPI openAPI;
private ModelUtils modelUtils;
private Random random; private Random random;
public ExampleGenerator(Map<String, Schema> examples, OpenAPI openAPI) { public ExampleGenerator(Map<String, Schema> examples, OpenAPI openAPI) {
this.examples = examples; this.examples = examples;
this.openAPI = openAPI; this.openAPI = openAPI;
this.modelUtils = new ModelUtils(openAPI);
// use a fixed seed to make the "random" numbers reproducible. // use a fixed seed to make the "random" numbers reproducible.
this.random = new Random("ExampleGenerator".hashCode()); this.random = new Random("ExampleGenerator".hashCode());
} }
@ -69,7 +72,7 @@ public class ExampleGenerator {
} }
private List<Map<String, String>> generateFromResponseSchema(Schema responseSchema, Set<String> producesInfo) { private List<Map<String, String>> generateFromResponseSchema(Schema responseSchema, Set<String> producesInfo) {
if (responseSchema.getExample() == null && StringUtils.isEmpty(responseSchema.get$ref()) && !ModelUtils.isArraySchema(responseSchema)) { if (responseSchema.getExample() == null && StringUtils.isEmpty(responseSchema.get$ref()) && !modelUtils.isArraySchema(responseSchema)) {
// no example provided // no example provided
return null; return null;
} }
@ -78,14 +81,14 @@ public class ExampleGenerator {
return generate(responseSchema.getExample(), new ArrayList<>(producesInfo)); return generate(responseSchema.getExample(), new ArrayList<>(producesInfo));
} }
if (ModelUtils.isArraySchema(responseSchema)) { // array of schema if (modelUtils.isArraySchema(responseSchema)) { // array of schema
ArraySchema as = (ArraySchema) responseSchema; ArraySchema as = (ArraySchema) responseSchema;
if (as.getItems() != null && StringUtils.isEmpty(as.getItems().get$ref())) { // arary of primtive types if (as.getItems() != null && StringUtils.isEmpty(as.getItems().get$ref())) { // arary of primtive types
return generate((Map<String, Object>) responseSchema.getExample(), return generate((Map<String, Object>) responseSchema.getExample(),
new ArrayList<String>(producesInfo), as.getItems()); new ArrayList<String>(producesInfo), as.getItems());
} else if (as.getItems() != null && !StringUtils.isEmpty(as.getItems().get$ref())) { // array of model } else if (as.getItems() != null && !StringUtils.isEmpty(as.getItems().get$ref())) { // array of model
return generate((Map<String, Object>) responseSchema.getExample(), return generate((Map<String, Object>) responseSchema.getExample(),
new ArrayList<String>(producesInfo), ModelUtils.getSimpleRef(as.getItems().get$ref())); new ArrayList<String>(producesInfo), modelUtils.getSimpleRef(as.getItems().get$ref()));
} else { } else {
// TODO log warning message as such case is not handled at the moment // TODO log warning message as such case is not handled at the moment
return null; return null;
@ -95,7 +98,7 @@ public class ExampleGenerator {
new ArrayList<String>(producesInfo), responseSchema); new ArrayList<String>(producesInfo), responseSchema);
} else { // model } else { // model
return generate((Map<String, Object>) responseSchema.getExample(), return generate((Map<String, Object>) responseSchema.getExample(),
new ArrayList<String>(producesInfo), ModelUtils.getSimpleRef(responseSchema.get$ref())); new ArrayList<String>(producesInfo), modelUtils.getSimpleRef(responseSchema.get$ref()));
} }
} }
@ -118,7 +121,7 @@ public class ExampleGenerator {
output.add(kv); output.add(kv);
} }
} else if (property != null && mediaType.startsWith(MIME_TYPE_XML)) { } else if (property != null && mediaType.startsWith(MIME_TYPE_XML)) {
String example = new XmlExampleGenerator(this.examples).toXml(property); String example = new XmlExampleGenerator(this.examples, openAPI).toXml(property);
if (example != null) { if (example != null) {
kv.put(EXAMPLE, example); kv.put(EXAMPLE, example);
output.add(kv); output.add(kv);
@ -165,7 +168,7 @@ public class ExampleGenerator {
} }
} else if (modelName != null && mediaType.startsWith(MIME_TYPE_XML)) { } else if (modelName != null && mediaType.startsWith(MIME_TYPE_XML)) {
final Schema schema = this.examples.get(modelName); final Schema schema = this.examples.get(modelName);
String example = new XmlExampleGenerator(this.examples).toXml(schema, 0, Collections.<String>emptySet()); String example = new XmlExampleGenerator(this.examples, openAPI).toXml(schema, 0, Collections.<String>emptySet());
if (example != null) { if (example != null) {
kv.put(EXAMPLE, example); kv.put(EXAMPLE, example);
output.add(kv); output.add(kv);
@ -222,13 +225,13 @@ public class ExampleGenerator {
if (property.getExample() != null) { if (property.getExample() != null) {
LOGGER.debug("Example set in openapi spec, returning example: '{}'", property.getExample().toString()); LOGGER.debug("Example set in openapi spec, returning example: '{}'", property.getExample().toString());
return property.getExample(); return property.getExample();
} else if (ModelUtils.isBooleanSchema(property)) { } else if (modelUtils.isBooleanSchema(property)) {
Object defaultValue = property.getDefault(); Object defaultValue = property.getDefault();
if (defaultValue != null) { if (defaultValue != null) {
return defaultValue; return defaultValue;
} }
return Boolean.TRUE; return Boolean.TRUE;
} else if (ModelUtils.isArraySchema(property)) { } else if (modelUtils.isArraySchema(property)) {
Schema innerType = ((ArraySchema) property).getItems(); Schema innerType = ((ArraySchema) property).getItems();
if (innerType != null) { if (innerType != null) {
int arrayLength = null == ((ArraySchema) property).getMaxItems() ? 2 : ((ArraySchema) property).getMaxItems(); int arrayLength = null == ((ArraySchema) property).getMaxItems() ? 2 : ((ArraySchema) property).getMaxItems();
@ -241,45 +244,45 @@ public class ExampleGenerator {
} }
return objectProperties; return objectProperties;
} }
} else if (ModelUtils.isDateSchema(property)) { } else if (modelUtils.isDateSchema(property)) {
return "2000-01-23"; return "2000-01-23";
} else if (ModelUtils.isDateTimeSchema(property)) { } else if (modelUtils.isDateTimeSchema(property)) {
return "2000-01-23T04:56:07.000+00:00"; return "2000-01-23T04:56:07.000+00:00";
} else if (ModelUtils.isNumberSchema(property)) { } else if (modelUtils.isNumberSchema(property)) {
Double min = getPropertyValue(property.getMinimum()); Double min = getPropertyValue(property.getMinimum());
Double max = getPropertyValue(property.getMaximum()); Double max = getPropertyValue(property.getMaximum());
if (ModelUtils.isFloatSchema(property)) { // float if (modelUtils.isFloatSchema(property)) { // float
return (float) randomNumber(min, max); return (float) randomNumber(min, max);
} else if (ModelUtils.isDoubleSchema(property)) { // decimal/double } else if (modelUtils.isDoubleSchema(property)) { // decimal/double
return BigDecimal.valueOf(randomNumber(min, max)); return BigDecimal.valueOf(randomNumber(min, max));
} else { // no format defined } else { // no format defined
return randomNumber(min, max); return randomNumber(min, max);
} }
} else if (ModelUtils.isFileSchema(property)) { } else if (modelUtils.isFileSchema(property)) {
return ""; // TODO return ""; // TODO
} else if (ModelUtils.isIntegerSchema(property)) { } else if (modelUtils.isIntegerSchema(property)) {
Double min = getPropertyValue(property.getMinimum()); Double min = getPropertyValue(property.getMinimum());
Double max = getPropertyValue(property.getMaximum()); Double max = getPropertyValue(property.getMaximum());
if (ModelUtils.isLongSchema(property)) { if (modelUtils.isLongSchema(property)) {
return (long) randomNumber(min, max); return (long) randomNumber(min, max);
} }
return (int) randomNumber(min, max); return (int) randomNumber(min, max);
} else if (ModelUtils.isMapSchema(property)) { } else if (modelUtils.isMapSchema(property)) {
Map<String, Object> mp = new HashMap<String, Object>(); Map<String, Object> mp = new HashMap<String, Object>();
if (property.getName() != null) { if (property.getName() != null) {
mp.put(property.getName(), mp.put(property.getName(),
resolvePropertyToExample(propertyName, mediaType, ModelUtils.getAdditionalProperties(openAPI, property), processedModels)); resolvePropertyToExample(propertyName, mediaType, modelUtils.getAdditionalProperties(property), processedModels));
} else { } else {
mp.put("key", mp.put("key",
resolvePropertyToExample(propertyName, mediaType, ModelUtils.getAdditionalProperties(openAPI, property), processedModels)); resolvePropertyToExample(propertyName, mediaType, modelUtils.getAdditionalProperties(property), processedModels));
} }
return mp; return mp;
} else if (ModelUtils.isUUIDSchema(property)) { } else if (modelUtils.isUUIDSchema(property)) {
return "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
} else if (ModelUtils.isURISchema(property)) { } else if (modelUtils.isURISchema(property)) {
return "https://openapi-generator.tech"; return "https://openapi-generator.tech";
} else if (ModelUtils.isStringSchema(property)) { } else if (modelUtils.isStringSchema(property)) {
LOGGER.debug("String property"); LOGGER.debug("String property");
String defaultValue = (String) property.getDefault(); String defaultValue = (String) property.getDefault();
if (defaultValue != null && !defaultValue.isEmpty()) { if (defaultValue != null && !defaultValue.isEmpty()) {
@ -299,14 +302,14 @@ public class ExampleGenerator {
LOGGER.debug("No values found, using property name " + propertyName + " as example"); LOGGER.debug("No values found, using property name " + propertyName + " as example");
return propertyName; return propertyName;
} else if (!StringUtils.isEmpty(property.get$ref())) { // model } else if (!StringUtils.isEmpty(property.get$ref())) { // model
String simpleName = ModelUtils.getSimpleRef(property.get$ref()); String simpleName = modelUtils.getSimpleRef(property.get$ref());
Schema schema = ModelUtils.getSchema(openAPI, simpleName); Schema schema = modelUtils.getSchema(simpleName);
if (schema == null) { // couldn't find the model/schema if (schema == null) { // couldn't find the model/schema
return "{}"; return "{}";
} }
return resolveModelToExample(simpleName, mediaType, schema, processedModels); return resolveModelToExample(simpleName, mediaType, schema, processedModels);
} else if (ModelUtils.isObjectSchema(property)) { } else if (modelUtils.isObjectSchema(property)) {
return "{}"; return "{}";
} }

View File

@ -17,6 +17,7 @@
package org.openapitools.codegen.examples; package org.openapitools.codegen.examples;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.XML; import io.swagger.v3.oas.models.media.XML;
@ -35,8 +36,12 @@ public class XmlExampleGenerator {
public static String TAG_END = "</"; public static String TAG_END = "</";
private static String EMPTY = ""; private static String EMPTY = "";
protected Map<String, Schema> examples; protected Map<String, Schema> examples;
protected OpenAPI openAPI;
protected ModelUtils modelUtils;
public XmlExampleGenerator(Map<String, Schema> examples) { public XmlExampleGenerator(Map<String, Schema> examples, OpenAPI openAPI) {
this.openAPI = openAPI;
this.modelUtils = new ModelUtils(openAPI);
this.examples = examples; this.examples = examples;
if (examples == null) { if (examples == null) {
this.examples = new HashMap<String, Schema>(); this.examples = new HashMap<String, Schema>();
@ -124,7 +129,7 @@ public class XmlExampleGenerator {
} }
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (ModelUtils.isArraySchema(schema)) { if (modelUtils.isArraySchema(schema)) {
ArraySchema as = (ArraySchema) schema; ArraySchema as = (ArraySchema) schema;
Schema inner = as.getItems(); Schema inner = as.getItems();
boolean wrapped = false; boolean wrapped = false;
@ -177,29 +182,29 @@ public class XmlExampleGenerator {
protected String getExample(Schema schema) { protected String getExample(Schema schema) {
if (schema.getExample() != null) { if (schema.getExample() != null) {
return schema.getExample().toString(); return schema.getExample().toString();
} else if (ModelUtils.isDateTimeSchema(schema)) { } else if (modelUtils.isDateTimeSchema(schema)) {
return "2000-01-23T04:56:07.000Z"; return "2000-01-23T04:56:07.000Z";
} else if (ModelUtils.isDateSchema(schema)) { } else if (modelUtils.isDateSchema(schema)) {
return "2000-01-23"; return "2000-01-23";
} else if (ModelUtils.isBooleanSchema(schema)) { } else if (modelUtils.isBooleanSchema(schema)) {
return "true"; return "true";
} else if (ModelUtils.isNumberSchema(schema)) { } else if (modelUtils.isNumberSchema(schema)) {
if (ModelUtils.isFloatSchema(schema)) { // float if (modelUtils.isFloatSchema(schema)) { // float
return "1.3579"; return "1.3579";
} else { // double } else { // double
return "3.149"; return "3.149";
} }
} else if (ModelUtils.isPasswordSchema(schema)) { } else if (modelUtils.isPasswordSchema(schema)) {
return "********"; return "********";
} else if (ModelUtils.isUUIDSchema(schema)) { } else if (modelUtils.isUUIDSchema(schema)) {
return "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
} else if (ModelUtils.isURISchema(schema)) { } else if (modelUtils.isURISchema(schema)) {
return "https://openapi-generator.tech"; return "https://openapi-generator.tech";
// do these last in case the specific types above are derived from these classes // do these last in case the specific types above are derived from these classes
} else if (ModelUtils.isStringSchema(schema)) { } else if (modelUtils.isStringSchema(schema)) {
return "aeiou"; return "aeiou";
} else if (ModelUtils.isIntegerSchema(schema)) { } else if (modelUtils.isIntegerSchema(schema)) {
if (ModelUtils.isLongSchema(schema)) { // long if (modelUtils.isLongSchema(schema)) { // long
return "123456789"; return "123456789";
} else { //integer } else { //integer
return "123"; return "123";

View File

@ -410,12 +410,12 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
schemaType = schemaType.replace("-", "_"); schemaType = schemaType.replace("-", "_");
} }
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getTypeDeclaration(inner) + "_Vectors.Vector"; return getTypeDeclaration(inner) + "_Vectors.Vector";
} }
if (ModelUtils.isMapSchema(p)) { if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
String name = getTypeDeclaration(inner) + "_Map"; String name = getTypeDeclaration(inner) + "_Map";
if (name.startsWith("Swagger.")) { if (name.startsWith("Swagger.")) {
@ -432,7 +432,7 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
return schemaType; return schemaType;
} }
String modelType = toModelName(schemaType).replace("-", "_"); String modelType = toModelName(schemaType).replace("-", "_");
if (ModelUtils.isStringSchema(p) || ModelUtils.isFileSchema(p) if (modelUtils.isStringSchema(p) || modelUtils.isFileSchema(p)
|| languageSpecificPrimitives.contains(modelType)) { || languageSpecificPrimitives.contains(modelType)) {
return modelType; return modelType;
} }
@ -526,8 +526,8 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
ApiResponse methodResponse = findMethodResponse(operation.getResponses()); ApiResponse methodResponse = findMethodResponse(operation.getResponses());
if (methodResponse != null && ModelUtils.getSchemaFromResponse(methodResponse) != null) { if (methodResponse != null && modelUtils.getSchemaFromResponse(methodResponse) != null) {
CodegenProperty cm = fromProperty("response", ModelUtils.getSchemaFromResponse(methodResponse)); CodegenProperty cm = fromProperty("response", modelUtils.getSchemaFromResponse(methodResponse));
op.vendorExtensions.put("x-codegen-response", cm); op.vendorExtensions.put("x-codegen-response", cm);
op.vendorExtensions.put("x-is-model-type", isModelType(cm)); op.vendorExtensions.put("x-is-model-type", isModelType(cm));
op.vendorExtensions.put("x-is-stream-type", isStreamType(cm)); op.vendorExtensions.put("x-is-stream-type", isStreamType(cm));

View File

@ -185,7 +185,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
if (inner == null) { if (inner == null) {
@ -194,7 +194,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
return null; return null;
} }
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
if (inner == null) { if (inner == null) {
@ -217,7 +217,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
final ArraySchema ap = (ArraySchema) p; final ArraySchema ap = (ArraySchema) p;
final String pattern = "new ArrayList<%s>()"; final String pattern = "new ArrayList<%s>()";
if (ap.getItems() == null) { if (ap.getItems() == null) {
@ -225,7 +225,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
} }
return String.format(Locale.ROOT, pattern, getTypeDeclaration(ap.getItems())); return String.format(Locale.ROOT, pattern, getTypeDeclaration(ap.getItems()));
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
final MapSchema ap = (MapSchema) p; final MapSchema ap = (MapSchema) p;
final String pattern = "new HashMap<%s>()"; final String pattern = "new HashMap<%s>()";
if (getAdditionalProperties(ap) == null) { if (getAdditionalProperties(ap) == null) {
@ -233,32 +233,32 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
} }
return String.format(Locale.ROOT, pattern, String.format(Locale.ROOT, "String, %s", getTypeDeclaration(getAdditionalProperties(ap)))); return String.format(Locale.ROOT, pattern, String.format(Locale.ROOT, "String, %s", getTypeDeclaration(getAdditionalProperties(ap))));
} else if (ModelUtils.isLongSchema(p)) { } else if (modelUtils.isLongSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString() + "l"; return p.getDefault().toString() + "l";
} }
return "null"; return "null";
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
return "null"; return "null";
} else if (ModelUtils.isFloatSchema(p)) { } else if (modelUtils.isFloatSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString() + "f"; return p.getDefault().toString() + "f";
} }
return "null"; return "null";
} else if (ModelUtils.isDoubleSchema(p)) { } else if (modelUtils.isDoubleSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString() + "d"; return p.getDefault().toString() + "d";
} }
return "null"; return "null";
} else if (ModelUtils.isBooleanSchema(p)) { } else if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
return "null"; return "null";
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
String _default = (String) p.getDefault(); String _default = (String) p.getDefault();
if (p.getEnum() == null) { if (p.getEnum() == null) {
@ -314,18 +314,18 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
Object obj = p.getExample(); Object obj = p.getExample();
String example = obj == null ? "" : obj.toString(); String example = obj == null ? "" : obj.toString();
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
example = "new " + getTypeDeclaration(p) + "{" + toExampleValue( example = "new " + getTypeDeclaration(p) + "{" + toExampleValue(
((ArraySchema) p).getItems()) + "}"; ((ArraySchema) p).getItems()) + "}";
} else if (ModelUtils.isBooleanSchema(p)) { } else if (modelUtils.isBooleanSchema(p)) {
example = String.valueOf(!"false".equals(example)); example = String.valueOf(!"false".equals(example));
} else if (ModelUtils.isByteArraySchema(p)) { } else if (modelUtils.isByteArraySchema(p)) {
if (example.isEmpty()) { if (example.isEmpty()) {
example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu"; example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu";
} }
p.setExample(example); p.setExample(example);
example = "EncodingUtil.base64Decode('" + example + "')"; example = "EncodingUtil.base64Decode('" + example + "')";
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
if (example.matches("^\\d{4}(-\\d{2}){2}")) { if (example.matches("^\\d{4}(-\\d{2}){2}")) {
example = example.substring(0, 10).replaceAll("-0?", ", "); example = example.substring(0, 10).replaceAll("-0?", ", ");
} else if (example.isEmpty()) { } else if (example.isEmpty()) {
@ -336,7 +336,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
example = "2000, 1, 23"; example = "2000, 1, 23";
} }
example = "Date.newInstance(" + example + ")"; example = "Date.newInstance(" + example + ")";
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
if (example.matches("^\\d{4}([-T:]\\d{2}){5}.+")) { if (example.matches("^\\d{4}([-T:]\\d{2}){5}.+")) {
example = example.substring(0, 19).replaceAll("[-T:]0?", ", "); example = example.substring(0, 19).replaceAll("[-T:]0?", ", ");
} else if (example.isEmpty()) { } else if (example.isEmpty()) {
@ -347,31 +347,31 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
example = "2000, 1, 23, 4, 56, 7"; example = "2000, 1, 23, 4, 56, 7";
} }
example = "Datetime.newInstanceGmt(" + example + ")"; example = "Datetime.newInstanceGmt(" + example + ")";
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
example = example.replaceAll("[^-0-9.]", ""); example = example.replaceAll("[^-0-9.]", "");
example = example.isEmpty() ? "1.3579" : example; example = example.isEmpty() ? "1.3579" : example;
} else if (ModelUtils.isFileSchema(p)) { } else if (modelUtils.isFileSchema(p)) {
if (example.isEmpty()) { if (example.isEmpty()) {
example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu"; example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu";
p.setExample(example); p.setExample(example);
} }
example = "EncodingUtil.base64Decode(" + example + ")"; example = "EncodingUtil.base64Decode(" + example + ")";
} else if (ModelUtils.isEmailSchema(p)) { } else if (modelUtils.isEmailSchema(p)) {
if (example.isEmpty()) { if (example.isEmpty()) {
example = "example@example.com"; example = "example@example.com";
p.setExample(example); p.setExample(example);
} }
example = "'" + example + "'"; example = "'" + example + "'";
} else if (ModelUtils.isLongSchema(p)) { } else if (modelUtils.isLongSchema(p)) {
example = example.isEmpty() ? "123456789L" : example + "L"; example = example.isEmpty() ? "123456789L" : example + "L";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
example = "new " + getTypeDeclaration(p) + "{'key'=>" + toExampleValue(getAdditionalProperties(p)) + "}"; example = "new " + getTypeDeclaration(p) + "{'key'=>" + toExampleValue(getAdditionalProperties(p)) + "}";
} else if (ModelUtils.isPasswordSchema(p)) { } else if (modelUtils.isPasswordSchema(p)) {
example = example.isEmpty() ? "password123" : escapeText(example); example = example.isEmpty() ? "password123" : escapeText(example);
p.setExample(example); p.setExample(example);
example = "'" + example + "'"; example = "'" + example + "'";
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
List<String> enums = p.getEnum(); List<String> enums = p.getEnum();
if (enums != null && example.isEmpty()) { if (enums != null && example.isEmpty()) {
example = enums.get(0); example = enums.get(0);
@ -383,13 +383,13 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
p.setExample(example); p.setExample(example);
} }
example = "'" + example + "'"; example = "'" + example + "'";
} else if (ModelUtils.isUUIDSchema(p)) { } else if (modelUtils.isUUIDSchema(p)) {
example = example.isEmpty() example = example.isEmpty()
? "'046b6c7f-0b8a-43b9-b35d-6489e6daee91'" ? "'046b6c7f-0b8a-43b9-b35d-6489e6daee91'"
: "'" + escapeText(example) + "'"; : "'" + escapeText(example) + "'";
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
example = example.matches("^-?\\d+$") ? example : "0"; example = example.matches("^-?\\d+$") ? example : "0";
} else if (ModelUtils.isObjectSchema(p)) { } else if (modelUtils.isObjectSchema(p)) {
example = example.isEmpty() ? "null" : example; example = example.isEmpty() ? "null" : example;
} else { } else {
example = getTypeDeclaration(p) + ".getExample()"; example = getTypeDeclaration(p) + ".getExample()";
@ -571,7 +571,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
if (op.getHasExamples()) { if (op.getHasExamples()) {
// prepare examples for Apex test classes // prepare examples for Apex test classes
ApiResponse apiResponse = findMethodResponse(operation.getResponses()); ApiResponse apiResponse = findMethodResponse(operation.getResponses());
final Schema responseSchema = ModelUtils.getSchemaFromResponse(apiResponse); final Schema responseSchema = modelUtils.getSchemaFromResponse(apiResponse);
String deserializedExample = toExampleValue(responseSchema); String deserializedExample = toExampleValue(responseSchema);
for (Map<String, String> example : op.examples) { for (Map<String, String> example : op.examples) {
example.put("example", escapeText(example.get("example"))); example.put("example", escapeText(example.get("example")));

View File

@ -437,7 +437,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
private void postProcessEnumRefs(final Map<String, Object> models) { private void postProcessEnumRefs(final Map<String, Object> models) {
Map<String, CodegenModel> enumRefs = new HashMap<String, CodegenModel>(); Map<String, CodegenModel> enumRefs = new HashMap<String, CodegenModel>();
for (Map.Entry<String, Object> entry : models.entrySet()) { for (Map.Entry<String, Object> entry : models.entrySet()) {
CodegenModel model = ModelUtils.getModelByName(entry.getKey(), models); CodegenModel model = modelUtils.getModelByName(entry.getKey(), models);
if (model.isEnum) { if (model.isEnum) {
enumRefs.put(entry.getKey(), model); enumRefs.put(entry.getKey(), model);
} }
@ -445,7 +445,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
for (Map.Entry<String, Object> entry : models.entrySet()) { for (Map.Entry<String, Object> entry : models.entrySet()) {
String openAPIName = entry.getKey(); String openAPIName = entry.getKey();
CodegenModel model = ModelUtils.getModelByName(openAPIName, models); CodegenModel model = modelUtils.getModelByName(openAPIName, models);
if (model != null) { if (model != null) {
for (CodegenProperty var : model.allVars) { for (CodegenProperty var : model.allVars) {
if (enumRefs.containsKey(var.dataType)) { if (enumRefs.containsKey(var.dataType)) {
@ -594,7 +594,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
protected void updateValueTypeProperty(Map<String, Object> models) { protected void updateValueTypeProperty(Map<String, Object> models) {
for (Map.Entry<String, Object> entry : models.entrySet()) { for (Map.Entry<String, Object> entry : models.entrySet()) {
String openAPIName = entry.getKey(); String openAPIName = entry.getKey();
CodegenModel model = ModelUtils.getModelByName(openAPIName, models); CodegenModel model = modelUtils.getModelByName(openAPIName, models);
if (model != null) { if (model != null) {
for (CodegenProperty var : model.vars) { for (CodegenProperty var : model.vars) {
var.vendorExtensions.put("x-is-value-type", isValueType(var)); var.vendorExtensions.put("x-is-value-type", isValueType(var));
@ -611,7 +611,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
protected void updateNullableTypeProperty(Map<String, Object> models) { protected void updateNullableTypeProperty(Map<String, Object> models) {
for (Map.Entry<String, Object> entry : models.entrySet()) { for (Map.Entry<String, Object> entry : models.entrySet()) {
String openAPIName = entry.getKey(); String openAPIName = entry.getKey();
CodegenModel model = ModelUtils.getModelByName(openAPIName, models); CodegenModel model = modelUtils.getModelByName(openAPIName, models);
if (model != null) { if (model != null) {
for (CodegenProperty var : model.vars) { for (CodegenProperty var : model.vars) {
if (!var.isContainer && (nullableType.contains(var.dataType) || var.isEnum)) { if (!var.isContainer && (nullableType.contains(var.dataType) || var.isEnum)) {
@ -859,23 +859,23 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
*/ */
@Override @Override
public String toExampleValue(Schema p) { public String toExampleValue(Schema p) {
if (ModelUtils.isStringSchema(p)) { if (modelUtils.isStringSchema(p)) {
if (p.getExample() != null) { if (p.getExample() != null) {
return "\"" + p.getExample().toString() + "\""; return "\"" + p.getExample().toString() + "\"";
} }
} else if (ModelUtils.isBooleanSchema(p)) { } else if (modelUtils.isBooleanSchema(p)) {
if (p.getExample() != null) { if (p.getExample() != null) {
return p.getExample().toString(); return p.getExample().toString();
} }
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getExample() != null) { if (p.getExample() != null) {
return p.getExample().toString(); return p.getExample().toString();
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getExample() != null) { if (p.getExample() != null) {
return p.getExample().toString(); return p.getExample().toString();
} }
@ -891,33 +891,33 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
*/ */
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\""; return "\"" + p.getDefault().toString() + "\"";
} }
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\""; return "\"" + p.getDefault().toString() + "\"";
} }
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (ModelUtils.isFloatSchema(p)) { // float if (modelUtils.isFloatSchema(p)) { // float
return p.getDefault().toString() + "F"; return p.getDefault().toString() + "F";
} else if (ModelUtils.isDoubleSchema(p)) { // double } else if (modelUtils.isDoubleSchema(p)) { // double
return p.getDefault().toString() + "D"; return p.getDefault().toString() + "D";
} else { // decimal } else { // decimal
return p.getDefault().toString() + "M"; return p.getDefault().toString() + "M";
} }
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
String _default = (String) p.getDefault(); String _default = (String) p.getDefault();
if (p.getEnum() == null) { if (p.getEnum() == null) {
@ -989,7 +989,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
@Override @Override
public String toInstantiationType(Schema p) { public String toInstantiationType(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
return getArrayTypeDeclaration((ArraySchema) p); return getArrayTypeDeclaration((ArraySchema) p);
} }
return super.toInstantiationType(p); return super.toInstantiationType(p);
@ -997,9 +997,9 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
return getArrayTypeDeclaration((ArraySchema) p); return getArrayTypeDeclaration((ArraySchema) p);
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
// Should we also support maps of maps? // Should we also support maps of maps?
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "<string, " + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<string, " + getTypeDeclaration(inner) + ">";

View File

@ -326,7 +326,7 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides()); URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());
String port = URLPathUtils.getPort(url, ""); String port = URLPathUtils.getPort(url, "");
String host = url.getHost(); String host = url.getHost();
@ -362,7 +362,7 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg
public Map<String, Object> postProcessAllModels(Map<String, Object> objs){ public Map<String, Object> postProcessAllModels(Map<String, Object> objs){
Map<String, Object> models = super.postProcessAllModels(objs); Map<String, Object> models = super.postProcessAllModels(objs);
for (final Entry<String, Object> model : models.entrySet()) { for (final Entry<String, Object> model : models.entrySet()) {
CodegenModel mo = ModelUtils.getModelByName(model.getKey(), models); CodegenModel mo = modelUtils.getModelByName(model.getKey(), models);
addForwardDeclarations(mo, models); addForwardDeclarations(mo, models);
} }
return models; return models;
@ -379,7 +379,7 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg
} }
String childPropertyType = property.isContainer? property.mostInnerItems.baseType : property.baseType; String childPropertyType = property.isContainer? property.mostInnerItems.baseType : property.baseType;
for(final Entry<String, Object> mo : objs.entrySet()) { for(final Entry<String, Object> mo : objs.entrySet()) {
CodegenModel childModel = ModelUtils.getModelByName(mo.getKey(), objs); CodegenModel childModel = modelUtils.getModelByName(mo.getKey(), objs);
if( !childPropertyType.equals(childModel.classname) || childPropertyType.equals(parentModel.classname) || !childModel.hasVars ){ if( !childPropertyType.equals(childModel.classname) || childPropertyType.equals(parentModel.classname) || !childModel.hasVars ){
continue; continue;
} }

View File

@ -292,11 +292,11 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return "LIST [" + getTypeDeclaration(inner) + "]"; return "LIST [" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + " [" + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + " [" + getTypeDeclaration(inner) + "]";
@ -463,7 +463,7 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
private void postProcessParentModels(final Map<String, Object> models) { private void postProcessParentModels(final Map<String, Object> models) {
for (final String parent : parentModels) { for (final String parent : parentModels) {
final CodegenModel parentModel = ModelUtils.getModelByName(parent, models); final CodegenModel parentModel = modelUtils.getModelByName(parent, models);
final Collection<CodegenModel> childrenModels = childrenByParent.get(parent); final Collection<CodegenModel> childrenModels = childrenByParent.get(parent);
for (final CodegenModel child : childrenModels) { for (final CodegenModel child : childrenModels) {
processParentPropertiesInChildModel(parentModel, child); processParentPropertiesInChildModel(parentModel, child);
@ -492,7 +492,7 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
@Override @Override
public CodegenModel fromModel(String name, Schema model) { public CodegenModel fromModel(String name, Schema model) {
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI); Map<String, Schema> allDefinitions = modelUtils.getSchemas();
CodegenModel codegenModel = super.fromModel(name, model); CodegenModel codegenModel = super.fromModel(name, model);
if (allDefinitions != null && codegenModel.parentSchema != null && codegenModel.hasEnums) { if (allDefinitions != null && codegenModel.parentSchema != null && codegenModel.hasEnums) {
final Schema parentModel = allDefinitions.get(codegenModel.parentSchema); final Schema parentModel = allDefinitions.get(codegenModel.parentSchema);
@ -571,7 +571,7 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
@Override @Override
public String toInstantiationType(Schema p) { public String toInstantiationType(Schema p) {
return getTypeDeclaration(p); return getTypeDeclaration(p);
// if (ModelUtils.isMapSchema(p)) { // if (modelUtils.isMapSchema(p)) {
// Schema additionalProperties2 = getAdditionalProperties(p); // Schema additionalProperties2 = getAdditionalProperties(p);
// String type = additionalProperties2.getType(); // String type = additionalProperties2.getType();
// if (null == type) { // if (null == type) {
@ -580,7 +580,7 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
// } // }
// String inner = toModelName(getSchemaType(additionalProperties2)); // String inner = toModelName(getSchemaType(additionalProperties2));
// return instantiationTypes.get("map") + " [" + inner + "]"; // return instantiationTypes.get("map") + " [" + inner + "]";
// } else if (ModelUtils.isArraySchema(p)) { // } else if (modelUtils.isArraySchema(p)) {
// ArraySchema ap = (ArraySchema) p; // ArraySchema ap = (ArraySchema) p;
// String inner = toModelName(getSchemaType(ap.getItems())); // String inner = toModelName(getSchemaType(ap.getItems()));
// return instantiationTypes.get("array") + " [" + inner + "]"; // return instantiationTypes.get("array") + " [" + inner + "]";

View File

@ -358,7 +358,7 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
List<String> classNames = new ArrayList<String>(); List<String> classNames = new ArrayList<String>();
for (String k : objs.keySet()) { for (String k : objs.keySet()) {
CodegenModel model = ModelUtils.getModelByName(k, objs); CodegenModel model = modelUtils.getModelByName(k, objs);
if (model == null || model.classname == null) { if (model == null || model.classname == null) {
throw new RuntimeException("Null model encountered"); throw new RuntimeException("Null model encountered");
} }
@ -405,7 +405,7 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
private void postProcessEnumRefs(final Map<String, Object> models) { private void postProcessEnumRefs(final Map<String, Object> models) {
Map<String, CodegenModel> enumRefs = new HashMap<String, CodegenModel>(); Map<String, CodegenModel> enumRefs = new HashMap<String, CodegenModel>();
for (Map.Entry<String, Object> entry : models.entrySet()) { for (Map.Entry<String, Object> entry : models.entrySet()) {
CodegenModel model = ModelUtils.getModelByName(entry.getKey(), models); CodegenModel model = modelUtils.getModelByName(entry.getKey(), models);
if (model.isEnum) { if (model.isEnum) {
enumRefs.put(entry.getKey(), model); enumRefs.put(entry.getKey(), model);
} }
@ -413,7 +413,7 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
for (Map.Entry<String, Object> entry : models.entrySet()) { for (Map.Entry<String, Object> entry : models.entrySet()) {
String openAPIName = entry.getKey(); String openAPIName = entry.getKey();
CodegenModel model = ModelUtils.getModelByName(openAPIName, models); CodegenModel model = modelUtils.getModelByName(openAPIName, models);
if (model != null) { if (model != null) {
for (CodegenProperty var : model.allVars) { for (CodegenProperty var : model.allVars) {
if (enumRefs.containsKey(var.dataType)) { if (enumRefs.containsKey(var.dataType)) {
@ -735,23 +735,23 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
*/ */
@Override @Override
public String toExampleValue(Schema p) { public String toExampleValue(Schema p) {
if (ModelUtils.isStringSchema(p)) { if (modelUtils.isStringSchema(p)) {
if (p.getExample() != null) { if (p.getExample() != null) {
return "\"" + p.getExample().toString() + "\""; return "\"" + p.getExample().toString() + "\"";
} }
} else if (ModelUtils.isBooleanSchema(p)) { } else if (modelUtils.isBooleanSchema(p)) {
if (p.getExample() != null) { if (p.getExample() != null) {
return p.getExample().toString(); return p.getExample().toString();
} }
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getExample() != null) { if (p.getExample() != null) {
return p.getExample().toString(); return p.getExample().toString();
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getExample() != null) { if (p.getExample() != null) {
return p.getExample().toString(); return p.getExample().toString();
} }
@ -768,33 +768,33 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
*/ */
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\""; return "\"" + p.getDefault().toString() + "\"";
} }
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\""; return "\"" + p.getDefault().toString() + "\"";
} }
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (ModelUtils.isFloatSchema(p)) { // float if (modelUtils.isFloatSchema(p)) { // float
return p.getDefault().toString() + "F"; return p.getDefault().toString() + "F";
} else if (ModelUtils.isDoubleSchema(p)) { // double } else if (modelUtils.isDoubleSchema(p)) { // double
return p.getDefault().toString() + "D"; return p.getDefault().toString() + "D";
} else { // decimal } else { // decimal
return p.getDefault().toString() + "M"; return p.getDefault().toString() + "M";
} }
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
String _default = (String) p.getDefault(); String _default = (String) p.getDefault();
if (p.getEnum() == null) { if (p.getEnum() == null) {
@ -817,7 +817,7 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
public String getNullableType(Schema p, String type) { public String getNullableType(Schema p, String type) {
if (languageSpecificPrimitives.contains(type)) { if (languageSpecificPrimitives.contains(type)) {
if (isSupportNullable() && ModelUtils.isNullable(p) && nullableType.contains(type)) { if (isSupportNullable() && modelUtils.isNullable(p) && nullableType.contains(type)) {
return type + " option"; return type + " option";
} else { } else {
return type; return type;
@ -869,7 +869,7 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
@Override @Override
public String toInstantiationType(Schema p) { public String toInstantiationType(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
return getArrayTypeDeclaration((ArraySchema) p); return getArrayTypeDeclaration((ArraySchema) p);
} }
return super.toInstantiationType(p); return super.toInstantiationType(p);
@ -877,9 +877,9 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
return getArrayTypeDeclaration((ArraySchema) p); return getArrayTypeDeclaration((ArraySchema) p);
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
// Should we also support maps of maps? // Should we also support maps of maps?
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "<string, " + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<string, " + getTypeDeclaration(inner) + ">";

View File

@ -17,6 +17,7 @@
package org.openapitools.codegen.languages; package org.openapitools.codegen.languages;
import com.sun.org.apache.xpath.internal.operations.Mod;
import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FilenameUtils;
@ -330,7 +331,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
*/ */
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
// In OAS 3.0.x, the array "items" attribute is required. // In OAS 3.0.x, the array "items" attribute is required.
@ -338,7 +339,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
// specification is aligned with the JSON schema specification. // specification is aligned with the JSON schema specification.
// When "items" is not specified, the elements of the array may be anything at all. // When "items" is not specified, the elements of the array may be anything at all.
if (inner != null) { if (inner != null) {
inner = ModelUtils.unaliasSchema(this.openAPI, inner); inner = modelUtils.unaliasSchema(inner);
} }
String typDecl; String typDecl;
if (inner != null) { if (inner != null) {
@ -347,9 +348,9 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
typDecl = "interface{}"; typDecl = "interface{}";
} }
return "[]" + typDecl; return "[]" + typDecl;
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[string]" + getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, inner)); return getSchemaType(p) + "[string]" + getTypeDeclaration(modelUtils.unaliasSchema(inner));
} }
//return super.getTypeDeclaration(p); //return super.getTypeDeclaration(p);
@ -394,7 +395,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
if (ref != null && !ref.isEmpty()) { if (ref != null && !ref.isEmpty()) {
type = openAPIType; type = openAPIType;
} else if ("object".equals(openAPIType) && isAnyTypeSchema(p)) { } else if ("object".equals(openAPIType) && modelUtils.isAnyTypeSchema(p)) {
// Arbitrary type. Note this is not the same thing as free-form object. // Arbitrary type. Note this is not the same thing as free-form object.
type = "interface{}"; type = "interface{}";
} else if (typeMapping.containsKey(openAPIType)) { } else if (typeMapping.containsKey(openAPIType)) {
@ -425,9 +426,9 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
*/ */
@Override @Override
public String toInstantiationType(Schema property) { public String toInstantiationType(Schema property) {
if (ModelUtils.isMapSchema(property)) { if (modelUtils.isMapSchema(property)) {
return getTypeDeclaration(property); return getTypeDeclaration(property);
} else if (ModelUtils.isArraySchema(property)) { } else if (modelUtils.isArraySchema(property)) {
return getTypeDeclaration(property); return getTypeDeclaration(property);
} }
return super.toInstantiationType(property); return super.toInstantiationType(property);

View File

@ -266,11 +266,11 @@ public abstract class AbstractGraphQLCodegen extends DefaultCodegen implements C
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]"; return "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = (Schema) p.getAdditionalProperties(); Schema inner = (Schema) p.getAdditionalProperties();
return getTypeDeclaration(inner); return getTypeDeclaration(inner);
} }
@ -278,7 +278,7 @@ public abstract class AbstractGraphQLCodegen extends DefaultCodegen implements C
// Not using the supertype invocation, because we want to UpperCamelize // Not using the supertype invocation, because we want to UpperCamelize
// the type. // the type.
String schemaType = getSchemaType(p); String schemaType = getSchemaType(p);
String nullable = ModelUtils.isNullable(p) ? "" : "!"; String nullable = modelUtils.isNullable(p) ? "" : "!";
/* /*
if (p != null && Boolean.TRUE.equals(p.getNullable())) { if (p != null && Boolean.TRUE.equals(p.getNullable())) {
nullable = ""; nullable = "";

View File

@ -794,13 +794,13 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
Schema<?> schema = ModelUtils.unaliasSchema(this.openAPI, p, importMapping); Schema<?> schema = modelUtils.unaliasSchema(p, importMapping);
Schema<?> target = ModelUtils.isGenerateAliasAsModel() ? p : schema; Schema<?> target = modelUtils.isGenerateAliasAsModel() ? p : schema;
if (ModelUtils.isArraySchema(target)) { if (modelUtils.isArraySchema(target)) {
Schema<?> items = getSchemaItems((ArraySchema) schema); Schema<?> items = getSchemaItems((ArraySchema) schema);
return getSchemaType(target) + "<" + getTypeDeclaration(items) + ">"; return getSchemaType(target) + "<" + getTypeDeclaration(items) + ">";
} else if (ModelUtils.isMapSchema(target)) { } else if (modelUtils.isMapSchema(target)) {
// Note: ModelUtils.isMapSchema(p) returns true when p is a composed schema that also defines // Note: modelUtils.isMapSchema(p) returns true when p is a composed schema that also defines
// additionalproperties: true // additionalproperties: true
Schema<?> inner = getAdditionalProperties(target); Schema<?> inner = getAdditionalProperties(target);
if (inner == null) { if (inner == null) {
@ -823,10 +823,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override @Override
public String toDefaultValue(Schema schema) { public String toDefaultValue(Schema schema) {
schema = ModelUtils.getReferencedSchema(this.openAPI, schema); schema = modelUtils.getReferencedSchema(schema);
if (ModelUtils.isArraySchema(schema)) { if (modelUtils.isArraySchema(schema)) {
final String pattern; final String pattern;
if (ModelUtils.isSet(schema)) { if (modelUtils.isSet(schema)) {
String mapInstantiationType = instantiationTypes().getOrDefault("set", "LinkedHashSet"); String mapInstantiationType = instantiationTypes().getOrDefault("set", "LinkedHashSet");
pattern = "new " + mapInstantiationType + "<%s>()"; pattern = "new " + mapInstantiationType + "<%s>()";
} else { } else {
@ -836,7 +836,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
Schema<?> items = getSchemaItems((ArraySchema) schema); Schema<?> items = getSchemaItems((ArraySchema) schema);
String typeDeclaration = getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, items)); String typeDeclaration = getTypeDeclaration(modelUtils.unaliasSchema(items));
Object java8obj = additionalProperties.get("java8"); Object java8obj = additionalProperties.get("java8");
if (java8obj != null) { if (java8obj != null) {
Boolean java8 = Boolean.valueOf(java8obj.toString()); Boolean java8 = Boolean.valueOf(java8obj.toString());
@ -846,7 +846,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} }
return String.format(Locale.ROOT, pattern, typeDeclaration); return String.format(Locale.ROOT, pattern, typeDeclaration);
} else if (ModelUtils.isMapSchema(schema) && !(schema instanceof ComposedSchema)) { } else if (modelUtils.isMapSchema(schema) && !(schema instanceof ComposedSchema)) {
if (schema.getProperties() != null && schema.getProperties().size() > 0) { if (schema.getProperties() != null && schema.getProperties().size() > 0) {
// object is complex object with free-form additional properties // object is complex object with free-form additional properties
if (schema.getDefault() != null) { if (schema.getDefault() != null) {
@ -872,7 +872,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} }
return String.format(Locale.ROOT, pattern, typeDeclaration); return String.format(Locale.ROOT, pattern, typeDeclaration);
} else if (ModelUtils.isIntegerSchema(schema)) { } else if (modelUtils.isIntegerSchema(schema)) {
if (schema.getDefault() != null) { if (schema.getDefault() != null) {
if (SchemaTypeUtil.INTEGER64_FORMAT.equals(schema.getFormat())) { if (SchemaTypeUtil.INTEGER64_FORMAT.equals(schema.getFormat())) {
return schema.getDefault().toString() + "l"; return schema.getDefault().toString() + "l";
@ -881,7 +881,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} }
} }
return null; return null;
} else if (ModelUtils.isNumberSchema(schema)) { } else if (modelUtils.isNumberSchema(schema)) {
if (schema.getDefault() != null) { if (schema.getDefault() != null) {
if (SchemaTypeUtil.FLOAT_FORMAT.equals(schema.getFormat())) { if (SchemaTypeUtil.FLOAT_FORMAT.equals(schema.getFormat())) {
return schema.getDefault().toString() + "f"; return schema.getDefault().toString() + "f";
@ -892,17 +892,17 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} }
} }
return null; return null;
} else if (ModelUtils.isBooleanSchema(schema)) { } else if (modelUtils.isBooleanSchema(schema)) {
if (schema.getDefault() != null) { if (schema.getDefault() != null) {
return schema.getDefault().toString(); return schema.getDefault().toString();
} }
return null; return null;
} else if (ModelUtils.isURISchema(schema)) { } else if (modelUtils.isURISchema(schema)) {
if (schema.getDefault() != null) { if (schema.getDefault() != null) {
return "URI.create(\"" + escapeText((String) schema.getDefault()) + "\")"; return "URI.create(\"" + escapeText((String) schema.getDefault()) + "\")";
} }
return null; return null;
} else if (ModelUtils.isStringSchema(schema)) { } else if (modelUtils.isStringSchema(schema)) {
if (schema.getDefault() != null) { if (schema.getDefault() != null) {
String _default; String _default;
if (schema.getDefault() instanceof Date) { if (schema.getDefault() instanceof Date) {
@ -923,7 +923,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} }
} }
return null; return null;
} else if (ModelUtils.isObjectSchema(schema)) { } else if (modelUtils.isObjectSchema(schema)) {
if (schema.getDefault() != null) { if (schema.getDefault() != null) {
return super.toDefaultValue(schema); return super.toDefaultValue(schema);
} }
@ -1100,7 +1100,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override @Override
public CodegenModel fromModel(String name, Schema model) { public CodegenModel fromModel(String name, Schema model) {
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI); Map<String, Schema> allDefinitions = modelUtils.getSchemas();
CodegenModel codegenModel = super.fromModel(name, model); CodegenModel codegenModel = super.fromModel(name, model);
if (codegenModel.description != null) { if (codegenModel.description != null) {
codegenModel.imports.add("ApiModel"); codegenModel.imports.add("ApiModel");
@ -1200,8 +1200,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
if (openAPI == null) { if (openAPI == null) {
return; return;
} }
@ -1213,13 +1213,13 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} }
for (Operation operation : path.readOperations()) { for (Operation operation : path.readOperations()) {
LOGGER.info("Processing operation " + operation.getOperationId()); LOGGER.info("Processing operation " + operation.getOperationId());
if (hasBodyParameter(openAPI, operation) || hasFormParameter(openAPI, operation)) { if (hasBodyParameter(operation) || hasFormParameter(operation)) {
String defaultContentType = hasFormParameter(openAPI, operation) ? "application/x-www-form-urlencoded" : "application/json"; String defaultContentType = hasFormParameter(operation) ? "application/x-www-form-urlencoded" : "application/json";
List<String> consumes = new ArrayList<>(getConsumesInfo(openAPI, operation)); List<String> consumes = new ArrayList<>(getConsumesInfo(operation));
String contentType = consumes == null || consumes.isEmpty() ? defaultContentType : consumes.get(0); String contentType = consumes == null || consumes.isEmpty() ? defaultContentType : consumes.get(0);
operation.addExtension("x-contentType", contentType); operation.addExtension("x-contentType", contentType);
} }
String accepts = getAccept(openAPI, operation); String accepts = getAccept(operation);
operation.addExtension("x-accepts", accepts); operation.addExtension("x-accepts", accepts);
} }
@ -1271,10 +1271,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} }
} }
private static String getAccept(OpenAPI openAPI, Operation operation) { private String getAccept(Operation operation) {
String accepts = null; String accepts = null;
String defaultContentType = "application/json"; String defaultContentType = "application/json";
Set<String> producesInfo = getProducesInfo(openAPI, operation); Set<String> producesInfo = getProducesInfo(operation);
if (producesInfo != null && !producesInfo.isEmpty()) { if (producesInfo != null && !producesInfo.isEmpty()) {
ArrayList<String> produces = new ArrayList<>(producesInfo); ArrayList<String> produces = new ArrayList<>(producesInfo);
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();

View File

@ -127,8 +127,8 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
/* TODO there should be no need for the following logic /* TODO there should be no need for the following logic
if ("/".equals(swagger.getBasePath())) { if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath(""); swagger.setBasePath("");

View File

@ -310,13 +310,13 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
*/ */
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
Schema<?> schema = ModelUtils.unaliasSchema(this.openAPI, p, importMapping); Schema<?> schema = modelUtils.unaliasSchema(p, importMapping);
Schema<?> target = ModelUtils.isGenerateAliasAsModel() ? p : schema; Schema<?> target = modelUtils.isGenerateAliasAsModel() ? p : schema;
if (ModelUtils.isArraySchema(target)) { if (modelUtils.isArraySchema(target)) {
Schema<?> items = getSchemaItems((ArraySchema) schema); Schema<?> items = getSchemaItems((ArraySchema) schema);
return getSchemaType(target) + "<" + getTypeDeclaration(items) + ">"; return getSchemaType(target) + "<" + getTypeDeclaration(items) + ">";
} else if (ModelUtils.isMapSchema(target)) { } else if (modelUtils.isMapSchema(target)) {
// Note: ModelUtils.isMapSchema(p) returns true when p is a composed schema that also defines // Note: modelUtils.isMapSchema(p) returns true when p is a composed schema that also defines
// additionalproperties: true // additionalproperties: true
Schema<?> inner = getAdditionalProperties(target); Schema<?> inner = getAdditionalProperties(target);
if (inner == null) { if (inner == null) {
@ -899,27 +899,27 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isURISchema(p)) { } else if (modelUtils.isURISchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "URI.create('" + p.getDefault() + "')"; return "URI.create('" + p.getDefault() + "')";
} }
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "\"" + p.getDefault() + "\""; return "\"" + p.getDefault() + "\"";
} }

View File

@ -293,7 +293,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
if (inner == null) { if (inner == null) {
@ -301,7 +301,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
inner = new StringSchema().description("TODO default missing array inner type to string"); inner = new StringSchema().description("TODO default missing array inner type to string");
} }
return getTypeDeclaration(inner) + "[]"; return getTypeDeclaration(inner) + "[]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
if (inner == null) { if (inner == null) {
LOGGER.warn(p.getName() + "(map property) does not have a proper inner type defined. Default to string"); LOGGER.warn(p.getName() + "(map property) does not have a proper inner type defined. Default to string");
@ -514,23 +514,23 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
*/ */
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "'" + p.getDefault() + "'"; return "'" + p.getDefault() + "'";
} }

View File

@ -345,11 +345,11 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[str, " + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[str, " + getTypeDeclaration(inner) + "]";
} }
@ -372,7 +372,7 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
// need vendor extensions for x-openapi-router-controller // need vendor extensions for x-openapi-router-controller
Map<String, PathItem> paths = openAPI.getPaths(); Map<String, PathItem> paths = openAPI.getPaths();
if (paths != null) { if (paths != null) {
@ -704,26 +704,26 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
*/ */
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (p.getDefault().toString().equalsIgnoreCase("false")) if (p.getDefault().toString().equalsIgnoreCase("false"))
return "False"; return "False";
else else
return "True"; return "True";
} }
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "'" + (String) p.getDefault() + "'"; return "'" + (String) p.getDefault() + "'";
} }

View File

@ -114,10 +114,10 @@ abstract public class AbstractRubyCodegen extends DefaultCodegen implements Code
@Override @Override
public String getTypeDeclaration(Schema schema) { public String getTypeDeclaration(Schema schema) {
if (ModelUtils.isArraySchema(schema)) { if (modelUtils.isArraySchema(schema)) {
Schema inner = ((ArraySchema) schema).getItems(); Schema inner = ((ArraySchema) schema).getItems();
return getSchemaType(schema) + "<" + getTypeDeclaration(inner) + ">"; return getSchemaType(schema) + "<" + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(schema)) { } else if (modelUtils.isMapSchema(schema)) {
Schema inner = getAdditionalProperties(schema); Schema inner = getAdditionalProperties(schema);
return getSchemaType(schema) + "<String, " + getTypeDeclaration(inner) + ">"; return getSchemaType(schema) + "<String, " + getTypeDeclaration(inner) + ">";
} }
@ -127,11 +127,11 @@ abstract public class AbstractRubyCodegen extends DefaultCodegen implements Code
@Override @Override
public String toInstantiationType(Schema schema) { public String toInstantiationType(Schema schema) {
if (ModelUtils.isMapSchema(schema)) { if (modelUtils.isMapSchema(schema)) {
return instantiationTypes.get("map"); return instantiationTypes.get("map");
} else if (ModelUtils.isArraySchema(schema)) { } else if (modelUtils.isArraySchema(schema)) {
String parentType; String parentType;
if (ModelUtils.isSet(schema)) { if (modelUtils.isSet(schema)) {
parentType = "set"; parentType = "set";
} else { } else {
parentType = "array"; parentType = "array";
@ -143,12 +143,12 @@ abstract public class AbstractRubyCodegen extends DefaultCodegen implements Code
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
p = ModelUtils.getReferencedSchema(this.openAPI, p); p = modelUtils.getReferencedSchema(p);
if (ModelUtils.isIntegerSchema(p) || ModelUtils.isNumberSchema(p) || ModelUtils.isBooleanSchema(p)) { if (modelUtils.isIntegerSchema(p) || modelUtils.isNumberSchema(p) || modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (p.getDefault() instanceof Date) { if (p.getDefault() instanceof Date) {
Date date = (Date) p.getDefault(); Date date = (Date) p.getDefault();

View File

@ -320,11 +320,11 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]";
@ -335,7 +335,7 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
@Override @Override
public String getSchemaType(Schema p) { public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p); String openAPIType = super.getSchemaType(p);
if (ModelUtils.isSet(p)) { if (modelUtils.isSet(p)) {
openAPIType = "set"; openAPIType = "set";
} }
@ -353,13 +353,13 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
@Override @Override
public String toInstantiationType(Schema p) { public String toInstantiationType(Schema p) {
if (ModelUtils.isMapSchema(p)) { if (modelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p)); String inner = getSchemaType(getAdditionalProperties(p));
return instantiationTypes.get("map") + "[String, " + inner + "]"; return instantiationTypes.get("map") + "[String, " + inner + "]";
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems()); String inner = getSchemaType(ap.getItems());
return ( ModelUtils.isSet(ap) ? instantiationTypes.get("set") : instantiationTypes.get("array") ) + "[" + inner + "]"; return ( modelUtils.isSet(ap) ? instantiationTypes.get("set") : instantiationTypes.get("array") ) + "[" + inner + "]";
} else { } else {
return null; return null;
} }
@ -372,24 +372,24 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
} }
// comment out the following as the default value is no handled differently // comment out the following as the default value is no handled differently
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
return null; return null;
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
return null; return null;
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
return null; return null;
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
return null; return null;
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
return null; return null;
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p)); String inner = getSchemaType(getAdditionalProperties(p));
return "new HashMap[String, " + inner + "]() "; return "new HashMap[String, " + inner + "]() ";
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems()); String inner = getSchemaType(ap.getItems());
String genericType; String genericType;
if (ModelUtils.isSet(ap)) { if (modelUtils.isSet(ap)) {
genericType = instantiationTypes.get("set"); genericType = instantiationTypes.get("set");
} else { } else {
genericType = instantiationTypes.get("array"); genericType = instantiationTypes.get("array");
@ -410,7 +410,7 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
// Assume that any other generic types can be new'd up. // Assume that any other generic types can be new'd up.
return "new " + genericType + "[" + inner + "]() "; return "new " + genericType + "[" + inner + "]() ";
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
return null; return null;
} else { } else {
return null; return null;
@ -427,9 +427,9 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
@Override @Override
public CodegenProperty fromProperty(String name, Schema p) { public CodegenProperty fromProperty(String name, Schema p) {
CodegenProperty prop = super.fromProperty(name, p); CodegenProperty prop = super.fromProperty(name, p);
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema as = (ArraySchema) p; ArraySchema as = (ArraySchema) p;
if (ModelUtils.isSet(as)) { if (modelUtils.isSet(as)) {
prop.containerType = "set"; prop.containerType = "set";
} }
} }

View File

@ -269,7 +269,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
if (additionalProperties.containsKey(NPM_NAME)) { if (additionalProperties.containsKey(NPM_NAME)) {
@ -413,16 +413,16 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
Schema<?> items = getSchemaItems((ArraySchema) p); Schema<?> items = getSchemaItems((ArraySchema) p);
return getSchemaType(p) + "<" + getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, items)) + ">"; return getSchemaType(p) + "<" + getTypeDeclaration(modelUtils.unaliasSchema(items)) + ">";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema<?> inner = getSchemaAdditionalProperties(p); Schema<?> inner = getSchemaAdditionalProperties(p);
String nullSafeSuffix = getNullSafeAdditionalProps() ? " | undefined" : ""; String nullSafeSuffix = getNullSafeAdditionalProps() ? " | undefined" : "";
return "{ [key: string]: " + getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, inner)) + nullSafeSuffix + "; }"; return "{ [key: string]: " + getTypeDeclaration(modelUtils.unaliasSchema(inner)) + nullSafeSuffix + "; }";
} else if (ModelUtils.isFileSchema(p)) { } else if (modelUtils.isFileSchema(p)) {
return "any"; return "any";
} else if (ModelUtils.isBinarySchema(p)) { } else if (modelUtils.isBinarySchema(p)) {
return "any"; return "any";
} }
return super.getTypeDeclaration(p); return super.getTypeDeclaration(p);
@ -432,37 +432,37 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
protected String getParameterDataType(Parameter parameter, Schema p) { protected String getParameterDataType(Parameter parameter, Schema p) {
// handle enums of various data types // handle enums of various data types
Schema inner; Schema inner;
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema mp1 = (ArraySchema) p; ArraySchema mp1 = (ArraySchema) p;
inner = mp1.getItems(); inner = mp1.getItems();
return this.getSchemaType(p) + "<" + this.getParameterDataType(parameter, inner) + ">"; return this.getSchemaType(p) + "<" + this.getParameterDataType(parameter, inner) + ">";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
inner = getAdditionalProperties(p); inner = getAdditionalProperties(p);
return "{ [key: string]: " + this.getParameterDataType(parameter, inner) + "; }"; return "{ [key: string]: " + this.getParameterDataType(parameter, inner) + "; }";
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
// Handle string enums // Handle string enums
if (p.getEnum() != null) { if (p.getEnum() != null) {
return enumValuesToEnumTypeUnion(p.getEnum(), "string"); return enumValuesToEnumTypeUnion(p.getEnum(), "string");
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
// Handle integer enums // Handle integer enums
if (p.getEnum() != null) { if (p.getEnum() != null) {
return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum())); return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum()));
} }
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
// Handle double enums // Handle double enums
if (p.getEnum() != null) { if (p.getEnum() != null) {
return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum())); return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum()));
} }
} }
/* TODO revise the logic below /* TODO revise the logic below
else if (ModelUtils.isDateSchema(p)) { else if (modelUtils.isDateSchema(p)) {
// Handle date enums // Handle date enums
DateSchema sp = (DateSchema) p; DateSchema sp = (DateSchema) p;
if (sp.getEnum() != null) { if (sp.getEnum() != null) {
return enumValuesToEnumTypeUnion(sp.getEnum(), "string"); return enumValuesToEnumTypeUnion(sp.getEnum(), "string");
} }
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
// Handle datetime enums // Handle datetime enums
DateTimeSchema sp = (DateTimeSchema) p; DateTimeSchema sp = (DateTimeSchema) p;
if (sp.getEnum() != null) { if (sp.getEnum() != null) {
@ -510,27 +510,27 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
return UNDEFINED_VALUE; return UNDEFINED_VALUE;
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
return UNDEFINED_VALUE; return UNDEFINED_VALUE;
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
return UNDEFINED_VALUE; return UNDEFINED_VALUE;
} else if (ModelUtils.isNumberSchema(p) || ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isNumberSchema(p) || modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
return UNDEFINED_VALUE; return UNDEFINED_VALUE;
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "'" + (String) p.getDefault() + "'"; return "'" + (String) p.getDefault() + "'";
} }
@ -551,7 +551,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
public String getSchemaType(Schema p) { public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p); String openAPIType = super.getSchemaType(p);
String type = null; String type = null;
if (ModelUtils.isComposedSchema(p)) { if (modelUtils.isComposedSchema(p)) {
return openAPIType; return openAPIType;
} else if (typeMapping.containsKey(openAPIType)) { } else if (typeMapping.containsKey(openAPIType)) {
type = typeMapping.get(openAPIType); type = typeMapping.get(openAPIType);
@ -898,7 +898,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
return filteredSchemas.stream().map(schema -> { return filteredSchemas.stream().map(schema -> {
String schemaType = getSchemaType(schema); String schemaType = getSchemaType(schema);
if (ModelUtils.isArraySchema(schema)) { if (modelUtils.isArraySchema(schema)) {
ArraySchema ap = (ArraySchema) schema; ArraySchema ap = (ArraySchema) schema;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
schemaType = schemaType + "<" + getSchemaType(inner) + ">"; schemaType = schemaType + "<" + getSchemaType(inner) + ">";

View File

@ -223,11 +223,11 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "<String, " + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<String, " + getTypeDeclaration(inner) + ">";

View File

@ -158,7 +158,7 @@ public class ApexClientCodegen extends AbstractApexCodegen {
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
String calloutLabel = openAPI.getInfo().getTitle(); String calloutLabel = openAPI.getInfo().getTitle();
if (StringUtils.isNotBlank(namedCredential)) { if (StringUtils.isNotBlank(namedCredential)) {
calloutLabel = namedCredential; calloutLabel = namedCredential;
@ -221,24 +221,24 @@ public class ApexClientCodegen extends AbstractApexCodegen {
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
String out = null; String out = null;
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
Schema inner = ((ArraySchema) p).getItems(); Schema inner = ((ArraySchema) p).getItems();
out = String.format( out = String.format(
Locale.ROOT, Locale.ROOT,
"new List<%s>()", "new List<%s>()",
inner == null ? "Object" : getTypeDeclaration(inner) inner == null ? "Object" : getTypeDeclaration(inner)
); );
} else if (ModelUtils.isBooleanSchema(p)) { } else if (modelUtils.isBooleanSchema(p)) {
// true => "true", false => "false", null => "null" // true => "true", false => "false", null => "null"
out = String.valueOf(p.getDefault()); out = String.valueOf(p.getDefault());
} else if (ModelUtils.isLongSchema(p)) { } else if (modelUtils.isLongSchema(p)) {
Long def = (Long) p.getDefault(); Long def = (Long) p.getDefault();
out = def == null ? out : def.toString() + "L"; out = def == null ? out : def.toString() + "L";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
String s = inner == null ? "Object" : getTypeDeclaration(inner); String s = inner == null ? "Object" : getTypeDeclaration(inner);
out = String.format(Locale.ROOT, "new Map<String, %s>()", s); out = String.format(Locale.ROOT, "new Map<String, %s>()", s);
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
String def = p.getDefault().toString(); String def = p.getDefault().toString();
if (def != null) { if (def != null) {

View File

@ -359,14 +359,14 @@ public class AsciidocDocumentationCodegen extends DefaultCodegen implements Code
} }
@Override @Override
public void processOpenAPI(OpenAPI openAPI) { public void processOpenAPI() {
if (this.includeSpecMarkupLambda != null) { if (this.includeSpecMarkupLambda != null) {
LOGGER.debug("specs: " + ": " + this.includeSpecMarkupLambda.resetCounter()); LOGGER.debug("specs: " + ": " + this.includeSpecMarkupLambda.resetCounter());
} }
if (this.includeSnippetMarkupLambda != null) { if (this.includeSnippetMarkupLambda != null) {
LOGGER.debug("snippets: " + ": " + this.includeSnippetMarkupLambda.resetCounter()); LOGGER.debug("snippets: " + ": " + this.includeSnippetMarkupLambda.resetCounter());
} }
super.processOpenAPI(openAPI); super.processOpenAPI();
} }
} }

View File

@ -304,8 +304,8 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides()); URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());
additionalProperties.put("serverHost", url.getHost()); additionalProperties.put("serverHost", url.getHost());
additionalProperties.put("serverPort", URLPathUtils.getPort(url, 8080)); additionalProperties.put("serverPort", URLPathUtils.getPort(url, 8080));
@ -450,7 +450,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
@Override @Override
public String getNullableType(Schema p, String type) { public String getNullableType(Schema p, String type) {
if (languageSpecificPrimitives.contains(type)) { if (languageSpecificPrimitives.contains(type)) {
if (isSupportNullable() && ModelUtils.isNullable(p) && nullableType.contains(type)) { if (isSupportNullable() && modelUtils.isNullable(p) && nullableType.contains(type)) {
return type + "?"; return type + "?";
} else { } else {
return type; return type;

View File

@ -423,11 +423,11 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
*/ */
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]";
} }
@ -619,7 +619,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public CodegenOperation fromOperation(String path, String httpMethod, public CodegenOperation fromOperation(String path, String httpMethod,
Operation operation, List<Server> servers) { Operation operation, List<Server> servers) {
Map<String, Schema> definitions = ModelUtils.getSchemas(this.openAPI); Map<String, Schema> definitions = modelUtils.getSchemas();
CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers);
/** /**
@ -663,8 +663,8 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
* If the operation produces Json and has nonempty example * If the operation produces Json and has nonempty example
* try to reformat it. * try to reformat it.
*/ */
if (getConsumesInfo(this.openAPI, operation) != null if (getConsumesInfo(operation) != null
&& getConsumesInfo(this.openAPI, operation).contains("application/json") && getConsumesInfo(operation).contains("application/json")
&& definitions.get(p.dataType).getExample() != null) { && definitions.get(p.dataType).getExample() != null) {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
@ -697,8 +697,8 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
* @param openAPI [description] * @param openAPI [description]
*/ */
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
/* TODO need to revise the logic below /* TODO need to revise the logic below
if ("/".equals(openAPI.getServers())) { if ("/".equals(openAPI.getServers())) {

View File

@ -296,10 +296,10 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
@Override @Override
public String getTypeDeclaration(Schema schema) { public String getTypeDeclaration(Schema schema) {
/* comment out below as we'll do it in the template instead /* comment out below as we'll do it in the template instead
if (ModelUtils.isArraySchema(schema)) { if (modelUtils.isArraySchema(schema)) {
Schema inner = ((ArraySchema) schema).getItems(); Schema inner = ((ArraySchema) schema).getItems();
return getSchemaType(schema) + "<" + getTypeDeclaration(inner) + ">"; return getSchemaType(schema) + "<" + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(schema)) { } else if (modelUtils.isMapSchema(schema)) {
Schema inner = (Schema) schema.getAdditionalProperties(); Schema inner = (Schema) schema.getAdditionalProperties();
return getSchemaType(schema) + "<String, " + getTypeDeclaration(inner) + ">"; return getSchemaType(schema) + "<String, " + getTypeDeclaration(inner) + ">";
} }
@ -310,11 +310,11 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isIntegerSchema(p) || ModelUtils.isNumberSchema(p) || ModelUtils.isBooleanSchema(p)) { if (modelUtils.isIntegerSchema(p) || modelUtils.isNumberSchema(p) || modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "'" + escapeText((String) p.getDefault()) + "'"; return "'" + escapeText((String) p.getDefault()) + "'";
} }
@ -327,17 +327,17 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
public String toExampleValue(Schema schema) { public String toExampleValue(Schema schema) {
String example = super.toExampleValue(schema); String example = super.toExampleValue(schema);
if (ModelUtils.isNullType(schema) && null != example) { if (modelUtils.isNullType(schema) && null != example) {
// The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x, // The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x,
// though this tooling supports it. // though this tooling supports it.
return "NULL"; return "NULL";
} }
// correct "&#39;"s into "'"s after toString() // correct "&#39;"s into "'"s after toString()
if (ModelUtils.isStringSchema(schema) && schema.getDefault() != null) { if (modelUtils.isStringSchema(schema) && schema.getDefault() != null) {
example = (String) schema.getDefault(); example = (String) schema.getDefault();
} }
if (StringUtils.isNotBlank(example) && !"null".equals(example)) { if (StringUtils.isNotBlank(example) && !"null".equals(example)) {
if (ModelUtils.isStringSchema(schema)) { if (modelUtils.isStringSchema(schema)) {
example = "\"" + example + "\""; example = "\"" + example + "\"";
} }
return example; return example;
@ -346,7 +346,7 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
if (schema.getEnum() != null && !schema.getEnum().isEmpty()) { if (schema.getEnum() != null && !schema.getEnum().isEmpty()) {
// Enum case: // Enum case:
example = schema.getEnum().get(0).toString(); example = schema.getEnum().get(0).toString();
/* if (ModelUtils.isStringSchema(schema)) { /* if (modelUtils.isStringSchema(schema)) {
example = "'" + escapeText(example) + "'"; example = "'" + escapeText(example) + "'";
}*/ }*/
if (null == example) if (null == example)
@ -355,8 +355,8 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
return example; return example;
} else if (null != schema.get$ref()) { } else if (null != schema.get$ref()) {
// $ref case: // $ref case:
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI); Map<String, Schema> allDefinitions = modelUtils.getSchemas();
String ref = ModelUtils.getSimpleRef(schema.get$ref()); String ref = modelUtils.getSimpleRef(schema.get$ref());
if (allDefinitions != null) { if (allDefinitions != null) {
Schema refSchema = allDefinitions.get(ref); Schema refSchema = allDefinitions.get(ref);
if (null == refSchema) { if (null == refSchema) {
@ -372,18 +372,18 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
LOGGER.warn("allDefinitions not defined in toExampleValue!\n"); LOGGER.warn("allDefinitions not defined in toExampleValue!\n");
} }
} }
if (ModelUtils.isDateSchema(schema)) { if (modelUtils.isDateSchema(schema)) {
example = "\"2013-10-20\""; example = "\"2013-10-20\"";
return example; return example;
} else if (ModelUtils.isDateTimeSchema(schema)) { } else if (modelUtils.isDateTimeSchema(schema)) {
example = "\"2013-10-20T19:20:30+01:00\""; example = "\"2013-10-20T19:20:30+01:00\"";
return example; return example;
} else if (ModelUtils.isBinarySchema(schema)) { } else if (modelUtils.isBinarySchema(schema)) {
example = "instantiate_binary_t(\"blah\", 5)"; example = "instantiate_binary_t(\"blah\", 5)";
return example; return example;
} else if (ModelUtils.isByteArraySchema(schema)) { } else if (modelUtils.isByteArraySchema(schema)) {
example = "YQ=="; example = "YQ==";
} else if (ModelUtils.isStringSchema(schema)) { } else if (modelUtils.isStringSchema(schema)) {
// decimal (type: string, format: decimal) // decimal (type: string, format: decimal)
if ("number".equalsIgnoreCase(schema.getFormat())) { if ("number".equalsIgnoreCase(schema.getFormat())) {
return "1"; return "1";
@ -398,29 +398,29 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
example = ""; example = "";
for (int i = 0; i < len; i++) for (int i = 0; i < len; i++)
example += i; example += i;
} else if (ModelUtils.isIntegerSchema(schema)) { } else if (modelUtils.isIntegerSchema(schema)) {
if (schema.getMinimum() != null) if (schema.getMinimum() != null)
example = schema.getMinimum().toString(); example = schema.getMinimum().toString();
else else
example = "56"; example = "56";
} else if (ModelUtils.isNumberSchema(schema)) { } else if (modelUtils.isNumberSchema(schema)) {
if (schema.getMinimum() != null) if (schema.getMinimum() != null)
example = schema.getMinimum().toString(); example = schema.getMinimum().toString();
else else
example = "1.337"; example = "1.337";
} else if (ModelUtils.isBooleanSchema(schema)) { } else if (modelUtils.isBooleanSchema(schema)) {
example = "1"; example = "1";
} else if (ModelUtils.isArraySchema(schema)) { } else if (modelUtils.isArraySchema(schema)) {
example = "list_create()"; example = "list_create()";
} else if (ModelUtils.isMapSchema(schema)) { } else if (modelUtils.isMapSchema(schema)) {
example = "list_create()"; example = "list_create()";
} else if (ModelUtils.isObjectSchema(schema)) { } else if (modelUtils.isObjectSchema(schema)) {
return null; // models are managed at moustache level return null; // models are managed at moustache level
} else { } else {
LOGGER.warn("Type " + schema.getType() + " not handled properly in toExampleValue"); LOGGER.warn("Type " + schema.getType() + " not handled properly in toExampleValue");
} }
if (ModelUtils.isStringSchema(schema)) { if (modelUtils.isStringSchema(schema)) {
example = "\"" + escapeText(example) + "\""; example = "\"" + escapeText(example) + "\"";
} }
@ -716,7 +716,7 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
if (openAPI.getInfo() != null) { if (openAPI.getInfo() != null) {
Info info = openAPI.getInfo(); Info info = openAPI.getInfo();
setProjectName((escapeText(info.getTitle()))); setProjectName((escapeText(info.getTitle())));
@ -744,7 +744,7 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
@Override @Override
public CodegenProperty fromProperty(String name, Schema p) { public CodegenProperty fromProperty(String name, Schema p) {
CodegenProperty cm = super.fromProperty(name, p); CodegenProperty cm = super.fromProperty(name, p);
Schema ref = ModelUtils.getReferencedSchema(openAPI, p); Schema ref = modelUtils.getReferencedSchema(p);
if (ref != null) { if (ref != null) {
if (ref.getEnum() != null) { if (ref.getEnum() != null) {
cm.isEnum = true; cm.isEnum = true;

View File

@ -588,7 +588,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
@Override @Override
public CodegenModel fromModel(String name, Schema model) { public CodegenModel fromModel(String name, Schema model) {
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI); Map<String, Schema> allDefinitions = modelUtils.getSchemas();
CodegenModel codegenModel = super.fromModel(name, model); CodegenModel codegenModel = super.fromModel(name, model);
if (allDefinitions != null && codegenModel != null && codegenModel.parent != null) { if (allDefinitions != null && codegenModel != null && codegenModel.parent != null) {
final Schema parentModel = allDefinitions.get(toModelName(codegenModel.parent)); final Schema parentModel = allDefinitions.get(toModelName(codegenModel.parent));
@ -965,14 +965,14 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
*/ */
@Override @Override
public String toInstantiationType(Schema schema) { public String toInstantiationType(Schema schema) {
if (ModelUtils.isMapSchema(schema)) { if (modelUtils.isMapSchema(schema)) {
Schema additionalProperties = getAdditionalProperties(schema); Schema additionalProperties = getAdditionalProperties(schema);
String inner = getSchemaType(additionalProperties); String inner = getSchemaType(additionalProperties);
if (ModelUtils.isMapSchema(additionalProperties)) { if (modelUtils.isMapSchema(additionalProperties)) {
inner = toInstantiationType(additionalProperties); inner = toInstantiationType(additionalProperties);
} }
return instantiationTypes.get("map") + "<String, " + inner + ">"; return instantiationTypes.get("map") + "<String, " + inner + ">";
} else if (ModelUtils.isArraySchema(schema)) { } else if (modelUtils.isArraySchema(schema)) {
ArraySchema arraySchema = (ArraySchema) schema; ArraySchema arraySchema = (ArraySchema) schema;
String inner = getSchemaType(arraySchema.getItems()); String inner = getSchemaType(arraySchema.getItems());
return instantiationTypes.get("array") + "<" + inner + ">"; return instantiationTypes.get("array") + "<" + inner + ">";
@ -984,7 +984,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
@Override @Override
public String getNullableType(Schema p, String type) { public String getNullableType(Schema p, String type) {
if (languageSpecificPrimitives.contains(type)) { if (languageSpecificPrimitives.contains(type)) {
if (isSupportNullable() && ModelUtils.isNullable(p) && nullableType.contains(type)) { if (isSupportNullable() && modelUtils.isNullable(p) && nullableType.contains(type)) {
return type + "?"; return type + "?";
} else { } else {
return type; return type;

View File

@ -51,7 +51,7 @@ public class CSharpNancyFXServerCodegen extends AbstractCSharpCodegen {
private static final String PACKAGE_CONTEXT = "packageContext"; private static final String PACKAGE_CONTEXT = "packageContext";
private static final String ASYNC_SERVER = "asyncServer"; private static final String ASYNC_SERVER = "asyncServer";
private static final Map<String, Predicate<Schema>> propertyToOpenAPITypeMapping = private final Map<String, Predicate<Schema>> propertyToOpenAPITypeMapping =
createPropertyToOpenAPITypeMapping(); createPropertyToOpenAPITypeMapping();
private String packageGuid = "{" + randomUUID().toString().toUpperCase(Locale.ROOT) + "}"; private String packageGuid = "{" + randomUUID().toString().toUpperCase(Locale.ROOT) + "}";
@ -270,7 +270,7 @@ public class CSharpNancyFXServerCodegen extends AbstractCSharpCodegen {
private void postProcessParentModels(final Map<String, Object> models) { private void postProcessParentModels(final Map<String, Object> models) {
LOGGER.debug("Processing parents: " + parentModels); LOGGER.debug("Processing parents: " + parentModels);
for (final String parent : parentModels) { for (final String parent : parentModels) {
final CodegenModel parentModel = ModelUtils.getModelByName(parent, models); final CodegenModel parentModel = modelUtils.getModelByName(parent, models);
if (parentModel != null) { if (parentModel != null) {
parentModel.hasChildren = true; parentModel.hasChildren = true;
final Collection<CodegenModel> childrenModels = childrenByParent.get(parent); final Collection<CodegenModel> childrenModels = childrenByParent.get(parent);
@ -373,7 +373,7 @@ public class CSharpNancyFXServerCodegen extends AbstractCSharpCodegen {
} }
@Override @Override
public void preprocessOpenAPI(final OpenAPI openAPI) { public void preprocessOpenAPI() {
URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides()); URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());
String path = URLPathUtils.getPath(url, "/"); String path = URLPathUtils.getPath(url, "/");
final String packageContextOption = (String) additionalProperties.get(PACKAGE_CONTEXT); final String packageContextOption = (String) additionalProperties.get(PACKAGE_CONTEXT);
@ -397,17 +397,17 @@ public class CSharpNancyFXServerCodegen extends AbstractCSharpCodegen {
return super.getSchemaType(property); return super.getSchemaType(property);
} }
private static Map<String, Predicate<Schema>> createPropertyToOpenAPITypeMapping() { private Map<String, Predicate<Schema>> createPropertyToOpenAPITypeMapping() {
final ImmutableMap.Builder<String, Predicate<Schema>> mapping = ImmutableMap.builder(); final ImmutableMap.Builder<String, Predicate<Schema>> mapping = ImmutableMap.builder();
mapping.put("time", timeProperty()); mapping.put("time", timeProperty());
return mapping.build(); return mapping.build();
} }
private static Predicate<Schema> timeProperty() { private Predicate<Schema> timeProperty() {
return new Predicate<Schema>() { return new Predicate<Schema>() {
@Override @Override
public boolean apply(Schema property) { public boolean apply(Schema property) {
return ModelUtils.isStringSchema(property) && "time".equalsIgnoreCase(property.getFormat()); return modelUtils.isStringSchema(property) && "time".equalsIgnoreCase(property.getFormat());
} }
}; };
} }

View File

@ -306,7 +306,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
@Override @Override
public CodegenModel fromModel(String name, Schema model) { public CodegenModel fromModel(String name, Schema model) {
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI); Map<String, Schema> allDefinitions = modelUtils.getSchemas();
CodegenModel codegenModel = super.fromModel(name, model); CodegenModel codegenModel = super.fromModel(name, model);
if (allDefinitions != null && codegenModel != null && codegenModel.parent != null) { if (allDefinitions != null && codegenModel != null && codegenModel.parent != null) {
final Schema parentModel = allDefinitions.get(toModelName(codegenModel.parent)); final Schema parentModel = allDefinitions.get(toModelName(codegenModel.parent));
@ -401,7 +401,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
@Override @Override
public String getNullableType(Schema p, String type) { public String getNullableType(Schema p, String type) {
if (languageSpecificPrimitives.contains(type)) { if (languageSpecificPrimitives.contains(type)) {
if (isSupportNullable() && ModelUtils.isNullable(p) && nullableType.contains(type)) { if (isSupportNullable() && modelUtils.isNullable(p) && nullableType.contains(type)) {
return type + "?"; return type + "?";
} else { } else {
return type; return type;
@ -968,14 +968,14 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
*/ */
@Override @Override
public String toInstantiationType(Schema schema) { public String toInstantiationType(Schema schema) {
if (ModelUtils.isMapSchema(schema)) { if (modelUtils.isMapSchema(schema)) {
Schema additionalProperties = getAdditionalProperties(schema); Schema additionalProperties = getAdditionalProperties(schema);
String inner = getSchemaType(additionalProperties); String inner = getSchemaType(additionalProperties);
if (ModelUtils.isMapSchema(additionalProperties)) { if (modelUtils.isMapSchema(additionalProperties)) {
inner = toInstantiationType(additionalProperties); inner = toInstantiationType(additionalProperties);
} }
return instantiationTypes.get("map") + "<String, " + inner + ">"; return instantiationTypes.get("map") + "<String, " + inner + ">";
} else if (ModelUtils.isArraySchema(schema)) { } else if (modelUtils.isArraySchema(schema)) {
ArraySchema arraySchema = (ArraySchema) schema; ArraySchema arraySchema = (ArraySchema) schema;
String inner = getSchemaType(arraySchema.getItems()); String inner = getSchemaType(arraySchema.getItems());
return instantiationTypes.get("array") + "<" + inner + ">"; return instantiationTypes.get("array") + "<" + inner + ">";

View File

@ -168,7 +168,7 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return "(s/coll-of " + getTypeDeclaration(inner) + ")"; return "(s/coll-of " + getTypeDeclaration(inner) + ")";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = (Schema) p.getAdditionalProperties(); Schema inner = (Schema) p.getAdditionalProperties();
return "(s/map-of string? " + getTypeDeclaration(inner) + ")"; return "(s/map-of string? " + getTypeDeclaration(inner) + ")";
@ -216,8 +216,8 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
if (additionalProperties.containsKey(PROJECT_NAME)) { if (additionalProperties.containsKey(PROJECT_NAME)) {
projectName = ((String) additionalProperties.get(PROJECT_NAME)); projectName = ((String) additionalProperties.get(PROJECT_NAME));

View File

@ -102,11 +102,11 @@ public class ConfluenceWikiCodegen extends DefaultCodegen implements CodegenConf
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]";
} }

View File

@ -229,7 +229,7 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen {
ApiResponse apiResponse = findMethodResponse(operation.getResponses()); ApiResponse apiResponse = findMethodResponse(operation.getResponses());
if (apiResponse != null) { if (apiResponse != null) {
Schema response = ModelUtils.getSchemaFromResponse(apiResponse); Schema response = modelUtils.getSchemaFromResponse(apiResponse);
if (response != null) { if (response != null) {
CodegenProperty cm = fromProperty("response", response); CodegenProperty cm = fromProperty("response", response);
op.vendorExtensions.put("x-codegen-response", cm); op.vendorExtensions.put("x-codegen-response", cm);
@ -350,20 +350,20 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen {
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
String openAPIType = getSchemaType(p); String openAPIType = getSchemaType(p);
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} }
if (ModelUtils.isMapSchema(p)) { if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "<std::string, " + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<std::string, " + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isByteArraySchema(p)) { } else if (modelUtils.isByteArraySchema(p)) {
return "std::string"; return "std::string";
} }
if (ModelUtils.isStringSchema(p) if (modelUtils.isStringSchema(p)
|| ModelUtils.isDateSchema(p) || modelUtils.isDateSchema(p)
|| ModelUtils.isDateTimeSchema(p) || ModelUtils.isFileSchema(p) || modelUtils.isDateTimeSchema(p) || modelUtils.isFileSchema(p)
|| languageSpecificPrimitives.contains(openAPIType)) { || languageSpecificPrimitives.contains(openAPIType)) {
return toModelName(openAPIType); return toModelName(openAPIType);
} }
@ -373,34 +373,34 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen {
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
return "false"; return "false";
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
return "\"\""; return "\"\"";
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
return "\"\""; return "\"\"";
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (ModelUtils.isFloatSchema(p)) { if (modelUtils.isFloatSchema(p)) {
return "0.0f"; return "0.0f";
} }
return "0.0"; return "0.0";
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (ModelUtils.isLongSchema(p)) { if (modelUtils.isLongSchema(p)) {
return "0L"; return "0L";
} }
return "0"; return "0";
} else if (ModelUtils.isByteArraySchema(p)) { } else if (modelUtils.isByteArraySchema(p)) {
return "\"\""; return "\"\"";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p)); String inner = getSchemaType(getAdditionalProperties(p));
return "std::map<std::string, " + inner + ">()"; return "std::map<std::string, " + inner + ">()";
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems()); String inner = getSchemaType(ap.getItems());
return "std::vector<" + inner + ">()"; return "std::vector<" + inner + ">()";
} else if (!StringUtils.isEmpty(p.get$ref())) { // model } else if (!StringUtils.isEmpty(p.get$ref())) { // model
return toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()"; return toModelName(modelUtils.getSimpleRef(p.get$ref())) + "()";
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
return "\"\""; return "\"\"";
} }

View File

@ -181,16 +181,16 @@ public class CppQt5AbstractCodegen extends AbstractCppCodegen implements Codegen
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
String openAPIType = getSchemaType(p); String openAPIType = getSchemaType(p);
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "<QString, " + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<QString, " + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isBinarySchema(p)) { } else if (modelUtils.isBinarySchema(p)) {
return getSchemaType(p); return getSchemaType(p);
} else if (ModelUtils.isFileSchema(p)) { } else if (modelUtils.isFileSchema(p)) {
return getSchemaType(p); return getSchemaType(p);
} }
if (foundationClasses.contains(openAPIType)) { if (foundationClasses.contains(openAPIType)) {
@ -205,33 +205,33 @@ public class CppQt5AbstractCodegen extends AbstractCppCodegen implements Codegen
@Override @Override
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
return "false"; return "false";
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
return "NULL"; return "NULL";
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
return "NULL"; return "NULL";
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (SchemaTypeUtil.FLOAT_FORMAT.equals(p.getFormat())) { if (SchemaTypeUtil.FLOAT_FORMAT.equals(p.getFormat())) {
return "0.0f"; return "0.0f";
} }
return "0.0"; return "0.0";
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (SchemaTypeUtil.INTEGER64_FORMAT.equals(p.getFormat())) { if (SchemaTypeUtil.INTEGER64_FORMAT.equals(p.getFormat())) {
return "0L"; return "0L";
} }
return "0"; return "0";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return "QMap<QString, " + getTypeDeclaration(inner) + ">()"; return "QMap<QString, " + getTypeDeclaration(inner) + ">()";
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return "QList<" + getTypeDeclaration(inner) + ">()"; return "QList<" + getTypeDeclaration(inner) + ">()";
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
return "QString(\"\")"; return "QString(\"\")";
} else if (!StringUtils.isEmpty(p.get$ref())) { } else if (!StringUtils.isEmpty(p.get$ref())) {
return toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()"; return toModelName(modelUtils.getSimpleRef(p.get$ref())) + "()";
} }
return "NULL"; return "NULL";
} }

View File

@ -27,7 +27,6 @@ import io.swagger.v3.oas.models.servers.Server;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*; import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.features.*; import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.utils.ModelUtils;
import java.util.*; import java.util.*;
@ -271,8 +270,8 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
ApiResponse methodResponse = findMethodResponse(operation.getResponses()); ApiResponse methodResponse = findMethodResponse(operation.getResponses());
if (methodResponse != null) { if (methodResponse != null) {
Schema response = ModelUtils.getSchemaFromResponse(methodResponse); Schema response = modelUtils.getSchemaFromResponse(methodResponse);
response = ModelUtils.unaliasSchema(this.openAPI, response, importMapping); response = modelUtils.unaliasSchema(response, importMapping);
if (response != null) { if (response != null) {
CodegenProperty cm = fromProperty("response", response); CodegenProperty cm = fromProperty("response", response);
op.vendorExtensions.put("x-codegen-response", cm); op.vendorExtensions.put("x-codegen-response", cm);
@ -344,18 +343,18 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
String openAPIType = getSchemaType(p); String openAPIType = getSchemaType(p);
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "<utility::string_t, " + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<utility::string_t, " + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isFileSchema(p) || ModelUtils.isBinarySchema(p)) { } else if (modelUtils.isFileSchema(p) || modelUtils.isBinarySchema(p)) {
return "std::shared_ptr<" + openAPIType + ">"; return "std::shared_ptr<" + openAPIType + ">";
} else if (ModelUtils.isStringSchema(p) } else if (modelUtils.isStringSchema(p)
|| ModelUtils.isDateSchema(p) || ModelUtils.isDateTimeSchema(p) || modelUtils.isDateSchema(p) || modelUtils.isDateTimeSchema(p)
|| ModelUtils.isFileSchema(p) || ModelUtils.isUUIDSchema(p) || modelUtils.isFileSchema(p) || modelUtils.isUUIDSchema(p)
|| languageSpecificPrimitives.contains(openAPIType)) { || languageSpecificPrimitives.contains(openAPIType)) {
return toModelName(openAPIType); return toModelName(openAPIType);
} }
@ -365,26 +364,26 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
return "false"; return "false";
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
return "utility::datetime()"; return "utility::datetime()";
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
return "utility::datetime()"; return "utility::datetime()";
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (ModelUtils.isFloatSchema(p)) { if (modelUtils.isFloatSchema(p)) {
return "0.0f"; return "0.0f";
} }
return "0.0"; return "0.0";
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (ModelUtils.isLongSchema(p)) { if (modelUtils.isLongSchema(p)) {
return "0L"; return "0L";
} }
return "0"; return "0";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p)); String inner = getSchemaType(getAdditionalProperties(p));
return "std::map<utility::string_t, " + inner + ">()"; return "std::map<utility::string_t, " + inner + ">()";
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems()); String inner = getSchemaType(ap.getItems());
if (!languageSpecificPrimitives.contains(inner)) { if (!languageSpecificPrimitives.contains(inner)) {
@ -392,10 +391,10 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
} }
return "std::vector<" + inner + ">()"; return "std::vector<" + inner + ">()";
} else if (!StringUtils.isEmpty(p.get$ref())) { } else if (!StringUtils.isEmpty(p.get$ref())) {
return "new " + toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()"; return "new " + toModelName(modelUtils.getSimpleRef(p.get$ref())) + "()";
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
return "utility::conversions::to_string_t(\"\")"; return "utility::conversions::to_string_t(\"\")";
} else if (isFreeFormObject(p)) { } else if (modelUtils.isFreeFormObject(p)) {
return "new Object()"; return "new Object()";
} }
@ -446,7 +445,7 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
private void postProcessParentModels(final Map<String, Object> models) { private void postProcessParentModels(final Map<String, Object> models) {
for (final String parent : parentModels) { for (final String parent : parentModels) {
final CodegenModel parentModel = ModelUtils.getModelByName(parent, models); final CodegenModel parentModel = modelUtils.getModelByName(parent, models);
final Collection<CodegenModel> childrenModels = childrenByParent.get(parent); final Collection<CodegenModel> childrenModels = childrenByParent.get(parent);
for (final CodegenModel child : childrenModels) { for (final CodegenModel child : childrenModels) {
processParentPropertiesInChildModel(parentModel, child); processParentPropertiesInChildModel(parentModel, child);

View File

@ -345,18 +345,18 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen {
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
String openAPIType = getSchemaType(p); String openAPIType = getSchemaType(p);
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "<std::string, " + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<std::string, " + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isByteArraySchema(p)) { } else if (modelUtils.isByteArraySchema(p)) {
return "std::string"; return "std::string";
} else if (ModelUtils.isStringSchema(p) } else if (modelUtils.isStringSchema(p)
|| ModelUtils.isDateSchema(p) || modelUtils.isDateSchema(p)
|| ModelUtils.isDateTimeSchema(p) || ModelUtils.isFileSchema(p) || modelUtils.isDateTimeSchema(p) || modelUtils.isFileSchema(p)
|| languageSpecificPrimitives.contains(openAPIType)) { || languageSpecificPrimitives.contains(openAPIType)) {
return toModelName(openAPIType); return toModelName(openAPIType);
} }
@ -366,32 +366,32 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen {
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isStringSchema(p)) { if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\""; return "\"" + p.getDefault().toString() + "\"";
} else { } else {
return "\"\""; return "\"\"";
} }
} else if (ModelUtils.isBooleanSchema(p)) { } else if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} else { } else {
return "false"; return "false";
} }
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\""; return "\"" + p.getDefault().toString() + "\"";
} else { } else {
return "\"\""; return "\"\"";
} }
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\""; return "\"" + p.getDefault().toString() + "\"";
} else { } else {
return "\"\""; return "\"\"";
} }
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (ModelUtils.isFloatSchema(p)) { // float if (modelUtils.isFloatSchema(p)) { // float
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString() + "f"; return p.getDefault().toString() + "f";
} else { } else {
@ -404,8 +404,8 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen {
return "0.0"; return "0.0";
} }
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (ModelUtils.isLongSchema(p)) { // long if (modelUtils.isLongSchema(p)) { // long
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString() + "L"; return p.getDefault().toString() + "L";
} else { } else {
@ -418,16 +418,16 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen {
return "0"; return "0";
} }
} }
} else if (ModelUtils.isByteArraySchema(p)) { } else if (modelUtils.isByteArraySchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\""; return "\"" + p.getDefault().toString() + "\"";
} else { } else {
return "\"\""; return "\"\"";
} }
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p)); String inner = getSchemaType(getAdditionalProperties(p));
return "std::map<std::string, " + inner + ">()"; return "std::map<std::string, " + inner + ">()";
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems()); String inner = getSchemaType(ap.getItems());
if (!languageSpecificPrimitives.contains(inner)) { if (!languageSpecificPrimitives.contains(inner)) {
@ -435,7 +435,7 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen {
} }
return "std::vector<" + inner + ">()"; return "std::vector<" + inner + ">()";
} else if (!StringUtils.isEmpty(p.get$ref())) { } else if (!StringUtils.isEmpty(p.get$ref())) {
return "std::make_shared<" + toModelName(ModelUtils.getSimpleRef(p.get$ref())) + ">()"; return "std::make_shared<" + toModelName(modelUtils.getSimpleRef(p.get$ref())) + ">()";
} }
return "nullptr"; return "nullptr";

View File

@ -161,9 +161,9 @@ public class CppTizenClientCodegen extends AbstractCppCodegen implements Codegen
@Override @Override
public String toInstantiationType(Schema p) { public String toInstantiationType(Schema p) {
if (ModelUtils.isMapSchema(p)) { if (modelUtils.isMapSchema(p)) {
return instantiationTypes.get("map"); return instantiationTypes.get("map");
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
return instantiationTypes.get("array"); return instantiationTypes.get("array");
} else { } else {
return null; return null;
@ -232,28 +232,28 @@ public class CppTizenClientCodegen extends AbstractCppCodegen implements Codegen
//Might not be needed //Might not be needed
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
return "bool(false)"; return "bool(false)";
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (SchemaTypeUtil.FLOAT_FORMAT.equals(p.getFormat())) { if (SchemaTypeUtil.FLOAT_FORMAT.equals(p.getFormat())) {
return "float(0)"; return "float(0)";
} }
return "double(0)"; return "double(0)";
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (SchemaTypeUtil.INTEGER64_FORMAT.equals(p.getFormat())) { if (SchemaTypeUtil.INTEGER64_FORMAT.equals(p.getFormat())) {
return "long(0)"; return "long(0)";
} }
return "int(0)"; return "int(0)";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
return "new std::map()"; return "new std::map()";
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
return "new std::list()"; return "new std::list()";
} else if (!StringUtils.isEmpty(p.get$ref())) { } else if (!StringUtils.isEmpty(p.get$ref())) {
return "new " + toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()"; return "new " + toModelName(modelUtils.getSimpleRef(p.get$ref())) + "()";
} else if (ModelUtils.isDateSchema(p) || ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateSchema(p) || modelUtils.isDateTimeSchema(p)) {
return "null"; return "null";
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
return "std::string()"; return "std::string()";
} }
return "null"; return "null";

View File

@ -379,11 +379,11 @@ public class CppUE4ClientCodegen extends AbstractCppCodegen {
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
String openAPIType = getSchemaType(p); String openAPIType = getSchemaType(p);
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems()); String inner = getSchemaType(ap.getItems());
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p)); String inner = getSchemaType(getAdditionalProperties(p));
return getSchemaType(p) + "<FString, " + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<FString, " + getTypeDeclaration(inner) + ">";
} }
@ -404,41 +404,41 @@ public class CppUE4ClientCodegen extends AbstractCppCodegen {
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isStringSchema(p)) { if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "TEXT(\"" + p.getDefault().toString() + "\")"; return "TEXT(\"" + p.getDefault().toString() + "\")";
} else { } else {
return null; return null;
} }
} else if (ModelUtils.isBooleanSchema(p)) { } else if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} else { } else {
return "false"; return "false";
} }
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
return "FDateTime(0)"; return "FDateTime(0)";
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
return "FDateTime(0)"; return "FDateTime(0)";
} else if (ModelUtils.isDoubleSchema(p)) { } else if (modelUtils.isDoubleSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} else { } else {
return "0.0"; return "0.0";
} }
} else if (ModelUtils.isFloatSchema(p)) { } else if (modelUtils.isFloatSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} else { } else {
return "0.0f"; return "0.0f";
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} else { } else {
return "0"; return "0";
} }
} else if (ModelUtils.isLongSchema(p)) { } else if (modelUtils.isLongSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} else { } else {

View File

@ -412,14 +412,14 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String toDefaultValue(Schema schema) { public String toDefaultValue(Schema schema) {
if (ModelUtils.isMapSchema(schema)) { if (modelUtils.isMapSchema(schema)) {
return "const {}"; return "const {}";
} else if (ModelUtils.isArraySchema(schema)) { } else if (modelUtils.isArraySchema(schema)) {
return "const []"; return "const []";
} }
if (schema.getDefault() != null) { if (schema.getDefault() != null) {
if (ModelUtils.isStringSchema(schema)) { if (modelUtils.isStringSchema(schema)) {
return "'" + schema.getDefault().toString().replaceAll("'", "\\'") + "'"; return "'" + schema.getDefault().toString().replaceAll("'", "\\'") + "'";
} }
return schema.getDefault().toString(); return schema.getDefault().toString();
@ -430,11 +430,11 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "<String, " + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<String, " + getTypeDeclaration(inner) + ">";

View File

@ -118,14 +118,14 @@ public class DartDioClientCodegen extends DartClientCodegen {
@Override @Override
public String toDefaultValue(Schema schema) { public String toDefaultValue(Schema schema) {
if (ModelUtils.isMapSchema(schema)) { if (modelUtils.isMapSchema(schema)) {
return "const {}"; return "const {}";
} else if (ModelUtils.isArraySchema(schema)) { } else if (modelUtils.isArraySchema(schema)) {
return "const []"; return "const []";
} }
if (schema.getDefault() != null) { if (schema.getDefault() != null) {
if (ModelUtils.isStringSchema(schema)) { if (modelUtils.isStringSchema(schema)) {
return "'" + schema.getDefault().toString().replaceAll("'", "\\'") + "'"; return "'" + schema.getDefault().toString().replaceAll("'", "\\'") + "'";
} }
return schema.getDefault().toString(); return schema.getDefault().toString();

View File

@ -132,14 +132,14 @@ public class DartJaguarClientCodegen extends DartClientCodegen {
@Override @Override
public String toDefaultValue(Schema schema) { public String toDefaultValue(Schema schema) {
if (ModelUtils.isMapSchema(schema)) { if (modelUtils.isMapSchema(schema)) {
return "const {}"; return "const {}";
} else if (ModelUtils.isArraySchema(schema)) { } else if (modelUtils.isArraySchema(schema)) {
return "const []"; return "const []";
} }
if (schema.getDefault() != null) { if (schema.getDefault() != null) {
if (ModelUtils.isStringSchema(schema)) { if (modelUtils.isStringSchema(schema)) {
return "'" + schema.getDefault().toString().replaceAll("'", "\\'") + "'"; return "'" + schema.getDefault().toString().replaceAll("'", "\\'") + "'";
} }
return schema.getDefault().toString(); return schema.getDefault().toString();

View File

@ -264,7 +264,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
Info info = openAPI.getInfo(); Info info = openAPI.getInfo();
if (moduleName == null) { if (moduleName == null) {
if (info.getTitle() != null) { if (info.getTitle() != null) {
@ -490,42 +490,42 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
*/ */
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]"; return "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return "%{optional(String.t) => " + getTypeDeclaration(inner) + "}"; return "%{optional(String.t) => " + getTypeDeclaration(inner) + "}";
} else if (ModelUtils.isPasswordSchema(p)) { } else if (modelUtils.isPasswordSchema(p)) {
return "String.t"; return "String.t";
} else if (ModelUtils.isEmailSchema(p)) { } else if (modelUtils.isEmailSchema(p)) {
return "String.t"; return "String.t";
} else if (ModelUtils.isByteArraySchema(p)) { } else if (modelUtils.isByteArraySchema(p)) {
return "binary()"; return "binary()";
} else if (ModelUtils.isUUIDSchema(p)) { } else if (modelUtils.isUUIDSchema(p)) {
return "String.t"; return "String.t";
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
return "Date.t"; return "Date.t";
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
return "DateTime.t"; return "DateTime.t";
} else if (ModelUtils.isObjectSchema(p)) { } else if (modelUtils.isObjectSchema(p)) {
// TODO How to map it? // TODO How to map it?
return super.getTypeDeclaration(p); return super.getTypeDeclaration(p);
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
return "integer()"; return "integer()";
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
return "float()"; return "float()";
} else if (ModelUtils.isBinarySchema(p) || ModelUtils.isFileSchema(p)) { } else if (modelUtils.isBinarySchema(p) || modelUtils.isFileSchema(p)) {
return "String.t"; return "String.t";
} else if (ModelUtils.isBooleanSchema(p)) { } else if (modelUtils.isBooleanSchema(p)) {
return "boolean()"; return "boolean()";
} else if (!StringUtils.isEmpty(p.get$ref())) { // model } else if (!StringUtils.isEmpty(p.get$ref())) { // model
// How to map it? // How to map it?
return super.getTypeDeclaration(p); return super.getTypeDeclaration(p);
} else if (ModelUtils.isFileSchema(p)) { } else if (modelUtils.isFileSchema(p)) {
return "String.t"; return "String.t";
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
return "String.t"; return "String.t";
} }
return super.getTypeDeclaration(p); return super.getTypeDeclaration(p);

View File

@ -238,7 +238,7 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String toInstantiationType(Schema p) { public String toInstantiationType(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems()); String inner = getSchemaType(ap.getItems());
return instantiationTypes.get("array") + " " + inner; return instantiationTypes.get("array") + " " + inner;
@ -414,19 +414,19 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isStringSchema(p)) { if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\""; return "\"" + p.getDefault().toString() + "\"";
} }
} else if (ModelUtils.isBooleanSchema(p)) { } else if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return Boolean.valueOf(p.getDefault().toString()) ? "True" : "False"; return Boolean.valueOf(p.getDefault().toString()) ? "True" : "False";
} }
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
@ -450,11 +450,11 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getTypeDeclaration(inner); return getTypeDeclaration(inner);
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getTypeDeclaration(inner); return getTypeDeclaration(inner);
} }

View File

@ -137,7 +137,7 @@ public class ErlangProperCodegen extends DefaultCodegen implements CodegenConfig
@Override @Override
public CodegenModel fromModel(String name, Schema model) { public CodegenModel fromModel(String name, Schema model) {
CodegenModel cm = super.fromModel(name, model); CodegenModel cm = super.fromModel(name, model);
if(ModelUtils.isArraySchema(model)) { if(modelUtils.isArraySchema(model)) {
return new CodegenArrayModel(cm, (ArraySchema) model); return new CodegenArrayModel(cm, (ArraySchema) model);
} else { } else {
return cm; return cm;
@ -152,7 +152,7 @@ public class ErlangProperCodegen extends DefaultCodegen implements CodegenConfig
@Override @Override
public String getTypeDeclaration(Schema schema) { public String getTypeDeclaration(Schema schema) {
String typeDeclaration = super.getSchemaType(schema); String typeDeclaration = super.getSchemaType(schema);
if(ModelUtils.isArraySchema(schema)) { if(modelUtils.isArraySchema(schema)) {
ArraySchema arraySchema = (ArraySchema) schema; ArraySchema arraySchema = (ArraySchema) schema;
String complexType = getSchemaType(arraySchema.getItems()); String complexType = getSchemaType(arraySchema.getItems());
@ -170,7 +170,7 @@ public class ErlangProperCodegen extends DefaultCodegen implements CodegenConfig
@Override @Override
public String getSchemaType(Schema schema) { public String getSchemaType(Schema schema) {
String schemaType = super.getSchemaType(schema); String schemaType = super.getSchemaType(schema);
if(ModelUtils.isArraySchema(schema)) { if(modelUtils.isArraySchema(schema)) {
ArraySchema arraySchema = (ArraySchema) schema; ArraySchema arraySchema = (ArraySchema) schema;
String complexType = getSchemaType(arraySchema.getItems()); String complexType = getSchemaType(arraySchema.getItems());
@ -183,7 +183,7 @@ public class ErlangProperCodegen extends DefaultCodegen implements CodegenConfig
if(minItems != null && maxItems != null) sb.append(", ").append(maxItems); if(minItems != null && maxItems != null) sb.append(", ").append(maxItems);
return sb.append(")").toString(); return sb.append(")").toString();
} else if(ModelUtils.isIntegerSchema(schema)) { } else if(modelUtils.isIntegerSchema(schema)) {
StringBuilder sb = new StringBuilder("integer("); StringBuilder sb = new StringBuilder("integer(");
BigDecimal min = schema.getMinimum(); BigDecimal min = schema.getMinimum();
@ -192,9 +192,9 @@ public class ErlangProperCodegen extends DefaultCodegen implements CodegenConfig
if(min != null && max != null) sb.append(", ").append(max); if(min != null && max != null) sb.append(", ").append(max);
return sb.append(")").toString(); return sb.append(")").toString();
} else if(ModelUtils.isDateSchema(schema) || ModelUtils.isDateTimeSchema(schema)) { } else if(modelUtils.isDateSchema(schema) || modelUtils.isDateTimeSchema(schema)) {
return typeMapping.get(schemaType); return typeMapping.get(schemaType);
} else if(ModelUtils.isStringSchema(schema)) { } else if(modelUtils.isStringSchema(schema)) {
StringBuilder sb = new StringBuilder("binary("); StringBuilder sb = new StringBuilder("binary(");
Integer min = schema.getMinLength(); Integer min = schema.getMinLength();
Integer max = schema.getMaxLength(); Integer max = schema.getMaxLength();

View File

@ -235,7 +235,7 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p) || ModelUtils.isMapSchema(p)) { if (modelUtils.isArraySchema(p) || modelUtils.isMapSchema(p)) {
return getSchemaType(p); return getSchemaType(p);
} }
return super.getTypeDeclaration(p); return super.getTypeDeclaration(p);
@ -258,27 +258,27 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
return "false"; return "false";
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
return "null"; return "null";
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
return "null"; return "null";
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
return "0.0"; return "0.0";
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
return "0"; return "0";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
return "new Dictionary()"; return "new Dictionary()";
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
return "new Array()"; return "new Array()";
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
return "null"; return "null";
} else { } else {
return "NaN"; return "NaN";

View File

@ -166,8 +166,8 @@ public class FsharpGiraffeServerCodegen extends AbstractFSharpCodegen {
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides()); URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());
additionalProperties.put("serverHost", url.getHost()); additionalProperties.put("serverHost", url.getHost());
additionalProperties.put("serverPort", URLPathUtils.getPort(url, 8080)); additionalProperties.put("serverPort", URLPathUtils.getPort(url, 8080));

View File

@ -349,8 +349,8 @@ public class GoClientCodegen extends AbstractGoCodegen {
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
p = ModelUtils.getReferencedSchema(this.openAPI, p); p = modelUtils.getReferencedSchema(p);
if (ModelUtils.isStringSchema(p)) { if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "\"" + escapeText((String) p.getDefault()) + "\""; return "\"" + escapeText((String) p.getDefault()) + "\"";
} }

View File

@ -123,7 +123,7 @@ public class GraphQLNodeJSExpressServerCodegen extends AbstractGraphQLCodegen im
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
@ -131,7 +131,7 @@ public class GraphQLNodeJSExpressServerCodegen extends AbstractGraphQLCodegen im
// between some specific types for GraphQL: // between some specific types for GraphQL:
// return "[" + getTypeDeclaration(inner) + "]"; // return "[" + getTypeDeclaration(inner) + "]";
return getTypeDeclaration(inner); return getTypeDeclaration(inner);
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = (Schema) p.getAdditionalProperties(); Schema inner = (Schema) p.getAdditionalProperties();
return getTypeDeclaration(inner); return getTypeDeclaration(inner);
@ -139,7 +139,7 @@ public class GraphQLNodeJSExpressServerCodegen extends AbstractGraphQLCodegen im
// IMPORANT NOTE Not using the supertype invocation, because we want to UpperCamelize the type: // IMPORANT NOTE Not using the supertype invocation, because we want to UpperCamelize the type:
String schemaType = getSchemaType(p); String schemaType = getSchemaType(p);
String nullable = ModelUtils.isNullable(p) ? "" : "!"; String nullable = modelUtils.isNullable(p) ? "" : "!";
if (typeMapping.containsKey(schemaType)) { if (typeMapping.containsKey(schemaType)) {
return typeMapping.get(schemaType) + nullable; return typeMapping.get(schemaType) + nullable;

View File

@ -519,7 +519,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
String baseTitle = openAPI.getInfo().getTitle(); String baseTitle = openAPI.getInfo().getTitle();
if (baseTitle == null) { if (baseTitle == null) {
@ -612,7 +612,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
additionalProperties.put(X_HAS_IMPORT_MAPPINGS, true); additionalProperties.put(X_HAS_IMPORT_MAPPINGS, true);
} }
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
} }
@Override @Override
@ -624,11 +624,11 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]"; return "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return "(Map.Map String " + getTypeDeclaration(inner) + ")"; return "(Map.Map String " + getTypeDeclaration(inner) + ")";
} }
@ -650,7 +650,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
@Override @Override
public String toInstantiationType(Schema p) { public String toInstantiationType(Schema p) {
if (ModelUtils.isMapSchema(p)) { if (modelUtils.isMapSchema(p)) {
Schema additionalProperties2 = getAdditionalProperties(p); Schema additionalProperties2 = getAdditionalProperties(p);
String type = additionalProperties2.getType(); String type = additionalProperties2.getType();
if (null == type) { if (null == type) {
@ -659,7 +659,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
} }
String inner = getSchemaType(additionalProperties2); String inner = getSchemaType(additionalProperties2);
return "(Map.Map Text " + inner + ")"; return "(Map.Map Text " + inner + ")";
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
return getSchemaType(ap.getItems()); return getSchemaType(ap.getItems());
} else { } else {
@ -1245,11 +1245,11 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isStringSchema(p)) { if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "\"" + escapeText((String) p.getDefault()) + "\""; return "\"" + escapeText((String) p.getDefault()) + "\"";
} }
} else if (ModelUtils.isBooleanSchema(p)) { } else if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (p.getDefault().toString().equalsIgnoreCase("false")) if (p.getDefault().toString().equalsIgnoreCase("false"))
return "False"; return "False";

View File

@ -268,7 +268,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
// From the title, compute a reasonable name for the package and the API // From the title, compute a reasonable name for the package and the API
String title = openAPI.getInfo().getTitle(); String title = openAPI.getInfo().getTitle();
@ -325,7 +325,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
// See docstring for setGenerateToSchema for why we do this // See docstring for setGenerateToSchema for why we do this
additionalProperties.put("generateToSchema", true); additionalProperties.put("generateToSchema", true);
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
} }
/** /**
@ -368,11 +368,11 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
*/ */
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]"; return "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return "(Map.Map String " + getTypeDeclaration(inner) + ")"; return "(Map.Map String " + getTypeDeclaration(inner) + ")";
} }
@ -407,7 +407,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
@Override @Override
public String toInstantiationType(Schema p) { public String toInstantiationType(Schema p) {
if (ModelUtils.isMapSchema(p)) { if (modelUtils.isMapSchema(p)) {
Schema additionalProperties2 = getAdditionalProperties(p); Schema additionalProperties2 = getAdditionalProperties(p);
String type = additionalProperties2.getType(); String type = additionalProperties2.getType();
if (null == type) { if (null == type) {
@ -416,7 +416,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
} }
String inner = getSchemaType(additionalProperties2); String inner = getSchemaType(additionalProperties2);
return "(Map.Map Text " + inner + ")"; return "(Map.Map Text " + inner + ")";
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems()); String inner = getSchemaType(ap.getItems());
// Return only the inner type; the wrapping with QueryList is done // Return only the inner type; the wrapping with QueryList is done

View File

@ -147,7 +147,7 @@ public class JMeterClientCodegen extends DefaultCodegen implements CodegenConfig
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
if (openAPI != null && openAPI.getPaths() != null) { if (openAPI != null && openAPI.getPaths() != null) {
for (String pathname : openAPI.getPaths().keySet()) { for (String pathname : openAPI.getPaths().keySet()) {
PathItem path = openAPI.getPaths().get(pathname); PathItem path = openAPI.getPaths().get(pathname);
@ -201,11 +201,11 @@ public class JMeterClientCodegen extends DefaultCodegen implements CodegenConfig
*/ */
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]";
} }

View File

@ -1431,9 +1431,9 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isGenerateAliasAsModel(p) && StringUtils.isNotEmpty(p.get$ref())) { if (modelUtils.isGenerateAliasAsModel(p) && StringUtils.isNotEmpty(p.get$ref())) {
Schema<?> ref = ModelUtils.getReferencedSchema(this.openAPI, p); Schema<?> ref = modelUtils.getReferencedSchema(p);
if (ModelUtils.isArraySchema(ref) || ModelUtils.isMapSchema(ref)) { if (modelUtils.isArraySchema(ref) || modelUtils.isMapSchema(ref)) {
String typeDeclaration = getTypeDeclaration(p); String typeDeclaration = getTypeDeclaration(p);
return String.format(Locale.ROOT, "new %s()", typeDeclaration); return String.format(Locale.ROOT, "new %s()", typeDeclaration);
} }

View File

@ -454,8 +454,8 @@ public class JavaPKMSTServerCodegen extends AbstractJavaCodegen {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
if (openAPI == null || openAPI.getPaths() == null) { if (openAPI == null || openAPI.getPaths() == null) {
return; return;
} }

View File

@ -223,8 +223,8 @@ public class JavaVertXServerCodegen extends AbstractJavaCodegen {
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
// add server port from the swagger file, 8080 by default // add server port from the swagger file, 8080 by default
URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides()); URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());

View File

@ -255,8 +255,8 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
if (openAPI.getInfo() != null) { if (openAPI.getInfo() != null) {
Info info = openAPI.getInfo(); Info info = openAPI.getInfo();
@ -560,11 +560,11 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]"; return "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return "{String: " + getTypeDeclaration(inner) + "}"; return "{String: " + getTypeDeclaration(inner) + "}";
} }
@ -573,23 +573,23 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "'" + p.getDefault() + "'"; return "'" + p.getDefault() + "'";
} }
@ -814,7 +814,7 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod
@Override @Override
public CodegenModel fromModel(String name, Schema model) { public CodegenModel fromModel(String name, Schema model) {
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI); Map<String, Schema> allDefinitions = modelUtils.getSchemas();
CodegenModel codegenModel = super.fromModel(name, model); CodegenModel codegenModel = super.fromModel(name, model);
if (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) { if (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) {
@ -822,14 +822,14 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel);
codegenModel = JavascriptApolloClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); codegenModel = JavascriptApolloClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel);
} }
if (ModelUtils.isArraySchema(model)) { if (modelUtils.isArraySchema(model)) {
ArraySchema am = (ArraySchema) model; ArraySchema am = (ArraySchema) model;
if (codegenModel != null && am.getItems() != null) { if (codegenModel != null && am.getItems() != null) {
String itemType = getSchemaType(am.getItems()); String itemType = getSchemaType(am.getItems());
codegenModel.vendorExtensions.put("x-is-array", true); codegenModel.vendorExtensions.put("x-is-array", true);
codegenModel.vendorExtensions.put("x-item-type", itemType); codegenModel.vendorExtensions.put("x-item-type", itemType);
} }
} else if (ModelUtils.isMapSchema(model)) { } else if (modelUtils.isMapSchema(model)) {
if (codegenModel != null && getAdditionalProperties(model) != null) { if (codegenModel != null && getAdditionalProperties(model) != null) {
String itemType = getSchemaType(getAdditionalProperties(model)); String itemType = getSchemaType(getAdditionalProperties(model));
codegenModel.vendorExtensions.put("x-is-map", true); codegenModel.vendorExtensions.put("x-is-map", true);

View File

@ -281,8 +281,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
if (openAPI.getInfo() != null) { if (openAPI.getInfo() != null) {
Info info = openAPI.getInfo(); Info info = openAPI.getInfo();
@ -611,11 +611,11 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]"; return "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return "{String: " + getTypeDeclaration(inner) + "}"; return "{String: " + getTypeDeclaration(inner) + "}";
} }
@ -624,23 +624,23 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "'" + p.getDefault() + "'"; return "'" + p.getDefault() + "'";
} }
@ -865,7 +865,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override @Override
public CodegenModel fromModel(String name, Schema model) { public CodegenModel fromModel(String name, Schema model) {
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI); Map<String, Schema> allDefinitions = modelUtils.getSchemas();
CodegenModel codegenModel = super.fromModel(name, model); CodegenModel codegenModel = super.fromModel(name, model);
if (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) { if (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) {
@ -873,14 +873,14 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel);
codegenModel = JavascriptClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); codegenModel = JavascriptClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel);
} }
if (ModelUtils.isArraySchema(model)) { if (modelUtils.isArraySchema(model)) {
ArraySchema am = (ArraySchema) model; ArraySchema am = (ArraySchema) model;
if (codegenModel != null && am.getItems() != null) { if (codegenModel != null && am.getItems() != null) {
String itemType = getSchemaType(am.getItems()); String itemType = getSchemaType(am.getItems());
codegenModel.vendorExtensions.put("x-is-array", true); codegenModel.vendorExtensions.put("x-is-array", true);
codegenModel.vendorExtensions.put("x-item-type", itemType); codegenModel.vendorExtensions.put("x-item-type", itemType);
} }
} else if (ModelUtils.isMapSchema(model)) { } else if (modelUtils.isMapSchema(model)) {
if (codegenModel != null && getAdditionalProperties(model) != null) { if (codegenModel != null && getAdditionalProperties(model) != null) {
String itemType = getSchemaType(getAdditionalProperties(model)); String itemType = getSchemaType(getAdditionalProperties(model));
codegenModel.vendorExtensions.put("x-is-map", true); codegenModel.vendorExtensions.put("x-is-map", true);

View File

@ -112,8 +112,8 @@ public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implem
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
if (useEs6) { if (useEs6) {
embeddedTemplateDir = templateDir = "Javascript-Closure-Angular/es6"; embeddedTemplateDir = templateDir = "Javascript-Closure-Angular/es6";
@ -220,14 +220,14 @@ public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implem
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "<!" + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<!" + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return "Object<!string, "+ getTypeDeclaration(inner) + ">"; return "Object<!string, "+ getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isFileSchema(p)) { } else if (modelUtils.isFileSchema(p)) {
return "Object"; return "Object";
} }
String type = super.getTypeDeclaration(p); String type = super.getTypeDeclaration(p);

View File

@ -136,8 +136,8 @@ public class JavascriptFlowtypedClientCodegen extends AbstractTypeScriptClientCo
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
if (openAPI.getInfo() != null) { if (openAPI.getInfo() != null) {
Info info = openAPI.getInfo(); Info info = openAPI.getInfo();

View File

@ -238,8 +238,8 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig {
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
if (openAPI.getInfo() != null) { if (openAPI.getInfo() != null) {
Info info = openAPI.getInfo(); Info info = openAPI.getInfo();
@ -325,16 +325,16 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig {
} }
} }
if (hasBodyParameter(openAPI, operation) || hasFormParameter(openAPI, operation)) { if (hasBodyParameter(operation) || hasFormParameter(operation)) {
String defaultContentType = hasFormParameter(openAPI, operation) ? "application/x-www-form-urlencoded" : "application/json"; String defaultContentType = hasFormParameter(operation) ? "application/x-www-form-urlencoded" : "application/json";
List<String> consumes = new ArrayList<>(getConsumesInfo(openAPI, operation)); List<String> consumes = new ArrayList<>(getConsumesInfo(operation));
String contentTypeValue = consumes == null || consumes.isEmpty() ? defaultContentType : consumes.get(0); String contentTypeValue = consumes == null || consumes.isEmpty() ? defaultContentType : consumes.get(0);
if (contentTypeValue.equals("*/*")) if (contentTypeValue.equals("*/*"))
contentTypeValue = "application/json"; contentTypeValue = "application/json";
Parameter contentType = new Parameter("Content-Type", getDoubleQuotedString(contentTypeValue)); Parameter contentType = new Parameter("Content-Type", getDoubleQuotedString(contentTypeValue));
httpParams.add(contentType); httpParams.add(contentType);
RequestBody requestBody = ModelUtils.getReferencedRequestBody(openAPI, operation.getRequestBody()); RequestBody requestBody = modelUtils.getReferencedRequestBody(operation.getRequestBody());
for (Map.Entry<String, ApiResponse> responseEntry : operation.getResponses().entrySet()) { for (Map.Entry<String, ApiResponse> responseEntry : operation.getResponses().entrySet()) {
CodegenResponse r = fromResponse(responseEntry.getKey(), responseEntry.getValue()); CodegenResponse r = fromResponse(responseEntry.getKey(), responseEntry.getValue());
@ -349,7 +349,7 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig {
for (CodegenParameter parameter : formParameteres) { for (CodegenParameter parameter : formParameteres) {
String reference = ""; String reference = "";
if (parameter.isModel) { if (parameter.isModel) {
Schema nestedSchema = ModelUtils.getSchema(openAPI, parameter.baseType); Schema nestedSchema = modelUtils.getSchema(parameter.baseType);
CodegenModel model = fromModel(parameter.paramName, nestedSchema); CodegenModel model = fromModel(parameter.paramName, nestedSchema);
reference = generateNestedModelTemplate(model); reference = generateNestedModelTemplate(model);
if (parameter.dataType.equals("List")) { if (parameter.dataType.equals("List")) {
@ -369,7 +369,7 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig {
bodyOrFormParams.add(k6Parameter); bodyOrFormParams.add(k6Parameter);
} }
} }
String accepts = getAccept(openAPI, operation); String accepts = getAccept(operation);
String responseType = getDoubleQuotedString(accepts); String responseType = getDoubleQuotedString(accepts);
try { try {
@ -602,10 +602,10 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig {
return input.replace("*/", "*_/").replace("/*", "/_*"); return input.replace("*/", "*_/").replace("/*", "/_*");
} }
private static String getAccept(OpenAPI openAPI, Operation operation) { private String getAccept(Operation operation) {
String accepts = null; String accepts = null;
String defaultContentType = "application/json"; String defaultContentType = "application/json";
Set<String> producesInfo = getProducesInfo(openAPI, operation); Set<String> producesInfo = getProducesInfo(operation);
if (producesInfo != null && !producesInfo.isEmpty()) { if (producesInfo != null && !producesInfo.isEmpty()) {
ArrayList<String> produces = new ArrayList<>(producesInfo); ArrayList<String> produces = new ArrayList<>(producesInfo);
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();

View File

@ -474,8 +474,8 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
if (!additionalProperties.containsKey(TITLE)) { if (!additionalProperties.containsKey(TITLE)) {
// The purpose of the title is for: // The purpose of the title is for:

View File

@ -362,11 +362,11 @@ public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getTypeDeclaration(inner); return getTypeDeclaration(inner);
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getTypeDeclaration(inner); return getTypeDeclaration(inner);
} }

View File

@ -270,14 +270,14 @@ public class NimClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
if (inner == null) { if (inner == null) {
return null; return null;
} }
return "seq[" + getTypeDeclaration(inner) + "]"; return "seq[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
if (inner == null) { if (inner == null) {
inner = new StringSchema(); inner = new StringSchema();

View File

@ -325,7 +325,7 @@ public class NodeJSExpressServerCodegen extends DefaultCodegen implements Codege
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides()); URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());
String host = URLPathUtils.getProtocolAndHost(url); String host = URLPathUtils.getProtocolAndHost(url);
String port = URLPathUtils.getPort(url, defaultServerPort); String port = URLPathUtils.getPort(url, defaultServerPort);

View File

@ -422,7 +422,7 @@ public class OCamlClientCodegen extends DefaultCodegen implements CodegenConfig
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
collectEnumSchemas(openAPI); collectEnumSchemas(openAPI);
supportingFiles.add(new SupportingFile("lib.mustache", "", packageName + ".opam")); supportingFiles.add(new SupportingFile("lib.mustache", "", packageName + ".opam"));
@ -575,7 +575,7 @@ public class OCamlClientCodegen extends DefaultCodegen implements CodegenConfig
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
if (inner == null) { if (inner == null) {
@ -583,7 +583,7 @@ public class OCamlClientCodegen extends DefaultCodegen implements CodegenConfig
inner = new StringSchema().description("TODO default missing array inner type to string"); inner = new StringSchema().description("TODO default missing array inner type to string");
} }
return getTypeDeclaration(inner) + " list"; return getTypeDeclaration(inner) + " list";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
if (inner == null) { if (inner == null) {
LOGGER.warn(p.getName() + "(map property) does not have a proper inner type defined. Default to string"); LOGGER.warn(p.getName() + "(map property) does not have a proper inner type defined. Default to string");
@ -596,7 +596,7 @@ public class OCamlClientCodegen extends DefaultCodegen implements CodegenConfig
return enumUniqNames.get(h); return enumUniqNames.get(h);
} }
Schema referencedSchema = ModelUtils.getReferencedSchema(openAPI, p); Schema referencedSchema = modelUtils.getReferencedSchema(p);
if (referencedSchema != null && referencedSchema.getEnum() != null) { if (referencedSchema != null && referencedSchema.getEnum() != null) {
String h = hashEnum(referencedSchema); String h = hashEnum(referencedSchema);
return "Enums." + enumUniqNames.get(h); return "Enums." + enumUniqNames.get(h);

View File

@ -325,9 +325,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String toInstantiationType(Schema p) { public String toInstantiationType(Schema p) {
if (ModelUtils.isMapSchema(p)) { if (modelUtils.isMapSchema(p)) {
return instantiationTypes.get("map"); return instantiationTypes.get("map");
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
return instantiationTypes.get("array"); return instantiationTypes.get("array");
} else { } else {
return null; return null;
@ -366,7 +366,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
String innerTypeDeclaration = getTypeDeclaration(inner); String innerTypeDeclaration = getTypeDeclaration(inner);
@ -388,7 +388,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
} }
return getSchemaType(p) + "<" + innerTypeDeclaration + ">*"; return getSchemaType(p) + "<" + innerTypeDeclaration + ">*";
} }
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
String innerTypeDeclaration = getTypeDeclaration(inner); String innerTypeDeclaration = getTypeDeclaration(inner);
@ -679,23 +679,23 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
*/ */
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isDateSchema(p)) { if (modelUtils.isDateSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "@" + p.getDefault().toString(); return "@" + p.getDefault().toString();
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "@" + p.getDefault().toString(); return "@" + p.getDefault().toString();
} }
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "@\"" + (String) p.getDefault() + "\""; return "@\"" + (String) p.getDefault() + "\"";
} }
} else if (ModelUtils.isBooleanSchema(p)) { } else if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (p.getDefault().toString().equalsIgnoreCase("false")) if (p.getDefault().toString().equalsIgnoreCase("false"))
return "@(NO)"; return "@(NO)";

View File

@ -83,7 +83,7 @@ public class OpenAPIGenerator extends DefaultCodegen implements CodegenConfig {
} }
@Override @Override
public void processOpenAPI(OpenAPI openAPI) { public void processOpenAPI() {
String jsonOpenAPI = SerializerUtils.toJsonString(openAPI); String jsonOpenAPI = SerializerUtils.toJsonString(openAPI);
try { try {

View File

@ -252,11 +252,11 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[string," + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[string," + getTypeDeclaration(inner) + "]";
} }
@ -283,23 +283,23 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "'" + p.getDefault() + "'"; return "'" + p.getDefault() + "'";
} }

View File

@ -171,11 +171,11 @@ public class PhpSilexServerCodegen extends DefaultCodegen implements CodegenConf
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[string," + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[string," + getTypeDeclaration(inner) + "]";
} }

View File

@ -536,13 +536,13 @@ public class PhpSymfonyServerCodegen extends AbstractPhpCodegen implements Codeg
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getTypeDeclaration(inner); return getTypeDeclaration(inner);
} }
if (ModelUtils.isMapSchema(p)) { if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getTypeDeclaration(inner); return getTypeDeclaration(inner);
} }

View File

@ -174,8 +174,8 @@ public class PhpZendExpressivePathHandlerServerCodegen extends AbstractPhpCodege
* @param openAPI OpenAPI object * @param openAPI OpenAPI object
*/ */
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
Map<String, PathItem> paths = openAPI.getPaths(); Map<String, PathItem> paths = openAPI.getPaths();
if (paths != null) { if (paths != null) {
@ -226,7 +226,7 @@ public class PhpZendExpressivePathHandlerServerCodegen extends AbstractPhpCodege
if (parameter instanceof QueryParameter) { if (parameter instanceof QueryParameter) {
QueryParameter queryParameter = (QueryParameter) parameter; QueryParameter queryParameter = (QueryParameter) parameter;
// array // array
if (ModelUtils.isArraySchema(queryParameter.getSchema())) { if (modelUtils.isArraySchema(queryParameter.getSchema())) {
Schema inner = ((ArraySchema) queryParameter.getSchema()).getItems(); Schema inner = ((ArraySchema) queryParameter.getSchema()).getItems();
ArraySchema arraySchema = new ArraySchema(); ArraySchema arraySchema = new ArraySchema();
arraySchema.setMinItems(queryParameter.getSchema().getMinItems()); arraySchema.setMinItems(queryParameter.getSchema().getMinItems());

View File

@ -906,11 +906,11 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo
*/ */
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getTypeDeclaration(inner) + "[]"; return getTypeDeclaration(inner) + "[]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
return "System.Collections.Hashtable"; return "System.Collections.Hashtable";
} else if (!languageSpecificPrimitives.contains(getSchemaType(p))) { } else if (!languageSpecificPrimitives.contains(getSchemaType(p))) {
return super.getTypeDeclaration(p); return super.getTypeDeclaration(p);
@ -1272,21 +1272,21 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
if (Boolean.valueOf(p.getDefault().toString())) { if (Boolean.valueOf(p.getDefault().toString())) {
return "$true"; return "$true";
} else { } else {
return "$false"; return "$false";
} }
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
LOGGER.warn("Default value for `date` not yet supported. Please open an issue with https://github.com/openapitools/openapi-generator"); LOGGER.warn("Default value for `date` not yet supported. Please open an issue with https://github.com/openapitools/openapi-generator");
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
LOGGER.warn("Default value for `datetime` not yet supported. Please open an issue with https://github.com/openapitools/openapi-generator"); LOGGER.warn("Default value for `datetime` not yet supported. Please open an issue with https://github.com/openapitools/openapi-generator");
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
return p.getDefault().toString(); return p.getDefault().toString();
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
return p.getDefault().toString(); return p.getDefault().toString();
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
return "\"" + p.getDefault() + "\""; return "\"" + p.getDefault() + "\"";
} }
} }

View File

@ -300,33 +300,33 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf
*/ */
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (Boolean.valueOf(p.getDefault().toString()) == false) if (Boolean.valueOf(p.getDefault().toString()) == false)
return "false"; return "false";
else else
return "true"; return "true";
} }
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (Pattern.compile("\r\n|\r|\n").matcher((String) p.getDefault()).find()) if (Pattern.compile("\r\n|\r|\n").matcher((String) p.getDefault()).find())
return "'''" + p.getDefault() + "'''"; return "'''" + p.getDefault() + "'''";
else else
return "'" + p.getDefault() + "'"; return "'" + p.getDefault() + "'";
} }
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
@ -484,11 +484,11 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[str, " + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[str, " + getTypeDeclaration(inner) + "]";
} }

View File

@ -142,7 +142,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
} }
// default this to true so the python ModelSimple models will be generated // default this to true so the python ModelSimple models will be generated
ModelUtils.setGenerateAliasAsModel(true); modelUtils.setGenerateAliasAsModel(true);
LOGGER.info(CodegenConstants.GENERATE_ALIAS_AS_MODEL + " is hard coded to true in this generator. Alias models will only be generated if they contain validations or enums"); LOGGER.info(CodegenConstants.GENERATE_ALIAS_AS_MODEL + " is hard coded to true in this generator. Alias models will only be generated if they contain validations or enums");
Boolean attrNoneIfUnset = false; Boolean attrNoneIfUnset = false;
@ -170,7 +170,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
@Override @Override
public Schema unaliasSchema(Schema schema, Map<String, String> usedImportMappings) { public Schema unaliasSchema(Schema schema, Map<String, String> usedImportMappings) {
Map<String, Schema> allSchemas = ModelUtils.getSchemas(openAPI); Map<String, Schema> allSchemas = modelUtils.getSchemas();
if (allSchemas == null || allSchemas.isEmpty()) { if (allSchemas == null || allSchemas.isEmpty()) {
// skip the warning as the spec can have no model defined // skip the warning as the spec can have no model defined
//LOGGER.warn("allSchemas cannot be null/empty in unaliasSchema. Returned 'schema'"); //LOGGER.warn("allSchemas cannot be null/empty in unaliasSchema. Returned 'schema'");
@ -178,7 +178,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
} }
if (schema != null && StringUtils.isNotEmpty(schema.get$ref())) { if (schema != null && StringUtils.isNotEmpty(schema.get$ref())) {
String simpleRef = ModelUtils.getSimpleRef(schema.get$ref()); String simpleRef = modelUtils.getSimpleRef(schema.get$ref());
if (usedImportMappings.containsKey(simpleRef)) { if (usedImportMappings.containsKey(simpleRef)) {
LOGGER.debug("Schema unaliasing of {} omitted because aliased class is to be mapped to {}", simpleRef, usedImportMappings.get(simpleRef)); LOGGER.debug("Schema unaliasing of {} omitted because aliased class is to be mapped to {}", simpleRef, usedImportMappings.get(simpleRef));
return schema; return schema;
@ -190,41 +190,41 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
} else if (ref.getEnum() != null && !ref.getEnum().isEmpty()) { } else if (ref.getEnum() != null && !ref.getEnum().isEmpty()) {
// top-level enum class // top-level enum class
return schema; return schema;
} else if (ModelUtils.isArraySchema(ref)) { } else if (modelUtils.isArraySchema(ref)) {
if (ModelUtils.isGenerateAliasAsModel(ref)) { if (modelUtils.isGenerateAliasAsModel(ref)) {
return schema; // generate a model extending array return schema; // generate a model extending array
} else { } else {
return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())), return unaliasSchema(allSchemas.get(modelUtils.getSimpleRef(schema.get$ref())),
usedImportMappings); usedImportMappings);
} }
} else if (ModelUtils.isComposedSchema(ref)) { } else if (modelUtils.isComposedSchema(ref)) {
return schema; return schema;
} else if (ModelUtils.isMapSchema(ref)) { } else if (modelUtils.isMapSchema(ref)) {
if (ref.getProperties() != null && !ref.getProperties().isEmpty()) // has at least one property if (ref.getProperties() != null && !ref.getProperties().isEmpty()) // has at least one property
return schema; // treat it as model return schema; // treat it as model
else { else {
if (ModelUtils.isGenerateAliasAsModel(ref)) { if (modelUtils.isGenerateAliasAsModel(ref)) {
return schema; // generate a model extending map return schema; // generate a model extending map
} else { } else {
// treat it as a typical map // treat it as a typical map
return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())), return unaliasSchema(allSchemas.get(modelUtils.getSimpleRef(schema.get$ref())),
usedImportMappings); usedImportMappings);
} }
} }
} else if (ModelUtils.isObjectSchema(ref)) { // model } else if (modelUtils.isObjectSchema(ref)) { // model
if (ref.getProperties() != null && !ref.getProperties().isEmpty()) { // has at least one property if (ref.getProperties() != null && !ref.getProperties().isEmpty()) { // has at least one property
return schema; return schema;
} else { } else {
// free form object (type: object) // free form object (type: object)
if (ModelUtils.hasValidation(ref)) { if (modelUtils.hasValidation(ref)) {
return schema; return schema;
} else if (getAllOfDescendants(simpleRef, openAPI).size() > 0) { } else if (getAllOfDescendants(simpleRef, openAPI).size() > 0) {
return schema; return schema;
} }
return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())), return unaliasSchema(allSchemas.get(modelUtils.getSimpleRef(schema.get$ref())),
usedImportMappings); usedImportMappings);
} }
} else if (ModelUtils.hasValidation(ref)) { } else if (modelUtils.hasValidation(ref)) {
// non object non array non map schemas that have validations // non object non array non map schemas that have validations
// are returned so we can generate those schemas as models // are returned so we can generate those schemas as models
// we do this to: // we do this to:
@ -232,7 +232,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
// - use those validations when we use this schema in composed oneOf schemas // - use those validations when we use this schema in composed oneOf schemas
return schema; return schema;
} else { } else {
return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())), usedImportMappings); return unaliasSchema(allSchemas.get(modelUtils.getSimpleRef(schema.get$ref())), usedImportMappings);
} }
} }
return schema; return schema;
@ -297,13 +297,13 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
} }
String defaultValue = defaultObject.toString(); String defaultValue = defaultObject.toString();
if (ModelUtils.isDateSchema(p)) { if (modelUtils.isDateSchema(p)) {
defaultValue = pythonDate(defaultObject); defaultValue = pythonDate(defaultObject);
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
defaultValue = pythonDateTime(defaultObject); defaultValue = pythonDateTime(defaultObject);
} else if (ModelUtils.isStringSchema(p) && !ModelUtils.isByteArraySchema(p) && !ModelUtils.isBinarySchema(p) && !ModelUtils.isFileSchema(p) && !ModelUtils.isUUIDSchema(p) && !ModelUtils.isEmailSchema(p)) { } else if (modelUtils.isStringSchema(p) && !modelUtils.isByteArraySchema(p) && !modelUtils.isBinarySchema(p) && !modelUtils.isFileSchema(p) && !modelUtils.isUUIDSchema(p) && !modelUtils.isEmailSchema(p)) {
defaultValue = ensureQuotes(defaultValue); defaultValue = ensureQuotes(defaultValue);
} else if (ModelUtils.isBooleanSchema(p)) { } else if (modelUtils.isBooleanSchema(p)) {
if (Boolean.valueOf(defaultValue) == false) { if (Boolean.valueOf(defaultValue) == false) {
defaultValue = "False"; defaultValue = "False";
} else { } else {
@ -359,7 +359,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
super.postProcessAllModels(objs); super.postProcessAllModels(objs);
List<String> modelsToRemove = new ArrayList<>(); List<String> modelsToRemove = new ArrayList<>();
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI); Map<String, Schema> allDefinitions = modelUtils.getSchemas();
for (String schemaName: allDefinitions.keySet()) { for (String schemaName: allDefinitions.keySet()) {
Schema refSchema = new Schema().$ref("#/components/schemas/"+schemaName); Schema refSchema = new Schema().$ref("#/components/schemas/"+schemaName);
Schema unaliasedSchema = unaliasSchema(refSchema, importMapping); Schema unaliasedSchema = unaliasSchema(refSchema, importMapping);
@ -467,7 +467,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
@Override @Override
public CodegenParameter fromRequestBody(RequestBody body, Set<String> imports, String bodyParameterName) { public CodegenParameter fromRequestBody(RequestBody body, Set<String> imports, String bodyParameterName) {
CodegenParameter cp = super.fromRequestBody(body, imports, bodyParameterName); CodegenParameter cp = super.fromRequestBody(body, imports, bodyParameterName);
Schema schema = ModelUtils.getSchemaFromRequestBody(body); Schema schema = modelUtils.getSchemaFromRequestBody(body);
if (schema.get$ref() == null) { if (schema.get$ref() == null) {
return cp; return cp;
} }
@ -586,7 +586,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
oneOfanyOfSchemas.addAll(anyOf); oneOfanyOfSchemas.addAll(anyOf);
} }
for (Schema sc: oneOfanyOfSchemas) { for (Schema sc: oneOfanyOfSchemas) {
Schema refSchema = ModelUtils.getReferencedSchema(this.openAPI, sc); Schema refSchema = modelUtils.getReferencedSchema(sc);
addProperties(otherProperties, otherRequired, refSchema); addProperties(otherProperties, otherRequired, refSchema);
} }
Set<String> otherRequiredSet = new HashSet<String>(otherRequired); Set<String> otherRequiredSet = new HashSet<String>(otherRequired);
@ -651,7 +651,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
postProcessModelProperty(cm, cp); postProcessModelProperty(cm, cp);
} }
} }
Boolean isNotPythonModelSimpleModel = (ModelUtils.isComposedSchema(sc) || ModelUtils.isObjectSchema(sc) || ModelUtils.isMapSchema(sc)); Boolean isNotPythonModelSimpleModel = (modelUtils.isComposedSchema(sc) || modelUtils.isObjectSchema(sc) || modelUtils.isMapSchema(sc));
if (isNotPythonModelSimpleModel) { if (isNotPythonModelSimpleModel) {
return cm; return cm;
} }
@ -703,7 +703,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
if (sc.get$ref() != null) { if (sc.get$ref() != null) {
Schema unaliasedSchema = unaliasSchema(sc, importMapping); Schema unaliasedSchema = unaliasSchema(sc, importMapping);
if (unaliasedSchema.get$ref() != null) { if (unaliasedSchema.get$ref() != null) {
return toModelName(ModelUtils.getSimpleRef(sc.get$ref())); return toModelName(modelUtils.getSimpleRef(sc.get$ref()));
} }
} }
return null; return null;
@ -740,27 +740,27 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
// a composed schema, convert the name to a Python class. // a composed schema, convert the name to a Python class.
Schema unaliasedSchema = unaliasSchema(p, importMapping); Schema unaliasedSchema = unaliasSchema(p, importMapping);
if (unaliasedSchema.get$ref() != null) { if (unaliasedSchema.get$ref() != null) {
String modelName = toModelName(ModelUtils.getSimpleRef(p.get$ref())); String modelName = toModelName(modelUtils.getSimpleRef(p.get$ref()));
if (referencedModelNames != null) { if (referencedModelNames != null) {
referencedModelNames.add(modelName); referencedModelNames.add(modelName);
} }
return prefix + modelName + fullSuffix; return prefix + modelName + fullSuffix;
} }
} }
if (isAnyTypeSchema(p)) { if (modelUtils.isAnyTypeSchema(p)) {
return prefix + "bool, date, datetime, dict, float, int, list, str, none_type" + suffix; return prefix + "bool, date, datetime, dict, float, int, list, str, none_type" + suffix;
} }
// Resolve $ref because ModelUtils.isXYZ methods do not automatically resolve references. // Resolve $ref because modelUtils.isXYZ methods do not automatically resolve references.
if (ModelUtils.isNullable(ModelUtils.getReferencedSchema(this.openAPI, p))) { if (modelUtils.isNullable(modelUtils.getReferencedSchema(p))) {
fullSuffix = ", none_type" + suffix; fullSuffix = ", none_type" + suffix;
} }
if (isFreeFormObject(p) && getAdditionalProperties(p) == null) { if (modelUtils.isFreeFormObject(p) && getAdditionalProperties(p) == null) {
return prefix + "bool, date, datetime, dict, float, int, list, str" + fullSuffix; return prefix + "bool, date, datetime, dict, float, int, list, str" + fullSuffix;
} }
if ((ModelUtils.isMapSchema(p) || "object".equals(p.getType())) && getAdditionalProperties(p) != null) { if ((modelUtils.isMapSchema(p) || "object".equals(p.getType())) && getAdditionalProperties(p) != null) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return prefix + "{str: " + getTypeString(inner, "(", ")", referencedModelNames) + "}" + fullSuffix; return prefix + "{str: " + getTypeString(inner, "(", ")", referencedModelNames) + "}" + fullSuffix;
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
if (inner == null) { if (inner == null) {
@ -777,7 +777,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
return prefix + getTypeString(inner, "[", "]", referencedModelNames) + fullSuffix; return prefix + getTypeString(inner, "[", "]", referencedModelNames) + fullSuffix;
} }
} }
if (ModelUtils.isFileSchema(p)) { if (modelUtils.isFileSchema(p)) {
return prefix + "file_type" + fullSuffix; return prefix + "file_type" + fullSuffix;
} }
String baseType = getSchemaType(p); String baseType = getSchemaType(p);
@ -801,7 +801,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
@Override @Override
public String toInstantiationType(Schema property) { public String toInstantiationType(Schema property) {
if (ModelUtils.isArraySchema(property) || ModelUtils.isMapSchema(property) || property.getAdditionalProperties() != null) { if (modelUtils.isArraySchema(property) || modelUtils.isMapSchema(property) || property.getAdditionalProperties() != null) {
return getSchemaType(property); return getSchemaType(property);
} }
return super.toInstantiationType(property); return super.toInstantiationType(property);
@ -837,10 +837,10 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
Schema schema = sc; Schema schema = sc;
String ref = sc.get$ref(); String ref = sc.get$ref();
if (ref != null) { if (ref != null) {
schema = ModelUtils.getSchema(this.openAPI, ModelUtils.getSimpleRef(ref)); schema = modelUtils.getSchema(modelUtils.getSimpleRef(ref));
} }
// TODO handle examples in object models in the future // TODO handle examples in object models in the future
Boolean objectModel = (ModelUtils.isObjectSchema(schema) || ModelUtils.isMapSchema(schema) || ModelUtils.isComposedSchema(schema)); Boolean objectModel = (modelUtils.isObjectSchema(schema) || modelUtils.isMapSchema(schema) || modelUtils.isComposedSchema(schema));
if (objectModel) { if (objectModel) {
return null; return null;
} }
@ -883,9 +883,9 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
Schema sc = schema; Schema sc = schema;
String ref = schema.get$ref(); String ref = schema.get$ref();
if (ref != null) { if (ref != null) {
sc = ModelUtils.getSchema(this.openAPI, ModelUtils.getSimpleRef(ref)); sc = modelUtils.getSchema(modelUtils.getSimpleRef(ref));
} }
if (ModelUtils.isStringSchema(sc) && !ModelUtils.isDateSchema(sc) && !ModelUtils.isDateTimeSchema(sc) && !"Number".equalsIgnoreCase(sc.getFormat()) && !ModelUtils.isByteArraySchema(sc) && !ModelUtils.isBinarySchema(sc) && schema.getPattern() == null) { if (modelUtils.isStringSchema(sc) && !modelUtils.isDateSchema(sc) && !modelUtils.isDateTimeSchema(sc) && !"Number".equalsIgnoreCase(sc.getFormat()) && !modelUtils.isByteArraySchema(sc) && !modelUtils.isBinarySchema(sc) && schema.getPattern() == null) {
return true; return true;
} }
return false; return false;
@ -895,7 +895,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
for ( MappedModel mm : disc.getMappedModels() ) { for ( MappedModel mm : disc.getMappedModels() ) {
String modelName = mm.getModelName(); String modelName = mm.getModelName();
Schema modelSchema = getModelNameToSchemaCache().get(modelName); Schema modelSchema = getModelNameToSchemaCache().get(modelName);
if (ModelUtils.isObjectSchema(modelSchema)) { if (modelUtils.isObjectSchema(modelSchema)) {
return mm; return mm;
} }
} }
@ -949,8 +949,8 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
example = objExample.toString(); example = objExample.toString();
} }
if (null != schema.get$ref()) { if (null != schema.get$ref()) {
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI); Map<String, Schema> allDefinitions = modelUtils.getSchemas();
String ref = ModelUtils.getSimpleRef(schema.get$ref()); String ref = modelUtils.getSimpleRef(schema.get$ref());
Schema refSchema = allDefinitions.get(ref); Schema refSchema = allDefinitions.get(ref);
if (null == refSchema) { if (null == refSchema) {
LOGGER.warn("Unable to find referenced schema "+schema.get$ref()+"\n"); LOGGER.warn("Unable to find referenced schema "+schema.get$ref()+"\n");
@ -958,11 +958,11 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
} }
String refModelName = getModelName(schema); String refModelName = getModelName(schema);
return toExampleValueRecursive(refModelName, refSchema, objExample, indentationLevel, prefix, exampleLine); return toExampleValueRecursive(refModelName, refSchema, objExample, indentationLevel, prefix, exampleLine);
} else if (ModelUtils.isNullType(schema) || isAnyTypeSchema(schema)) { } else if (modelUtils.isNullType(schema) || modelUtils.isAnyTypeSchema(schema)) {
// The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x, // The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x,
// though this tooling supports it. // though this tooling supports it.
return fullPrefix + "None" + closeChars; return fullPrefix + "None" + closeChars;
} else if (ModelUtils.isBooleanSchema(schema)) { } else if (modelUtils.isBooleanSchema(schema)) {
if (objExample == null) { if (objExample == null) {
example = "True"; example = "True";
} else { } else {
@ -973,32 +973,32 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
} }
} }
return fullPrefix + example + closeChars; return fullPrefix + example + closeChars;
} else if (ModelUtils.isDateSchema(schema)) { } else if (modelUtils.isDateSchema(schema)) {
if (objExample == null) { if (objExample == null) {
example = pythonDate("1970-01-01"); example = pythonDate("1970-01-01");
} else { } else {
example = pythonDate(objExample); example = pythonDate(objExample);
} }
return fullPrefix + example + closeChars; return fullPrefix + example + closeChars;
} else if (ModelUtils.isDateTimeSchema(schema)) { } else if (modelUtils.isDateTimeSchema(schema)) {
if (objExample == null) { if (objExample == null) {
example = pythonDateTime("1970-01-01T00:00:00.00Z"); example = pythonDateTime("1970-01-01T00:00:00.00Z");
} else { } else {
example = pythonDateTime(objExample); example = pythonDateTime(objExample);
} }
return fullPrefix + example + closeChars; return fullPrefix + example + closeChars;
} else if (ModelUtils.isBinarySchema(schema)) { } else if (modelUtils.isBinarySchema(schema)) {
if (objExample == null) { if (objExample == null) {
example = "/path/to/file"; example = "/path/to/file";
} }
example = "open('" + example + "', 'rb')"; example = "open('" + example + "', 'rb')";
return fullPrefix + example + closeChars; return fullPrefix + example + closeChars;
} else if (ModelUtils.isByteArraySchema(schema)) { } else if (modelUtils.isByteArraySchema(schema)) {
if (objExample == null) { if (objExample == null) {
example = "'YQ=='"; example = "'YQ=='";
} }
return fullPrefix + example + closeChars; return fullPrefix + example + closeChars;
} else if (ModelUtils.isStringSchema(schema)) { } else if (modelUtils.isStringSchema(schema)) {
if (objExample == null) { if (objExample == null) {
// a BigDecimal: // a BigDecimal:
if ("Number".equalsIgnoreCase(schema.getFormat())) { if ("Number".equalsIgnoreCase(schema.getFormat())) {
@ -1022,14 +1022,14 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
example = ""; example = "";
int len = schema.getMinLength().intValue(); int len = schema.getMinLength().intValue();
for (int i=0;i<len;i++) example += "a"; for (int i=0;i<len;i++) example += "a";
} else if (ModelUtils.isUUIDSchema(schema)) { } else if (modelUtils.isUUIDSchema(schema)) {
example = "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; example = "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
} else { } else {
example = "string_example"; example = "string_example";
} }
} }
return fullPrefix + ensureQuotes(example) + closeChars; return fullPrefix + ensureQuotes(example) + closeChars;
} else if (ModelUtils.isIntegerSchema(schema)) { } else if (modelUtils.isIntegerSchema(schema)) {
if (objExample == null) { if (objExample == null) {
if (schema.getMinimum() != null) { if (schema.getMinimum() != null) {
example = schema.getMinimum().toString(); example = schema.getMinimum().toString();
@ -1038,7 +1038,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
} }
} }
return fullPrefix + example + closeChars; return fullPrefix + example + closeChars;
} else if (ModelUtils.isNumberSchema(schema)) { } else if (modelUtils.isNumberSchema(schema)) {
if (objExample == null) { if (objExample == null) {
if (schema.getMinimum() != null) { if (schema.getMinimum() != null) {
example = schema.getMinimum().toString(); example = schema.getMinimum().toString();
@ -1047,7 +1047,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
} }
} }
return fullPrefix + example + closeChars; return fullPrefix + example + closeChars;
} else if (ModelUtils.isArraySchema(schema)) { } else if (modelUtils.isArraySchema(schema)) {
if (objExample instanceof Iterable) { if (objExample instanceof Iterable) {
// If the example is already a list, return it directly instead of wrongly wrap it in another list // If the example is already a list, return it directly instead of wrongly wrap it in another list
return fullPrefix + objExample.toString(); return fullPrefix + objExample.toString();
@ -1057,7 +1057,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
String itemModelName = getModelName(itemSchema); String itemModelName = getModelName(itemSchema);
example = fullPrefix + "[" + "\n" + toExampleValueRecursive(itemModelName, itemSchema, objExample, indentationLevel+1, "", exampleLine+1) + ",\n" + closingIndentation + "]" + closeChars; example = fullPrefix + "[" + "\n" + toExampleValueRecursive(itemModelName, itemSchema, objExample, indentationLevel+1, "", exampleLine+1) + ",\n" + closingIndentation + "]" + closeChars;
return example; return example;
} else if (ModelUtils.isMapSchema(schema)) { } else if (modelUtils.isMapSchema(schema)) {
if (modelName == null) { if (modelName == null) {
fullPrefix += "{"; fullPrefix += "{";
closeChars = "}"; closeChars = "}";
@ -1082,7 +1082,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
example = fullPrefix + closeChars; example = fullPrefix + closeChars;
} }
return example; return example;
} else if (ModelUtils.isObjectSchema(schema)) { } else if (modelUtils.isObjectSchema(schema)) {
if (modelName == null) { if (modelName == null) {
fullPrefix += "{"; fullPrefix += "{";
closeChars = "}"; closeChars = "}";
@ -1101,7 +1101,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
} }
} }
return exampleForObjectModel(schema, fullPrefix, closeChars, null, indentationLevel, exampleLine, closingIndentation); return exampleForObjectModel(schema, fullPrefix, closeChars, null, indentationLevel, exampleLine, closingIndentation);
} else if (ModelUtils.isComposedSchema(schema)) { } else if (modelUtils.isComposedSchema(schema)) {
// TODO add examples for composed schema models without discriminators // TODO add examples for composed schema models without discriminators
CodegenDiscriminator disc = createDiscriminator(modelName, schema, openAPI); CodegenDiscriminator disc = createDiscriminator(modelName, schema, openAPI);
@ -1161,14 +1161,14 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
Schema schema = sc; Schema schema = sc;
String ref = sc.get$ref(); String ref = sc.get$ref();
if (ref != null) { if (ref != null) {
schema = ModelUtils.getSchema(this.openAPI, ModelUtils.getSimpleRef(ref)); schema = modelUtils.getSchema(modelUtils.getSimpleRef(ref));
} }
Object example = getObjectExample(schema); Object example = getObjectExample(schema);
if (example != null) { if (example != null) {
return example; return example;
} else if (simpleStringSchema(schema)) { } else if (simpleStringSchema(schema)) {
return propName + "_example"; return propName + "_example";
} else if (ModelUtils.isArraySchema(schema)) { } else if (modelUtils.isArraySchema(schema)) {
ArraySchema arraySchema = (ArraySchema) schema; ArraySchema arraySchema = (ArraySchema) schema;
Schema itemSchema = arraySchema.getItems(); Schema itemSchema = arraySchema.getItems();
example = getObjectExample(itemSchema); example = getObjectExample(itemSchema);
@ -1228,7 +1228,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
Content content = requestBody.getContent(); Content content = requestBody.getContent();
if (content.size() > 1) { if (content.size() > 1) {
// @see ModelUtils.getSchemaFromContent() // @see modelUtils.getSchemaFromContent()
once(LOGGER).warn("Multiple MediaTypes found, using only the first one"); once(LOGGER).warn("Multiple MediaTypes found, using only the first one");
} }
@ -1283,7 +1283,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
if (modelNameToSchemaCache == null) { if (modelNameToSchemaCache == null) {
// Create a cache to efficiently lookup schema based on model name. // Create a cache to efficiently lookup schema based on model name.
Map<String, Schema> m = new HashMap<String, Schema>(); Map<String, Schema> m = new HashMap<String, Schema>();
ModelUtils.getSchemas(openAPI).forEach((key, schema) -> { modelUtils.getSchemas().forEach((key, schema) -> {
m.put(toModelName(key), schema); m.put(toModelName(key), schema);
}); });
modelNameToSchemaCache = Collections.unmodifiableMap(m); modelNameToSchemaCache = Collections.unmodifiableMap(m);

View File

@ -469,11 +469,11 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "(str, " + getTypeDeclaration(inner) + ")"; return getSchemaType(p) + "(str, " + getTypeDeclaration(inner) + ")";
@ -673,33 +673,33 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
*/ */
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (Boolean.valueOf(p.getDefault().toString()) == false) if (Boolean.valueOf(p.getDefault().toString()) == false)
return "False"; return "False";
else else
return "True"; return "True";
} }
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (Pattern.compile("\r\n|\r|\n").matcher((String) p.getDefault()).find()) if (Pattern.compile("\r\n|\r|\n").matcher((String) p.getDefault()).find())
return "'''" + p.getDefault() + "'''"; return "'''" + p.getDefault() + "'''";
else else
return "'" + ((String) p.getDefault()).replaceAll("'", "\'") + "'"; return "'" + ((String) p.getDefault()).replaceAll("'", "\'") + "'";
} }
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
@ -726,24 +726,24 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
example = schema.getExample().toString(); example = schema.getExample().toString();
} }
if (ModelUtils.isNullType(schema) && null != example) { if (modelUtils.isNullType(schema) && null != example) {
// The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x, // The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x,
// though this tooling supports it. // though this tooling supports it.
return "None"; return "None";
} }
// correct "true"s into "True"s, since super.toExampleValue uses "toString()" on Java booleans // correct "true"s into "True"s, since super.toExampleValue uses "toString()" on Java booleans
if (ModelUtils.isBooleanSchema(schema) && null!=example) { if (modelUtils.isBooleanSchema(schema) && null!=example) {
if ("false".equalsIgnoreCase(example)) example = "False"; if ("false".equalsIgnoreCase(example)) example = "False";
else example = "True"; else example = "True";
} }
// correct "&#39;"s into "'"s after toString() // correct "&#39;"s into "'"s after toString()
if (ModelUtils.isStringSchema(schema) && schema.getDefault() != null && !ModelUtils.isDateSchema(schema) && !ModelUtils.isDateTimeSchema(schema)) { if (modelUtils.isStringSchema(schema) && schema.getDefault() != null && !modelUtils.isDateSchema(schema) && !modelUtils.isDateTimeSchema(schema)) {
example = (String) schema.getDefault(); example = (String) schema.getDefault();
} }
if (StringUtils.isNotBlank(example) && !"null".equals(example)) { if (StringUtils.isNotBlank(example) && !"null".equals(example)) {
if (ModelUtils.isStringSchema(schema)) { if (modelUtils.isStringSchema(schema)) {
example = "'" + example + "'"; example = "'" + example + "'";
} }
return example; return example;
@ -752,7 +752,7 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
if (schema.getEnum() != null && !schema.getEnum().isEmpty()) { if (schema.getEnum() != null && !schema.getEnum().isEmpty()) {
// Enum case: // Enum case:
example = schema.getEnum().get(0).toString(); example = schema.getEnum().get(0).toString();
if (ModelUtils.isStringSchema(schema)) { if (modelUtils.isStringSchema(schema)) {
example = "'" + escapeText(example) + "'"; example = "'" + escapeText(example) + "'";
} }
if (null == example) if (null == example)
@ -761,8 +761,8 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
return example; return example;
} else if (null != schema.get$ref()) { } else if (null != schema.get$ref()) {
// $ref case: // $ref case:
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI); Map<String, Schema> allDefinitions = modelUtils.getSchemas();
String ref = ModelUtils.getSimpleRef(schema.get$ref()); String ref = modelUtils.getSimpleRef(schema.get$ref());
if (allDefinitions != null) { if (allDefinitions != null) {
Schema refSchema = allDefinitions.get(ref); Schema refSchema = allDefinitions.get(ref);
if (null == refSchema) { if (null == refSchema) {
@ -781,18 +781,18 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
LOGGER.warn("allDefinitions not defined in toExampleValue!\n"); LOGGER.warn("allDefinitions not defined in toExampleValue!\n");
} }
} }
if (ModelUtils.isDateSchema(schema)) { if (modelUtils.isDateSchema(schema)) {
example = "datetime.datetime.strptime('1975-12-30', '%Y-%m-%d').date()"; example = "datetime.datetime.strptime('1975-12-30', '%Y-%m-%d').date()";
return example; return example;
} else if (ModelUtils.isDateTimeSchema(schema)) { } else if (modelUtils.isDateTimeSchema(schema)) {
example = "datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f')"; example = "datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f')";
return example; return example;
} else if (ModelUtils.isBinarySchema(schema)) { } else if (modelUtils.isBinarySchema(schema)) {
example = "bytes(b'blah')"; example = "bytes(b'blah')";
return example; return example;
} else if (ModelUtils.isByteArraySchema(schema)) { } else if (modelUtils.isByteArraySchema(schema)) {
example = "YQ=="; example = "YQ==";
} else if (ModelUtils.isStringSchema(schema)) { } else if (modelUtils.isStringSchema(schema)) {
// a BigDecimal: // a BigDecimal:
if ("Number".equalsIgnoreCase(schema.getFormat())) {return "1";} if ("Number".equalsIgnoreCase(schema.getFormat())) {return "1";}
if (StringUtils.isNotBlank(schema.getPattern())) { if (StringUtils.isNotBlank(schema.getPattern())) {
@ -822,25 +822,25 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
for (int i=0;i<len;i++) example += i; for (int i=0;i<len;i++) example += i;
} }
} }
} else if (ModelUtils.isIntegerSchema(schema)) { } else if (modelUtils.isIntegerSchema(schema)) {
if (schema.getMinimum() != null) if (schema.getMinimum() != null)
example = schema.getMinimum().toString(); example = schema.getMinimum().toString();
else else
example = "56"; example = "56";
} else if (ModelUtils.isNumberSchema(schema)) { } else if (modelUtils.isNumberSchema(schema)) {
if (schema.getMinimum() != null) if (schema.getMinimum() != null)
example = schema.getMinimum().toString(); example = schema.getMinimum().toString();
else else
example = "1.337"; example = "1.337";
} else if (ModelUtils.isBooleanSchema(schema)) { } else if (modelUtils.isBooleanSchema(schema)) {
example = "True"; example = "True";
} else if (ModelUtils.isArraySchema(schema)) { } else if (modelUtils.isArraySchema(schema)) {
if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) { if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) {
included_schemas.add(schema.getTitle()); included_schemas.add(schema.getTitle());
} }
ArraySchema arrayschema = (ArraySchema) schema; ArraySchema arrayschema = (ArraySchema) schema;
example = "[\n" + indentation_string + toExampleValueRecursive(arrayschema.getItems(), included_schemas, indentation+1) + "\n" + indentation_string + "]"; example = "[\n" + indentation_string + toExampleValueRecursive(arrayschema.getItems(), included_schemas, indentation+1) + "\n" + indentation_string + "]";
} else if (ModelUtils.isMapSchema(schema)) { } else if (modelUtils.isMapSchema(schema)) {
if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) { if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) {
included_schemas.add(schema.getTitle()); included_schemas.add(schema.getTitle());
} }
@ -850,7 +850,7 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
String the_key = "'key'"; String the_key = "'key'";
if (additional.getEnum() != null && !additional.getEnum().isEmpty()) { if (additional.getEnum() != null && !additional.getEnum().isEmpty()) {
the_key = additional.getEnum().get(0).toString(); the_key = additional.getEnum().get(0).toString();
if (ModelUtils.isStringSchema(additional)) { if (modelUtils.isStringSchema(additional)) {
the_key = "'" + escapeText(the_key) + "'"; the_key = "'" + escapeText(the_key) + "'";
} }
} }
@ -858,7 +858,7 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
} else { } else {
example = "{ }"; example = "{ }";
} }
} else if (ModelUtils.isObjectSchema(schema)) { } else if (modelUtils.isObjectSchema(schema)) {
if (StringUtils.isBlank(schema.getTitle())) { if (StringUtils.isBlank(schema.getTitle())) {
example = "None"; example = "None";
return example; return example;
@ -916,7 +916,7 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
LOGGER.warn("Type " + schema.getType() + " not handled properly in toExampleValue"); LOGGER.warn("Type " + schema.getType() + " not handled properly in toExampleValue");
} }
if (ModelUtils.isStringSchema(schema)) { if (modelUtils.isStringSchema(schema)) {
example = "'" + escapeText(example) + "'"; example = "'" + escapeText(example) + "'";
} }

View File

@ -355,11 +355,11 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner)+ "]"; return getSchemaType(p) + "[" + getTypeDeclaration(inner)+ "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "(" + getTypeDeclaration(inner) + ")"; return getSchemaType(p) + "(" + getTypeDeclaration(inner) + ")";
} }
@ -629,33 +629,33 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig {
*/ */
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (Boolean.valueOf(p.getDefault().toString()) == false) if (Boolean.valueOf(p.getDefault().toString()) == false)
return "FALSE"; return "FALSE";
else else
return "TRUE"; return "TRUE";
} }
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
// TODO // TODO
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (Pattern.compile("\r\n|\r|\n").matcher((String) p.getDefault()).find()) if (Pattern.compile("\r\n|\r|\n").matcher((String) p.getDefault()).find())
return "'''" + p.getDefault() + "'''"; return "'''" + p.getDefault() + "'''";
else else
return "'" + ((String) p.getDefault()).replaceAll("'","\'") + "'"; return "'" + ((String) p.getDefault()).replaceAll("'","\'") + "'";
} }
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }

View File

@ -440,7 +440,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
if (inner == null) { if (inner == null) {
@ -448,7 +448,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
inner = new StringSchema().description("TODO default missing array inner type to string"); inner = new StringSchema().description("TODO default missing array inner type to string");
} }
return "Vec<" + getTypeDeclaration(inner) + ">"; return "Vec<" + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
if (inner == null) { if (inner == null) {
LOGGER.warn(p.getName() + "(map property) does not have a proper inner type defined. Default to string"); LOGGER.warn(p.getName() + "(map property) does not have a proper inner type defined. Default to string");

View File

@ -266,7 +266,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
" (--enable-post-process-file for CLI)."); " (--enable-post-process-file for CLI).");
} }
if (!Boolean.TRUE.equals(ModelUtils.isGenerateAliasAsModel())) { if (!Boolean.TRUE.equals(modelUtils.isGenerateAliasAsModel())) {
LOGGER.warn("generateAliasAsModel is set to false, which means array/map will be generated as model instead and the resulting code may have issues. Please enable `generateAliasAsModel` to address the issue."); LOGGER.warn("generateAliasAsModel is set to false, which means array/map will be generated as model instead and the resulting code may have issues. Please enable `generateAliasAsModel` to address the issue.");
} }
@ -333,7 +333,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
Info info = openAPI.getInfo(); Info info = openAPI.getInfo();
@ -606,7 +606,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List<Server> servers) { public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List<Server> servers) {
Map<String, Schema> definitions = ModelUtils.getSchemas(this.openAPI); Map<String, Schema> definitions = modelUtils.getSchemas();
CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers);
String pathFormatString = op.path; String pathFormatString = op.path;
@ -762,7 +762,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
// Determine the types that this operation produces. `getProducesInfo` // Determine the types that this operation produces. `getProducesInfo`
// simply lists all the types, and then we add the correct imports to // simply lists all the types, and then we add the correct imports to
// the generated library. // the generated library.
List<String> produces = new ArrayList<String>(getProducesInfo(openAPI, operation)); List<String> produces = new ArrayList<String>(getProducesInfo(operation));
boolean producesXml = false; boolean producesXml = false;
boolean producesPlainText = false; boolean producesPlainText = false;
if (produces != null && !produces.isEmpty()) { if (produces != null && !produces.isEmpty()) {
@ -925,7 +925,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
Schema response = (Schema) rsp.schema; Schema response = (Schema) rsp.schema;
// Check whether we're returning an object with a defined XML namespace. // Check whether we're returning an object with a defined XML namespace.
if (response != null && (!StringUtils.isEmpty(response.get$ref()))) { if (response != null && (!StringUtils.isEmpty(response.get$ref()))) {
Schema model = definitions.get(ModelUtils.getSimpleRef(response.get$ref())); Schema model = definitions.get(modelUtils.getSimpleRef(response.get$ref()));
if ((model != null)) { if ((model != null)) {
XML xml = model.getXml(); XML xml = model.getXml();
if ((xml != null) && (xml.getNamespace() != null)) { if ((xml != null) && (xml.getNamespace() != null)) {
@ -1114,7 +1114,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
// restore things to sensible values. // restore things to sensible values.
@Override @Override
public CodegenParameter fromRequestBody(RequestBody body, Set<String> imports, String bodyParameterName) { public CodegenParameter fromRequestBody(RequestBody body, Set<String> imports, String bodyParameterName) {
Schema original_schema = ModelUtils.getSchemaFromRequestBody(body); Schema original_schema = modelUtils.getSchemaFromRequestBody(body);
CodegenParameter codegenParameter = super.fromRequestBody(body, imports, bodyParameterName); CodegenParameter codegenParameter = super.fromRequestBody(body, imports, bodyParameterName);
if (StringUtils.isNotBlank(original_schema.get$ref())) { if (StringUtils.isNotBlank(original_schema.get$ref())) {
@ -1124,7 +1124,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
codegenParameter.isPrimitiveType = false; codegenParameter.isPrimitiveType = false;
codegenParameter.isArray = false; codegenParameter.isArray = false;
codegenParameter.isString = false; codegenParameter.isString = false;
codegenParameter.isByteArray = ModelUtils.isByteArraySchema(original_schema); codegenParameter.isByteArray = modelUtils.isByteArraySchema(original_schema);
// This is a model, so should only have an example if explicitly // This is a model, so should only have an example if explicitly
@ -1142,12 +1142,12 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
String innerType = getTypeDeclaration(inner); String innerType = getTypeDeclaration(inner);
return typeMapping.get("array") + "<" + innerType + ">"; return typeMapping.get("array") + "<" + innerType + ">";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
String innerType = getTypeDeclaration(inner); String innerType = getTypeDeclaration(inner);
StringBuilder typeDeclaration = new StringBuilder(typeMapping.get("map")).append("<").append(typeMapping.get("string")).append(", "); StringBuilder typeDeclaration = new StringBuilder(typeMapping.get("map")).append("<").append(typeMapping.get("string")).append(", ");
@ -1177,11 +1177,11 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String toInstantiationType(Schema p) { public String toInstantiationType(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return instantiationTypes.get("array") + "<" + getSchemaType(inner) + ">"; return instantiationTypes.get("array") + "<" + getSchemaType(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return instantiationTypes.get("map") + "<" + typeMapping.get("string") + ", " + getSchemaType(inner) + ">"; return instantiationTypes.get("map") + "<" + typeMapping.get("string") + ", " + getSchemaType(inner) + ">";
} else { } else {
@ -1191,14 +1191,14 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public CodegenModel fromModel(String name, Schema model) { public CodegenModel fromModel(String name, Schema model) {
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI); Map<String, Schema> allDefinitions = modelUtils.getSchemas();
CodegenModel mdl = super.fromModel(name, model); CodegenModel mdl = super.fromModel(name, model);
mdl.vendorExtensions.put("x-upper-case-name", name.toUpperCase(Locale.ROOT)); mdl.vendorExtensions.put("x-upper-case-name", name.toUpperCase(Locale.ROOT));
if (!StringUtils.isEmpty(model.get$ref())) { if (!StringUtils.isEmpty(model.get$ref())) {
Schema schema = allDefinitions.get(ModelUtils.getSimpleRef(model.get$ref())); Schema schema = allDefinitions.get(modelUtils.getSimpleRef(model.get$ref()));
mdl.dataType = typeMapping.get(schema.getType()); mdl.dataType = typeMapping.get(schema.getType());
} }
if (ModelUtils.isArraySchema(model)) { if (modelUtils.isArraySchema(model)) {
ArraySchema am = (ArraySchema) model; ArraySchema am = (ArraySchema) model;
String xmlName = null; String xmlName = null;
@ -1213,7 +1213,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
am.getItems() != null && am.getItems() != null &&
!StringUtils.isEmpty(am.getItems().get$ref())) { !StringUtils.isEmpty(am.getItems().get$ref())) {
Schema inner_schema = allDefinitions.get( Schema inner_schema = allDefinitions.get(
ModelUtils.getSimpleRef(am.getItems().get$ref())); modelUtils.getSimpleRef(am.getItems().get$ref()));
if (inner_schema.getXml() != null && if (inner_schema.getXml() != null &&
inner_schema.getXml().getName() != null) { inner_schema.getXml().getName() != null) {
@ -1376,29 +1376,29 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
String defaultValue = null; String defaultValue = null;
if ((ModelUtils.isNullable(p)) && (p.getDefault() != null) && (p.getDefault().toString().equalsIgnoreCase("null"))) if ((modelUtils.isNullable(p)) && (p.getDefault() != null) && (p.getDefault().toString().equalsIgnoreCase("null")))
return "swagger::Nullable::Null"; return "swagger::Nullable::Null";
else if (ModelUtils.isBooleanSchema(p)) { else if (modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (p.getDefault().toString().equalsIgnoreCase("false")) if (p.getDefault().toString().equalsIgnoreCase("false"))
defaultValue = "false"; defaultValue = "false";
else else
defaultValue = "true"; defaultValue = "true";
} }
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
defaultValue = p.getDefault().toString(); defaultValue = p.getDefault().toString();
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
defaultValue = p.getDefault().toString(); defaultValue = p.getDefault().toString();
} }
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
defaultValue = "\"" + (String) p.getDefault() + "\".to_string()"; defaultValue = "\"" + (String) p.getDefault() + "\".to_string()";
} }
} }
if ((defaultValue != null) && (ModelUtils.isNullable(p))) if ((defaultValue != null) && (modelUtils.isNullable(p)))
defaultValue = "swagger::Nullable::Present(" + defaultValue + ")"; defaultValue = "swagger::Nullable::Present(" + defaultValue + ")";
return defaultValue; return defaultValue;
} }

View File

@ -271,27 +271,27 @@ public class ScalaAkkaClientCodegen extends AbstractScalaCodegen implements Code
return "None"; return "None";
} }
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
return null; return null;
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
return null; return null;
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
return null; return null;
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
return null; return null;
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
return null; return null;
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p)); String inner = getSchemaType(getAdditionalProperties(p));
return "Map[String, " + inner + "].empty "; return "Map[String, " + inner + "].empty ";
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems()); String inner = getSchemaType(ap.getItems());
if (ModelUtils.isSet(ap)) { if (modelUtils.isSet(ap)) {
return "Set[" + inner + "].empty "; return "Set[" + inner + "].empty ";
} }
return "Seq[" + inner + "].empty "; return "Seq[" + inner + "].empty ";
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
return null; return null;
} else { } else {
return null; return null;

View File

@ -260,11 +260,11 @@ public class ScalaFinchServerCodegen extends DefaultCodegen implements CodegenCo
@SuppressWarnings("Duplicates") @SuppressWarnings("Duplicates")
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]";

View File

@ -250,7 +250,7 @@ public class ScalaGatlingCodegen extends AbstractScalaCodegen implements Codegen
* @param openAPI input openapi document * @param openAPI input openapi document
*/ */
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
for (String pathname : openAPI.getPaths().keySet()) { for (String pathname : openAPI.getPaths().keySet()) {
PathItem path = openAPI.getPaths().get(pathname); PathItem path = openAPI.getPaths().get(pathname);
if (path.readOperations() == null) { if (path.readOperations() == null) {
@ -382,11 +382,11 @@ public class ScalaGatlingCodegen extends AbstractScalaCodegen implements Codegen
*/ */
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]";
} }

View File

@ -333,48 +333,48 @@ public class ScalaPlayFrameworkServerCodegen extends AbstractScalaCodegen implem
return p.getDefault().toString(); return p.getDefault().toString();
} }
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
return "false"; return "false";
} }
if (ModelUtils.isDateSchema(p)) { if (modelUtils.isDateSchema(p)) {
return "LocalDate.now"; return "LocalDate.now";
} }
if (ModelUtils.isDateTimeSchema(p)) { if (modelUtils.isDateTimeSchema(p)) {
return "OffsetDateTime.now"; return "OffsetDateTime.now";
} }
if (ModelUtils.isDoubleSchema(p)) { if (modelUtils.isDoubleSchema(p)) {
return "0.0"; return "0.0";
} }
if (ModelUtils.isFloatSchema(p)) { if (modelUtils.isFloatSchema(p)) {
return "0.0F"; return "0.0F";
} }
if (ModelUtils.isIntegerSchema(p)) { if (modelUtils.isIntegerSchema(p)) {
return "0"; return "0";
} }
if (ModelUtils.isLongSchema(p)) { if (modelUtils.isLongSchema(p)) {
return "0L"; return "0L";
} }
if (ModelUtils.isStringSchema(p)) { if (modelUtils.isStringSchema(p)) {
return "\"\""; return "\"\"";
} }
if (ModelUtils.isMapSchema(p)) { if (modelUtils.isMapSchema(p)) {
Schema ap = getAdditionalProperties(p); Schema ap = getAdditionalProperties(p);
String inner = getSchemaType(ap); String inner = getSchemaType(ap);
return "Map.empty[String, " + inner + "]"; return "Map.empty[String, " + inner + "]";
} }
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
Schema items = ((ArraySchema) p).getItems(); Schema items = ((ArraySchema) p).getItems();
String inner = getSchemaType(items); String inner = getSchemaType(items);
if (ModelUtils.isSet(p)) { if (modelUtils.isSet(p)) {
return "Set.empty[" + inner + "]"; return "Set.empty[" + inner + "]";
} }
return "List.empty[" + inner + "]"; return "List.empty[" + inner + "]";

View File

@ -275,27 +275,27 @@ public class ScalaSttpClientCodegen extends AbstractScalaCodegen implements Code
return "None"; return "None";
} }
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
return null; return null;
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
return null; return null;
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
return null; return null;
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
return null; return null;
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
return null; return null;
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p)); String inner = getSchemaType(getAdditionalProperties(p));
return "Map[String, " + inner + "].empty "; return "Map[String, " + inner + "].empty ";
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems()); String inner = getSchemaType(ap.getItems());
if (ModelUtils.isSet(ap)) { if (modelUtils.isSet(ap)) {
return "Set[" + inner + "].empty "; return "Set[" + inner + "].empty ";
} }
return "Seq[" + inner + "].empty "; return "Seq[" + inner + "].empty ";
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
return null; return null;
} else { } else {
return null; return null;

View File

@ -172,29 +172,29 @@ public class ScalazClientCodegen extends AbstractScalaCodegen implements Codegen
} }
// comment out the following as the default value is no handled differently // comment out the following as the default value is no handled differently
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
return null; return null;
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
return null; return null;
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
return null; return null;
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
return null; return null;
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
return null; return null;
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p)); String inner = getSchemaType(getAdditionalProperties(p));
return "Map.empty[String, " + inner + "] "; return "Map.empty[String, " + inner + "] ";
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems()); String inner = getSchemaType(ap.getItems());
String collectionType = ModelUtils.isSet(ap) ? typeMapping.get("set") : typeMapping.get("array"); String collectionType = modelUtils.isSet(ap) ? typeMapping.get("set") : typeMapping.get("array");
// We assume that users would map these collections to a monoid with an identity function // We assume that users would map these collections to a monoid with an identity function
// There's no reason to assume mutable structure here (which may make consumption more difficult) // There's no reason to assume mutable structure here (which may make consumption more difficult)
return collectionType + ".empty[" + inner + "] "; return collectionType + ".empty[" + inner + "] ";
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
return null; return null;
} else { } else {
return null; return null;

View File

@ -524,8 +524,8 @@ public class SpringCodegen extends AbstractJavaCodegen
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
/* TODO the following logic should not need anymore in OAS 3.0 /* TODO the following logic should not need anymore in OAS 3.0
if ("/".equals(swagger.getBasePath())) { if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath(""); swagger.setBasePath("");

View File

@ -130,11 +130,11 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]";
} }
@ -158,8 +158,8 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
super.preprocessOpenAPI(openAPI); super.preprocessOpenAPI();
if (openAPI.getInfo() != null) { if (openAPI.getInfo() != null) {
Info info = openAPI.getInfo(); Info info = openAPI.getInfo();

View File

@ -112,11 +112,11 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]";
} }
@ -203,11 +203,11 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
} }
} }
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
Info info = openAPI.getInfo(); Info info = openAPI.getInfo();
info.setDescription(toHtml(info.getDescription())); info.setDescription(toHtml(info.getDescription()));
info.setTitle(toHtml(info.getTitle())); info.setTitle(toHtml(info.getTitle()));
Map<String, Schema> models = ModelUtils.getSchemas(openAPI); Map<String, Schema> models = modelUtils.getSchemas();
for (Schema model : models.values()) { for (Schema model : models.values()) {
model.setDescription(toHtml(model.getDescription())); model.setDescription(toHtml(model.getDescription()));
model.setTitle(toHtml(model.getTitle())); model.setTitle(toHtml(model.getTitle()));

View File

@ -505,11 +505,11 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]"; return "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return "[String:" + getTypeDeclaration(inner) + "]"; return "[String:" + getTypeDeclaration(inner) + "]";
} }
@ -601,18 +601,18 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig {
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (p.getEnum() != null && !p.getEnum().isEmpty()) { if (p.getEnum() != null && !p.getEnum().isEmpty()) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (ModelUtils.isStringSchema(p)) { if (modelUtils.isStringSchema(p)) {
return "." + toEnumVarName(escapeText((String) p.getDefault()), p.getType()); return "." + toEnumVarName(escapeText((String) p.getDefault()), p.getType());
} else { } else {
return "." + toEnumVarName(escapeText(p.getDefault().toString()), p.getType()); return "." + toEnumVarName(escapeText(p.getDefault().toString()), p.getType());
} }
} }
} }
if (ModelUtils.isIntegerSchema(p) || ModelUtils.isNumberSchema(p) || ModelUtils.isBooleanSchema(p)) { if (modelUtils.isIntegerSchema(p) || modelUtils.isNumberSchema(p) || modelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "\"" + escapeText((String) p.getDefault()) + "\""; return "\"" + escapeText((String) p.getDefault()) + "\"";
} }
@ -622,9 +622,9 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String toInstantiationType(Schema p) { public String toInstantiationType(Schema p) {
if (ModelUtils.isMapSchema(p)) { if (modelUtils.isMapSchema(p)) {
return getSchemaType(getAdditionalProperties(p)); return getSchemaType(getAdditionalProperties(p));
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems()); String inner = getSchemaType(ap.getItems());
return "[" + inner + "]"; return "[" + inner + "]";
@ -737,7 +737,7 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public CodegenModel fromModel(String name, Schema model) { public CodegenModel fromModel(String name, Schema model) {
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI); Map<String, Schema> allDefinitions = modelUtils.getSchemas();
CodegenModel codegenModel = super.fromModel(name, model); CodegenModel codegenModel = super.fromModel(name, model);
if (codegenModel.description != null) { if (codegenModel.description != null) {
codegenModel.imports.add("ApiModel"); codegenModel.imports.add("ApiModel");

View File

@ -516,11 +516,11 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return ModelUtils.isSet(p) ? "Set<" + getTypeDeclaration(inner) + ">" : "[" + getTypeDeclaration(inner) + "]"; return modelUtils.isSet(p) ? "Set<" + getTypeDeclaration(inner) + ">" : "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p); Schema inner = getAdditionalProperties(p);
return "[String:" + getTypeDeclaration(inner) + "]"; return "[String:" + getTypeDeclaration(inner) + "]";
} }
@ -612,7 +612,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (p.getEnum() != null && !p.getEnum().isEmpty()) { if (p.getEnum() != null && !p.getEnum().isEmpty()) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (ModelUtils.isStringSchema(p)) { if (modelUtils.isStringSchema(p)) {
return "." + toEnumVarName(escapeText((String) p.getDefault()), p.getType()); return "." + toEnumVarName(escapeText((String) p.getDefault()), p.getType());
} else { } else {
return "." + toEnumVarName(escapeText(p.getDefault().toString()), p.getType()); return "." + toEnumVarName(escapeText(p.getDefault().toString()), p.getType());
@ -620,15 +620,15 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig
} }
} }
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (ModelUtils.isIntegerSchema(p) || ModelUtils.isNumberSchema(p) || ModelUtils.isBooleanSchema(p)) { if (modelUtils.isIntegerSchema(p) || modelUtils.isNumberSchema(p) || modelUtils.isBooleanSchema(p)) {
return p.getDefault().toString(); return p.getDefault().toString();
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
// Datetime time stamps in Swift are expressed as Seconds with Microsecond precision. // Datetime time stamps in Swift are expressed as Seconds with Microsecond precision.
// In Java, we need to be creative to get the Timestamp in Microseconds as a long. // In Java, we need to be creative to get the Timestamp in Microseconds as a long.
Instant instant = ((OffsetDateTime) p.getDefault()).toInstant(); Instant instant = ((OffsetDateTime) p.getDefault()).toInstant();
long epochMicro = TimeUnit.SECONDS.toMicros(instant.getEpochSecond()) + ((long) instant.get(ChronoField.MICRO_OF_SECOND)); long epochMicro = TimeUnit.SECONDS.toMicros(instant.getEpochSecond()) + ((long) instant.get(ChronoField.MICRO_OF_SECOND));
return "Date(timeIntervalSince1970: " + String.valueOf(epochMicro) + ".0 / 1_000_000)"; return "Date(timeIntervalSince1970: " + String.valueOf(epochMicro) + ".0 / 1_000_000)";
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
return "\"" + escapeText((String) p.getDefault()) + "\""; return "\"" + escapeText((String) p.getDefault()) + "\"";
} }
// TODO: Handle more cases from `ModelUtils`, such as Date // TODO: Handle more cases from `ModelUtils`, such as Date
@ -638,12 +638,12 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig
@Override @Override
public String toInstantiationType(Schema p) { public String toInstantiationType(Schema p) {
if (ModelUtils.isMapSchema(p)) { if (modelUtils.isMapSchema(p)) {
return getSchemaType(getAdditionalProperties(p)); return getSchemaType(getAdditionalProperties(p));
} else if (ModelUtils.isArraySchema(p)) { } else if (modelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems()); String inner = getSchemaType(ap.getItems());
return ModelUtils.isSet(p) ? "Set<" + inner + ">" : "[" + inner + "]"; return modelUtils.isSet(p) ? "Set<" + inner + ">" : "[" + inner + "]";
} }
return null; return null;
} }
@ -753,7 +753,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig
@Override @Override
public CodegenModel fromModel(String name, Schema model) { public CodegenModel fromModel(String name, Schema model) {
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI); Map<String, Schema> allDefinitions = modelUtils.getSchemas();
CodegenModel codegenModel = super.fromModel(name, model); CodegenModel codegenModel = super.fromModel(name, model);
if (codegenModel.description != null) { if (codegenModel.description != null) {
codegenModel.imports.add("ApiModel"); codegenModel.imports.add("ApiModel");

View File

@ -362,7 +362,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isFileSchema(p)) { if (modelUtils.isFileSchema(p)) {
return "Blob"; return "Blob";
} else { } else {
return super.getTypeDeclaration(p); return super.getTypeDeclaration(p);

View File

@ -249,7 +249,7 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo
} }
@Override @Override
public void preprocessOpenAPI(OpenAPI openAPI) { public void preprocessOpenAPI() {
if (additionalProperties.containsKey(NPM_NAME)) { if (additionalProperties.containsKey(NPM_NAME)) {
@ -424,24 +424,24 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo
protected String getParameterDataType(Parameter parameter, Schema p) { protected String getParameterDataType(Parameter parameter, Schema p) {
// handle enums of various data types // handle enums of various data types
Schema inner; Schema inner;
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
ArraySchema mp1 = (ArraySchema) p; ArraySchema mp1 = (ArraySchema) p;
inner = mp1.getItems(); inner = mp1.getItems();
return this.getSchemaType(p) + "<" + this.getParameterDataType(parameter, inner) + ">"; return this.getSchemaType(p) + "<" + this.getParameterDataType(parameter, inner) + ">";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
inner = (Schema) p.getAdditionalProperties(); inner = (Schema) p.getAdditionalProperties();
return "{ [key: string]: " + this.getParameterDataType(parameter, inner) + "; }"; return "{ [key: string]: " + this.getParameterDataType(parameter, inner) + "; }";
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
// Handle string enums // Handle string enums
if (p.getEnum() != null) { if (p.getEnum() != null) {
return enumValuesToEnumTypeUnion(p.getEnum(), "string"); return enumValuesToEnumTypeUnion(p.getEnum(), "string");
} }
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
// Handle integer enums // Handle integer enums
if (p.getEnum() != null) { if (p.getEnum() != null) {
return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum())); return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum()));
} }
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
// Handle double enums // Handle double enums
if (p.getEnum() != null) { if (p.getEnum() != null) {
return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum())); return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum()));
@ -488,23 +488,23 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override @Override
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (modelUtils.isBooleanSchema(p)) {
return UNDEFINED_VALUE; return UNDEFINED_VALUE;
} else if (ModelUtils.isDateSchema(p)) { } else if (modelUtils.isDateSchema(p)) {
return UNDEFINED_VALUE; return UNDEFINED_VALUE;
} else if (ModelUtils.isDateTimeSchema(p)) { } else if (modelUtils.isDateTimeSchema(p)) {
return UNDEFINED_VALUE; return UNDEFINED_VALUE;
} else if (ModelUtils.isNumberSchema(p)) { } else if (modelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
return UNDEFINED_VALUE; return UNDEFINED_VALUE;
} else if (ModelUtils.isIntegerSchema(p)) { } else if (modelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} }
return UNDEFINED_VALUE; return UNDEFINED_VALUE;
} else if (ModelUtils.isStringSchema(p)) { } else if (modelUtils.isStringSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return "'" + (String) p.getDefault() + "'"; return "'" + (String) p.getDefault() + "'";
} }
@ -837,15 +837,15 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
Schema inner; Schema inner;
if (ModelUtils.isArraySchema(p)) { if (modelUtils.isArraySchema(p)) {
inner = ((ArraySchema) p).getItems(); inner = ((ArraySchema) p).getItems();
return this.getSchemaType(p) + "<" + this.getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, inner)) + ">"; return this.getSchemaType(p) + "<" + this.getTypeDeclaration(modelUtils.unaliasSchema(inner)) + ">";
} else if (ModelUtils.isMapSchema(p)) { } else if (modelUtils.isMapSchema(p)) {
inner = (Schema) p.getAdditionalProperties(); inner = (Schema) p.getAdditionalProperties();
return "{ [key: string]: " + this.getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, inner)) + "; }"; return "{ [key: string]: " + this.getTypeDeclaration(modelUtils.unaliasSchema(inner)) + "; }";
} else if (ModelUtils.isFileSchema(p)) { } else if (modelUtils.isFileSchema(p)) {
return "HttpFile"; return "HttpFile";
} else if (ModelUtils.isBinarySchema(p)) { } else if (modelUtils.isBinarySchema(p)) {
return "any"; return "any";
} else { } else {
return super.getTypeDeclaration(p); return super.getTypeDeclaration(p);

View File

@ -166,9 +166,9 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isFileSchema(p)) { if (modelUtils.isFileSchema(p)) {
return "Blob"; return "Blob";
} else if (ModelUtils.isBinarySchema(p)) { } else if (modelUtils.isBinarySchema(p)) {
return "Blob"; return "Blob";
} }
return super.getTypeDeclaration(p); return super.getTypeDeclaration(p);

View File

@ -94,7 +94,7 @@ public class TypeScriptJqueryClientCodegen extends AbstractTypeScriptClientCodeg
@Override @Override
public String getSchemaType(Schema p) { public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p); String openAPIType = super.getSchemaType(p);
if (ModelUtils.isStringSchema(p)) { if (modelUtils.isStringSchema(p)) {
if (p.getEnum() != null) { if (p.getEnum() != null) {
return openAPIType; return openAPIType;
} }

View File

@ -87,14 +87,14 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isFileSchema(p)) { if (modelUtils.isFileSchema(p)) {
// There are two file types: // There are two file types:
// 1) RequestFile: the parameter for the request lib when uploading a file // 1) RequestFile: the parameter for the request lib when uploading a file
// (https://github.com/request/request#multipartform-data-multipart-form-uploads) // (https://github.com/request/request#multipartform-data-multipart-form-uploads)
// 2) Buffer: for downloading files. // 2) Buffer: for downloading files.
// Use RequestFile as a default. The return type is fixed to Buffer in handleMethodResponse. // Use RequestFile as a default. The return type is fixed to Buffer in handleMethodResponse.
return "RequestFile"; return "RequestFile";
} else if (ModelUtils.isBinarySchema(p)) { } else if (modelUtils.isBinarySchema(p)) {
return "Buffer"; return "Buffer";
} }
return super.getTypeDeclaration(p); return super.getTypeDeclaration(p);

View File

@ -107,9 +107,9 @@ public class TypeScriptReduxQueryClientCodegen extends AbstractTypeScriptClientC
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isFileSchema(p)) { if (modelUtils.isFileSchema(p)) {
return "Blob"; return "Blob";
} else if (ModelUtils.isBinarySchema(p)) { } else if (modelUtils.isBinarySchema(p)) {
return "Blob"; return "Blob";
} }
return super.getTypeDeclaration(p); return super.getTypeDeclaration(p);

View File

@ -108,9 +108,9 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen
@Override @Override
public String getTypeDeclaration(Schema p) { public String getTypeDeclaration(Schema p) {
if (ModelUtils.isFileSchema(p)) { if (modelUtils.isFileSchema(p)) {
return "Blob"; return "Blob";
} else if (ModelUtils.isBinarySchema(p)) { } else if (modelUtils.isBinarySchema(p)) {
return "Blob"; return "Blob";
} }
return super.getTypeDeclaration(p); return super.getTypeDeclaration(p);

View File

@ -59,16 +59,20 @@ public class ModelUtils {
private static final String URI_FORMAT = "uri"; private static final String URI_FORMAT = "uri";
private static final String generateAliasAsModelKey = "generateAliasAsModel"; //private static final String generateAliasAsModelKey = "generateAliasAsModel";
// A vendor extension to track the value of the 'swagger' field in a 2.0 doc, if applicable. // A vendor extension to track the value of the 'swagger' field in a 2.0 doc, if applicable.
private static final String openapiDocVersion = "x-original-swagger-version"; private static final String openapiDocVersion = "x-original-swagger-version";
// A vendor extension to track the value of the 'disallowAdditionalPropertiesIfNotPresent' CLI // A vendor extension to track the value of the 'disallowAdditionalPropertiesIfNotPresent' CLI
private static final String disallowAdditionalPropertiesIfNotPresent = "x-disallow-additional-properties-if-not-present"; //private static final String disallowAdditionalPropertiesIfNotPresent = "x-disallow-additional-properties-if-not-present";
private static final String freeFormExplicit = "x-is-free-form"; private static final String freeFormExplicit = "x-is-free-form";
private OpenAPI openAPI;
private boolean generateAliasAsModelKey;
private boolean disallowAdditionalPropertiesIfNotPresent;
private static ObjectMapper JSON_MAPPER, YAML_MAPPER; private static ObjectMapper JSON_MAPPER, YAML_MAPPER;
static { static {
@ -76,23 +80,37 @@ public class ModelUtils {
YAML_MAPPER = ObjectMapperFactory.createYaml(); YAML_MAPPER = ObjectMapperFactory.createYaml();
} }
public static void setDisallowAdditionalPropertiesIfNotPresent(boolean value) { public ModelUtils(OpenAPI openAPI) {
GlobalSettings.setProperty(disallowAdditionalPropertiesIfNotPresent, Boolean.toString(value)); this.openAPI = openAPI;
this.generateAliasAsModelKey = Boolean.parseBoolean(GlobalSettings.getProperty("generateAliasAsModelKey", "false"));
this.disallowAdditionalPropertiesIfNotPresent = Boolean.parseBoolean(GlobalSettings.getProperty("x-disallow-additional-properties-if-not-present", "true"));
} }
public static boolean isDisallowAdditionalPropertiesIfNotPresent() { public OpenAPI getOpenAPI() {
return Boolean.parseBoolean(GlobalSettings.getProperty(disallowAdditionalPropertiesIfNotPresent, "true")); return this.openAPI;
} }
public static void setGenerateAliasAsModel(boolean value) { public void setOpenAPI(OpenAPI openAPI) {
GlobalSettings.setProperty(generateAliasAsModelKey, Boolean.toString(value)); this.openAPI = openAPI;
} }
public static boolean isGenerateAliasAsModel() { public void setDisallowAdditionalPropertiesIfNotPresent(boolean value) {
return Boolean.parseBoolean(GlobalSettings.getProperty(generateAliasAsModelKey, "false")); this.disallowAdditionalPropertiesIfNotPresent = value;
} }
public static boolean isGenerateAliasAsModel(Schema schema) { public boolean isDisallowAdditionalPropertiesIfNotPresent() {
return this.disallowAdditionalPropertiesIfNotPresent;
}
public void setGenerateAliasAsModel(boolean value) {
this.generateAliasAsModelKey = value;
}
public boolean isGenerateAliasAsModel() {
return this.generateAliasAsModelKey;
}
public boolean isGenerateAliasAsModel(Schema schema) {
return isGenerateAliasAsModel() || (schema.getExtensions() != null && schema.getExtensions().getOrDefault("x-generate-alias-as-model", false).equals(true)); return isGenerateAliasAsModel() || (schema.getExtensions() != null && schema.getExtensions().getOrDefault("x-generate-alias-as-model", false).equals(true));
} }
@ -103,7 +121,7 @@ public class ModelUtils {
* @param models Map of models * @param models Map of models
* @return model * @return model
*/ */
public static CodegenModel getModelByName(final String name, final Map<String, Object> models) { public CodegenModel getModelByName(final String name, final Map<String, Object> models) {
final Object data = models.get(name); final Object data = models.get(name);
if (data instanceof Map) { if (data instanceof Map) {
final Map<?, ?> dataMap = (Map<?, ?>) data; final Map<?, ?> dataMap = (Map<?, ?>) data;
@ -127,13 +145,12 @@ public class ModelUtils {
/** /**
* Return the list of all schemas in the 'components/schemas' section used in the openAPI specification * Return the list of all schemas in the 'components/schemas' section used in the openAPI specification
* *
* @param openAPI specification
* @return schemas a list of used schemas * @return schemas a list of used schemas
*/ */
public static List<String> getAllUsedSchemas(OpenAPI openAPI) { public List<String> getAllUsedSchemas() {
Map<String, List<String>> childrenMap = getChildrenMap(openAPI); Map<String, List<String>> childrenMap = getChildrenMap(openAPI);
List<String> allUsedSchemas = new ArrayList<String>(); List<String> allUsedSchemas = new ArrayList<String>();
visitOpenAPI(openAPI, (s, t) -> { visitOpenAPI((s, t) -> {
if (s.get$ref() != null) { if (s.get$ref() != null) {
String ref = getSimpleRef(s.get$ref()); String ref = getSimpleRef(s.get$ref());
if (!allUsedSchemas.contains(ref)) { if (!allUsedSchemas.contains(ref)) {
@ -154,10 +171,9 @@ public class ModelUtils {
/** /**
* Return the list of unused schemas in the 'components/schemas' section of an openAPI specification * Return the list of unused schemas in the 'components/schemas' section of an openAPI specification
* *
* @param openAPI specification
* @return schemas a list of unused schemas * @return schemas a list of unused schemas
*/ */
public static List<String> getUnusedSchemas(OpenAPI openAPI) { public List<String> getUnusedSchemas() {
final Map<String, List<String>> childrenMap; final Map<String, List<String>> childrenMap;
Map<String, List<String>> tmpChildrenMap; Map<String, List<String>> tmpChildrenMap;
try { try {
@ -173,10 +189,10 @@ public class ModelUtils {
List<String> unusedSchemas = new ArrayList<String>(); List<String> unusedSchemas = new ArrayList<String>();
if (openAPI != null) { if (openAPI != null) {
Map<String, Schema> schemas = getSchemas(openAPI); Map<String, Schema> schemas = getSchemas();
unusedSchemas.addAll(schemas.keySet()); unusedSchemas.addAll(schemas.keySet());
visitOpenAPI(openAPI, (s, t) -> { visitOpenAPI((s, t) -> {
if (s.get$ref() != null) { if (s.get$ref() != null) {
String ref = getSimpleRef(s.get$ref()); String ref = getSimpleRef(s.get$ref());
unusedSchemas.remove(ref); unusedSchemas.remove(ref);
@ -192,14 +208,13 @@ public class ModelUtils {
/** /**
* Return the list of schemas in the 'components/schemas' used only in a 'application/x-www-form-urlencoded' or 'multipart/form-data' mime time * Return the list of schemas in the 'components/schemas' used only in a 'application/x-www-form-urlencoded' or 'multipart/form-data' mime time
* *
* @param openAPI specification
* @return schemas a list of schemas * @return schemas a list of schemas
*/ */
public static List<String> getSchemasUsedOnlyInFormParam(OpenAPI openAPI) { public List<String> getSchemasUsedOnlyInFormParam() {
List<String> schemasUsedInFormParam = new ArrayList<String>(); List<String> schemasUsedInFormParam = new ArrayList<String>();
List<String> schemasUsedInOtherCases = new ArrayList<String>(); List<String> schemasUsedInOtherCases = new ArrayList<String>();
visitOpenAPI(openAPI, (s, t) -> { visitOpenAPI((s, t) -> {
if (s.get$ref() != null) { if (s.get$ref() != null) {
String ref = getSimpleRef(s.get$ref()); String ref = getSimpleRef(s.get$ref());
if ("application/x-www-form-urlencoded".equalsIgnoreCase(t) || if ("application/x-www-form-urlencoded".equalsIgnoreCase(t) ||
@ -214,15 +229,14 @@ public class ModelUtils {
} }
/** /**
* Private method used by several methods ({@link #getAllUsedSchemas(OpenAPI)}, * Private method used by several methods ({@link #getAllUsedSchemas()},
* {@link #getUnusedSchemas(OpenAPI)}, * {@link #getUnusedSchemas()},
* {@link #getSchemasUsedOnlyInFormParam(OpenAPI)}, ...) to traverse all paths of an * {@link #getSchemasUsedOnlyInFormParam()}, ...) to traverse all paths of an
* OpenAPI instance and call the visitor functional interface when a schema is found. * OpenAPI instance and call the visitor functional interface when a schema is found.
* *
* @param openAPI specification
* @param visitor functional interface (can be defined as a lambda) called each time a schema is found. * @param visitor functional interface (can be defined as a lambda) called each time a schema is found.
*/ */
private static void visitOpenAPI(OpenAPI openAPI, OpenAPISchemaVisitor visitor) { private void visitOpenAPI(OpenAPISchemaVisitor visitor) {
Map<String, PathItem> paths = openAPI.getPaths(); Map<String, PathItem> paths = openAPI.getPaths();
List<String> visitedSchemas = new ArrayList<>(); List<String> visitedSchemas = new ArrayList<>();
@ -233,32 +247,32 @@ public class ModelUtils {
} }
} }
private static void visitPathItem(PathItem pathItem, OpenAPI openAPI, OpenAPISchemaVisitor visitor, List<String> visitedSchemas) { private void visitPathItem(PathItem pathItem, OpenAPI openAPI, OpenAPISchemaVisitor visitor, List<String> visitedSchemas) {
List<Operation> allOperations = pathItem.readOperations(); List<Operation> allOperations = pathItem.readOperations();
if (allOperations != null) { if (allOperations != null) {
for (Operation operation : allOperations) { for (Operation operation : allOperations) {
//Params: //Params:
visitParameters(openAPI, operation.getParameters(), visitor, visitedSchemas); visitParameters(operation.getParameters(), visitor, visitedSchemas);
//RequestBody: //RequestBody:
RequestBody requestBody = getReferencedRequestBody(openAPI, operation.getRequestBody()); RequestBody requestBody = getReferencedRequestBody(operation.getRequestBody());
if (requestBody != null) { if (requestBody != null) {
visitContent(openAPI, requestBody.getContent(), visitor, visitedSchemas); visitContent(requestBody.getContent(), visitor, visitedSchemas);
} }
//Responses: //Responses:
if (operation.getResponses() != null) { if (operation.getResponses() != null) {
for (ApiResponse r : operation.getResponses().values()) { for (ApiResponse r : operation.getResponses().values()) {
ApiResponse apiResponse = getReferencedApiResponse(openAPI, r); ApiResponse apiResponse = getReferencedApiResponse(r);
if (apiResponse != null) { if (apiResponse != null) {
visitContent(openAPI, apiResponse.getContent(), visitor, visitedSchemas); visitContent(apiResponse.getContent(), visitor, visitedSchemas);
if (apiResponse.getHeaders() != null) { if (apiResponse.getHeaders() != null) {
for (Entry<String, Header> e : apiResponse.getHeaders().entrySet()) { for (Entry<String, Header> e : apiResponse.getHeaders().entrySet()) {
Header header = getReferencedHeader(openAPI, e.getValue()); Header header = getReferencedHeader(e.getValue());
if (header.getSchema() != null) { if (header.getSchema() != null) {
visitSchema(openAPI, header.getSchema(), e.getKey(), visitedSchemas, visitor); visitSchema(header.getSchema(), e.getKey(), visitedSchemas, visitor);
} }
visitContent(openAPI, header.getContent(), visitor, visitedSchemas); visitContent(header.getContent(), visitor, visitedSchemas);
} }
} }
} }
@ -268,7 +282,7 @@ public class ModelUtils {
//Callbacks: //Callbacks:
if (operation.getCallbacks() != null) { if (operation.getCallbacks() != null) {
for (Callback c : operation.getCallbacks().values()) { for (Callback c : operation.getCallbacks().values()) {
Callback callback = getReferencedCallback(openAPI, c); Callback callback = getReferencedCallback(c);
if (callback != null) { if (callback != null) {
for (PathItem p : callback.values()) { for (PathItem p : callback.values()) {
visitPathItem(p, openAPI, visitor, visitedSchemas); visitPathItem(p, openAPI, visitor, visitedSchemas);
@ -279,19 +293,19 @@ public class ModelUtils {
} }
} }
//Params: //Params:
visitParameters(openAPI, pathItem.getParameters(), visitor, visitedSchemas); visitParameters(pathItem.getParameters(), visitor, visitedSchemas);
} }
private static void visitParameters(OpenAPI openAPI, List<Parameter> parameters, OpenAPISchemaVisitor visitor, private void visitParameters(List<Parameter> parameters, OpenAPISchemaVisitor visitor,
List<String> visitedSchemas) { List<String> visitedSchemas) {
if (parameters != null) { if (parameters != null) {
for (Parameter p : parameters) { for (Parameter p : parameters) {
Parameter parameter = getReferencedParameter(openAPI, p); Parameter parameter = getReferencedParameter(p);
if (parameter != null) { if (parameter != null) {
if (parameter.getSchema() != null) { if (parameter.getSchema() != null) {
visitSchema(openAPI, parameter.getSchema(), null, visitedSchemas, visitor); visitSchema(parameter.getSchema(), null, visitedSchemas, visitor);
} }
visitContent(openAPI, parameter.getContent(), visitor, visitedSchemas); visitContent(parameter.getContent(), visitor, visitedSchemas);
} else { } else {
once(LOGGER).warn("Unreferenced parameter(s) found."); once(LOGGER).warn("Unreferenced parameter(s) found.");
} }
@ -299,11 +313,11 @@ public class ModelUtils {
} }
} }
private static void visitContent(OpenAPI openAPI, Content content, OpenAPISchemaVisitor visitor, List<String> visitedSchemas) { private void visitContent(Content content, OpenAPISchemaVisitor visitor, List<String> visitedSchemas) {
if (content != null) { if (content != null) {
for (Entry<String, MediaType> e : content.entrySet()) { for (Entry<String, MediaType> e : content.entrySet()) {
if (e.getValue().getSchema() != null) { if (e.getValue().getSchema() != null) {
visitSchema(openAPI, e.getValue().getSchema(), e.getKey(), visitedSchemas, visitor); visitSchema(e.getValue().getSchema(), e.getKey(), visitedSchemas, visitor);
} }
} }
} }
@ -315,21 +329,20 @@ public class ModelUtils {
* To avoid infinite recursion, referenced schemas are visited only once. When a referenced schema is visited, * To avoid infinite recursion, referenced schemas are visited only once. When a referenced schema is visited,
* it is added to visitedSchemas. * it is added to visitedSchemas.
* *
* @param openAPI the OpenAPI document that contains schema objects.
* @param schema the root schema object to be visited. * @param schema the root schema object to be visited.
* @param mimeType the mime type. TODO: does not seem to be used in a meaningful way. * @param mimeType the mime type. TODO: does not seem to be used in a meaningful way.
* @param visitedSchemas the list of referenced schemas that have been visited. * @param visitedSchemas the list of referenced schemas that have been visited.
* @param visitor the visitor function which is invoked for every visited schema. * @param visitor the visitor function which is invoked for every visited schema.
*/ */
private static void visitSchema(OpenAPI openAPI, Schema schema, String mimeType, List<String> visitedSchemas, OpenAPISchemaVisitor visitor) { private void visitSchema(Schema schema, String mimeType, List<String> visitedSchemas, OpenAPISchemaVisitor visitor) {
visitor.visit(schema, mimeType); visitor.visit(schema, mimeType);
if (schema.get$ref() != null) { if (schema.get$ref() != null) {
String ref = getSimpleRef(schema.get$ref()); String ref = getSimpleRef(schema.get$ref());
if (!visitedSchemas.contains(ref)) { if (!visitedSchemas.contains(ref)) {
visitedSchemas.add(ref); visitedSchemas.add(ref);
Schema referencedSchema = getSchemas(openAPI).get(ref); Schema referencedSchema = getSchemas().get(ref);
if (referencedSchema != null) { if (referencedSchema != null) {
visitSchema(openAPI, referencedSchema, mimeType, visitedSchemas, visitor); visitSchema(referencedSchema, mimeType, visitedSchemas, visitor);
} }
} }
} }
@ -337,50 +350,49 @@ public class ModelUtils {
List<Schema> oneOf = ((ComposedSchema) schema).getOneOf(); List<Schema> oneOf = ((ComposedSchema) schema).getOneOf();
if (oneOf != null) { if (oneOf != null) {
for (Schema s : oneOf) { for (Schema s : oneOf) {
visitSchema(openAPI, s, mimeType, visitedSchemas, visitor); visitSchema(s, mimeType, visitedSchemas, visitor);
} }
} }
List<Schema> allOf = ((ComposedSchema) schema).getAllOf(); List<Schema> allOf = ((ComposedSchema) schema).getAllOf();
if (allOf != null) { if (allOf != null) {
for (Schema s : allOf) { for (Schema s : allOf) {
visitSchema(openAPI, s, mimeType, visitedSchemas, visitor); visitSchema(s, mimeType, visitedSchemas, visitor);
} }
} }
List<Schema> anyOf = ((ComposedSchema) schema).getAnyOf(); List<Schema> anyOf = ((ComposedSchema) schema).getAnyOf();
if (anyOf != null) { if (anyOf != null) {
for (Schema s : anyOf) { for (Schema s : anyOf) {
visitSchema(openAPI, s, mimeType, visitedSchemas, visitor); visitSchema(s, mimeType, visitedSchemas, visitor);
} }
} }
} else if (schema instanceof ArraySchema) { } else if (schema instanceof ArraySchema) {
Schema itemsSchema = ((ArraySchema) schema).getItems(); Schema itemsSchema = ((ArraySchema) schema).getItems();
if (itemsSchema != null) { if (itemsSchema != null) {
visitSchema(openAPI, itemsSchema, mimeType, visitedSchemas, visitor); visitSchema(itemsSchema, mimeType, visitedSchemas, visitor);
} }
} else if (isMapSchema(schema)) { } else if (isMapSchema(schema)) {
Object additionalProperties = schema.getAdditionalProperties(); Object additionalProperties = schema.getAdditionalProperties();
if (additionalProperties instanceof Schema) { if (additionalProperties instanceof Schema) {
visitSchema(openAPI, (Schema) additionalProperties, mimeType, visitedSchemas, visitor); visitSchema((Schema) additionalProperties, mimeType, visitedSchemas, visitor);
} }
} }
if (schema.getNot() != null) { if (schema.getNot() != null) {
visitSchema(openAPI, schema.getNot(), mimeType, visitedSchemas, visitor); visitSchema(schema.getNot(), mimeType, visitedSchemas, visitor);
} }
Map<String, Schema> properties = schema.getProperties(); Map<String, Schema> properties = schema.getProperties();
if (properties != null) { if (properties != null) {
for (Schema property : properties.values()) { for (Schema property : properties.values()) {
visitSchema(openAPI, property, mimeType, visitedSchemas, visitor); visitSchema(property, mimeType, visitedSchemas, visitor);
} }
} }
} }
@FunctionalInterface @FunctionalInterface
private static interface OpenAPISchemaVisitor { private interface OpenAPISchemaVisitor {
public void visit(Schema schema, String mimeType); public void visit(Schema schema, String mimeType);
} }
public static String getSimpleRef(String ref) { public String getSimpleRef(String ref) {
if (ref.startsWith("#/components/")) { if (ref.startsWith("#/components/")) {
ref = ref.substring(ref.lastIndexOf("/") + 1); ref = ref.substring(ref.lastIndexOf("/") + 1);
} else if (ref.startsWith("#/definitions/")) { } else if (ref.startsWith("#/definitions/")) {
@ -428,7 +440,7 @@ public class ModelUtils {
* @param schema the OAS schema * @param schema the OAS schema
* @return true if the specified schema is an Object schema. * @return true if the specified schema is an Object schema.
*/ */
public static boolean isObjectSchema(Schema schema) { public boolean isObjectSchema(Schema schema) {
if (schema instanceof ObjectSchema) { if (schema instanceof ObjectSchema) {
return true; return true;
} }
@ -452,7 +464,7 @@ public class ModelUtils {
* @param schema the OAS schema * @param schema the OAS schema
* @return true if the specified schema is a Composed schema. * @return true if the specified schema is a Composed schema.
*/ */
public static boolean isComposedSchema(Schema schema) { public boolean isComposedSchema(Schema schema) {
if (schema instanceof ComposedSchema) { if (schema instanceof ComposedSchema) {
return true; return true;
} }
@ -492,7 +504,7 @@ public class ModelUtils {
* @param schema the OAS schema * @param schema the OAS schema
* @return true if the specified schema is a Map schema. * @return true if the specified schema is a Map schema.
*/ */
public static boolean isMapSchema(Schema schema) { public boolean isMapSchema(Schema schema) {
if (schema instanceof MapSchema) { if (schema instanceof MapSchema) {
return true; return true;
} }
@ -518,22 +530,22 @@ public class ModelUtils {
* @param schema the OAS schema * @param schema the OAS schema
* @return true if the specified schema is an Array schema. * @return true if the specified schema is an Array schema.
*/ */
public static boolean isArraySchema(Schema schema) { public boolean isArraySchema(Schema schema) {
return (schema instanceof ArraySchema); return (schema instanceof ArraySchema);
} }
public static boolean isSet(Schema schema) { public boolean isSet(Schema schema) {
return ModelUtils.isArraySchema(schema) && Boolean.TRUE.equals(schema.getUniqueItems()); return isArraySchema(schema) && Boolean.TRUE.equals(schema.getUniqueItems());
} }
public static boolean isStringSchema(Schema schema) { public boolean isStringSchema(Schema schema) {
if (schema instanceof StringSchema || SchemaTypeUtil.STRING_TYPE.equals(schema.getType())) { if (schema instanceof StringSchema || SchemaTypeUtil.STRING_TYPE.equals(schema.getType())) {
return true; return true;
} }
return false; return false;
} }
public static boolean isIntegerSchema(Schema schema) { public boolean isIntegerSchema(Schema schema) {
if (schema instanceof IntegerSchema) { if (schema instanceof IntegerSchema) {
return true; return true;
} }
@ -543,7 +555,7 @@ public class ModelUtils {
return false; return false;
} }
public static boolean isShortSchema(Schema schema) { public boolean isShortSchema(Schema schema) {
if (SchemaTypeUtil.INTEGER_TYPE.equals(schema.getType()) // type: integer if (SchemaTypeUtil.INTEGER_TYPE.equals(schema.getType()) // type: integer
&& SchemaTypeUtil.INTEGER32_FORMAT.equals(schema.getFormat())) { // format: short (int32) && SchemaTypeUtil.INTEGER32_FORMAT.equals(schema.getFormat())) { // format: short (int32)
return true; return true;
@ -551,7 +563,7 @@ public class ModelUtils {
return false; return false;
} }
public static boolean isLongSchema(Schema schema) { public boolean isLongSchema(Schema schema) {
if (SchemaTypeUtil.INTEGER_TYPE.equals(schema.getType()) // type: integer if (SchemaTypeUtil.INTEGER_TYPE.equals(schema.getType()) // type: integer
&& SchemaTypeUtil.INTEGER64_FORMAT.equals(schema.getFormat())) { // format: long (int64) && SchemaTypeUtil.INTEGER64_FORMAT.equals(schema.getFormat())) { // format: long (int64)
return true; return true;
@ -559,7 +571,7 @@ public class ModelUtils {
return false; return false;
} }
public static boolean isBooleanSchema(Schema schema) { public boolean isBooleanSchema(Schema schema) {
if (schema instanceof BooleanSchema) { if (schema instanceof BooleanSchema) {
return true; return true;
} }
@ -569,7 +581,7 @@ public class ModelUtils {
return false; return false;
} }
public static boolean isNumberSchema(Schema schema) { public boolean isNumberSchema(Schema schema) {
if (schema instanceof NumberSchema) { if (schema instanceof NumberSchema) {
return true; return true;
} }
@ -579,7 +591,7 @@ public class ModelUtils {
return false; return false;
} }
public static boolean isFloatSchema(Schema schema) { public boolean isFloatSchema(Schema schema) {
if (SchemaTypeUtil.NUMBER_TYPE.equals(schema.getType()) if (SchemaTypeUtil.NUMBER_TYPE.equals(schema.getType())
&& SchemaTypeUtil.FLOAT_FORMAT.equals(schema.getFormat())) { // format: float && SchemaTypeUtil.FLOAT_FORMAT.equals(schema.getFormat())) { // format: float
return true; return true;
@ -587,7 +599,7 @@ public class ModelUtils {
return false; return false;
} }
public static boolean isDoubleSchema(Schema schema) { public boolean isDoubleSchema(Schema schema) {
if (SchemaTypeUtil.NUMBER_TYPE.equals(schema.getType()) if (SchemaTypeUtil.NUMBER_TYPE.equals(schema.getType())
&& SchemaTypeUtil.DOUBLE_FORMAT.equals(schema.getFormat())) { // format: double && SchemaTypeUtil.DOUBLE_FORMAT.equals(schema.getFormat())) { // format: double
return true; return true;
@ -595,7 +607,7 @@ public class ModelUtils {
return false; return false;
} }
public static boolean isDateSchema(Schema schema) { public boolean isDateSchema(Schema schema) {
if (schema instanceof DateSchema) { if (schema instanceof DateSchema) {
return true; return true;
} }
@ -607,7 +619,7 @@ public class ModelUtils {
return false; return false;
} }
public static boolean isDateTimeSchema(Schema schema) { public boolean isDateTimeSchema(Schema schema) {
if (schema instanceof DateTimeSchema) { if (schema instanceof DateTimeSchema) {
return true; return true;
} }
@ -618,7 +630,7 @@ public class ModelUtils {
return false; return false;
} }
public static boolean isPasswordSchema(Schema schema) { public boolean isPasswordSchema(Schema schema) {
if (schema instanceof PasswordSchema) { if (schema instanceof PasswordSchema) {
return true; return true;
} }
@ -629,7 +641,7 @@ public class ModelUtils {
return false; return false;
} }
public static boolean isByteArraySchema(Schema schema) { public boolean isByteArraySchema(Schema schema) {
if (schema instanceof ByteArraySchema) { if (schema instanceof ByteArraySchema) {
return true; return true;
} }
@ -640,7 +652,7 @@ public class ModelUtils {
return false; return false;
} }
public static boolean isBinarySchema(Schema schema) { public boolean isBinarySchema(Schema schema) {
if (schema instanceof BinarySchema) { if (schema instanceof BinarySchema) {
return true; return true;
} }
@ -651,7 +663,7 @@ public class ModelUtils {
return false; return false;
} }
public static boolean isFileSchema(Schema schema) { public boolean isFileSchema(Schema schema) {
if (schema instanceof FileSchema) { if (schema instanceof FileSchema) {
return true; return true;
} }
@ -659,7 +671,7 @@ public class ModelUtils {
return isBinarySchema(schema); return isBinarySchema(schema);
} }
public static boolean isUUIDSchema(Schema schema) { public boolean isUUIDSchema(Schema schema) {
if (schema instanceof UUIDSchema) { if (schema instanceof UUIDSchema) {
return true; return true;
} }
@ -678,7 +690,7 @@ public class ModelUtils {
return false; return false;
} }
public static boolean isEmailSchema(Schema schema) { public boolean isEmailSchema(Schema schema) {
if (schema instanceof EmailSchema) { if (schema instanceof EmailSchema) {
return true; return true;
} }
@ -689,7 +701,7 @@ public class ModelUtils {
return false; return false;
} }
public static boolean isDecimalSchema(Schema schema) { public boolean isDecimalSchema(Schema schema) {
if (SchemaTypeUtil.STRING_TYPE.equals(schema.getType()) // type: string if (SchemaTypeUtil.STRING_TYPE.equals(schema.getType()) // type: string
&& "number".equals(schema.getFormat())) { // format: number && "number".equals(schema.getFormat())) { // format: number
return true; return true;
@ -703,7 +715,7 @@ public class ModelUtils {
* @param schema potentially containing a '$ref' * @param schema potentially containing a '$ref'
* @return true if it's a model with at least one properties * @return true if it's a model with at least one properties
*/ */
public static boolean isModel(Schema schema) { public boolean isModel(Schema schema) {
if (schema == null) { if (schema == null) {
return false; return false;
} }
@ -717,7 +729,7 @@ public class ModelUtils {
return schema instanceof ComposedSchema || schema instanceof ObjectSchema; return schema instanceof ComposedSchema || schema instanceof ObjectSchema;
} }
public static boolean hasValidation(Schema sc) { public boolean hasValidation(Schema sc) {
return ( return (
sc.getMaxItems() != null || sc.getMaxItems() != null ||
sc.getMinProperties() != null || sc.getMinProperties() != null ||
@ -762,11 +774,10 @@ public class ModelUtils {
* description: This is NOT a free-form object. * description: This is NOT a free-form object.
* The value can be any type except the 'null' value. * The value can be any type except the 'null' value.
* *
* @param openAPI the object that encapsulates the OAS document.
* @param schema potentially containing a '$ref' * @param schema potentially containing a '$ref'
* @return true if it's a free-form object * @return true if it's a free-form object
*/ */
public static boolean isFreeFormObject(OpenAPI openAPI, Schema schema) { public boolean isFreeFormObject(Schema schema) {
if (schema == null) { if (schema == null) {
// TODO: Is this message necessary? A null schema is not a free-form object, so the result is correct. // TODO: Is this message necessary? A null schema is not a free-form object, so the result is correct.
once(LOGGER).error("Schema cannot be null in isFreeFormObject check"); once(LOGGER).error("Schema cannot be null in isFreeFormObject check");
@ -776,7 +787,7 @@ public class ModelUtils {
// not free-form if allOf, anyOf, oneOf is not empty // not free-form if allOf, anyOf, oneOf is not empty
if (schema instanceof ComposedSchema) { if (schema instanceof ComposedSchema) {
ComposedSchema cs = (ComposedSchema) schema; ComposedSchema cs = (ComposedSchema) schema;
List<Schema> interfaces = ModelUtils.getInterfaces(cs); List<Schema> interfaces = getInterfaces(cs);
if (interfaces != null && !interfaces.isEmpty()) { if (interfaces != null && !interfaces.isEmpty()) {
return false; return false;
} }
@ -786,7 +797,7 @@ public class ModelUtils {
if ("object".equals(schema.getType())) { if ("object".equals(schema.getType())) {
// no properties // no properties
if ((schema.getProperties() == null || schema.getProperties().isEmpty())) { if ((schema.getProperties() == null || schema.getProperties().isEmpty())) {
Schema addlProps = getAdditionalProperties(openAPI, schema); Schema addlProps = getAdditionalProperties(schema);
if (schema.getExtensions() != null && schema.getExtensions().containsKey(freeFormExplicit)) { if (schema.getExtensions() != null && schema.getExtensions().containsKey(freeFormExplicit)) {
// User has hard-coded vendor extension to handle free-form evaluation. // User has hard-coded vendor extension to handle free-form evaluation.
@ -823,14 +834,13 @@ public class ModelUtils {
/** /**
* If a Schema contains a reference to another Schema with '$ref', returns the referenced Schema if it is found or the actual Schema in the other cases. * If a Schema contains a reference to another Schema with '$ref', returns the referenced Schema if it is found or the actual Schema in the other cases.
* *
* @param openAPI specification being checked
* @param schema potentially containing a '$ref' * @param schema potentially containing a '$ref'
* @return schema without '$ref' * @return schema without '$ref'
*/ */
public static Schema getReferencedSchema(OpenAPI openAPI, Schema schema) { public Schema getReferencedSchema(Schema schema) {
if (schema != null && StringUtils.isNotEmpty(schema.get$ref())) { if (schema != null && StringUtils.isNotEmpty(schema.get$ref())) {
String name = getSimpleRef(schema.get$ref()); String name = getSimpleRef(schema.get$ref());
Schema referencedSchema = getSchema(openAPI, name); Schema referencedSchema = getSchema(name);
if (referencedSchema != null) { if (referencedSchema != null) {
return referencedSchema; return referencedSchema;
} }
@ -838,12 +848,12 @@ public class ModelUtils {
return schema; return schema;
} }
public static Schema getSchema(OpenAPI openAPI, String name) { public Schema getSchema(String name) {
if (name == null) { if (name == null) {
return null; return null;
} }
return getSchemas(openAPI).get(name); return getSchemas().get(name);
} }
/** /**
@ -851,10 +861,9 @@ public class ModelUtils {
* The returned Map only includes the direct children of /components/schemas in the OAS document; the Map * The returned Map only includes the direct children of /components/schemas in the OAS document; the Map
* does not include inlined schemas. * does not include inlined schemas.
* *
* @param openAPI the OpenAPI document.
* @return a map of schemas in the OAS document. * @return a map of schemas in the OAS document.
*/ */
public static Map<String, Schema> getSchemas(OpenAPI openAPI) { public Map<String, Schema> getSchemas() {
if (openAPI != null && openAPI.getComponents() != null && openAPI.getComponents().getSchemas() != null) { if (openAPI != null && openAPI.getComponents() != null && openAPI.getComponents().getSchemas() != null) {
return openAPI.getComponents().getSchemas(); return openAPI.getComponents().getSchemas();
} }
@ -868,13 +877,13 @@ public class ModelUtils {
* @param openAPI OpenAPI document * @param openAPI OpenAPI document
* @return a list of schemas * @return a list of schemas
*/ */
public static List<Schema> getAllSchemas(OpenAPI openAPI) { public List<Schema> getAllSchemas(OpenAPI openAPI) {
List<Schema> allSchemas = new ArrayList<Schema>(); List<Schema> allSchemas = new ArrayList<Schema>();
List<String> refSchemas = new ArrayList<String>(); List<String> refSchemas = new ArrayList<String>();
getSchemas(openAPI).forEach((key, schema) -> { getSchemas().forEach((key, schema) -> {
// Invoke visitSchema to recursively visit all schema objects, included inlined and composed schemas. // Invoke visitSchema to recursively visit all schema objects, included inlined and composed schemas.
// Use the OpenAPISchemaVisitor visitor function // Use the OpenAPISchemaVisitor visitor function
visitSchema(openAPI, schema, null, refSchemas, (s, mimetype) -> { visitSchema(schema, null, refSchemas, (s, mimetype) -> {
allSchemas.add(s); allSchemas.add(s);
}); });
}); });
@ -884,14 +893,13 @@ public class ModelUtils {
/** /**
* If a RequestBody contains a reference to an other RequestBody with '$ref', returns the referenced RequestBody if it is found or the actual RequestBody in the other cases. * If a RequestBody contains a reference to an other RequestBody with '$ref', returns the referenced RequestBody if it is found or the actual RequestBody in the other cases.
* *
* @param openAPI specification being checked
* @param requestBody potentially containing a '$ref' * @param requestBody potentially containing a '$ref'
* @return requestBody without '$ref' * @return requestBody without '$ref'
*/ */
public static RequestBody getReferencedRequestBody(OpenAPI openAPI, RequestBody requestBody) { public RequestBody getReferencedRequestBody(RequestBody requestBody) {
if (requestBody != null && StringUtils.isNotEmpty(requestBody.get$ref())) { if (requestBody != null && StringUtils.isNotEmpty(requestBody.get$ref())) {
String name = getSimpleRef(requestBody.get$ref()); String name = getSimpleRef(requestBody.get$ref());
RequestBody referencedRequestBody = getRequestBody(openAPI, name); RequestBody referencedRequestBody = getRequestBody(name);
if (referencedRequestBody != null) { if (referencedRequestBody != null) {
return referencedRequestBody; return referencedRequestBody;
} }
@ -899,7 +907,7 @@ public class ModelUtils {
return requestBody; return requestBody;
} }
public static RequestBody getRequestBody(OpenAPI openAPI, String name) { public RequestBody getRequestBody(String name) {
if (name == null) { if (name == null) {
return null; return null;
} }
@ -913,14 +921,13 @@ public class ModelUtils {
/** /**
* If a ApiResponse contains a reference to an other ApiResponse with '$ref', returns the referenced ApiResponse if it is found or the actual ApiResponse in the other cases. * If a ApiResponse contains a reference to an other ApiResponse with '$ref', returns the referenced ApiResponse if it is found or the actual ApiResponse in the other cases.
* *
* @param openAPI specification being checked
* @param apiResponse potentially containing a '$ref' * @param apiResponse potentially containing a '$ref'
* @return apiResponse without '$ref' * @return apiResponse without '$ref'
*/ */
public static ApiResponse getReferencedApiResponse(OpenAPI openAPI, ApiResponse apiResponse) { public ApiResponse getReferencedApiResponse(ApiResponse apiResponse) {
if (apiResponse != null && StringUtils.isNotEmpty(apiResponse.get$ref())) { if (apiResponse != null && StringUtils.isNotEmpty(apiResponse.get$ref())) {
String name = getSimpleRef(apiResponse.get$ref()); String name = getSimpleRef(apiResponse.get$ref());
ApiResponse referencedApiResponse = getApiResponse(openAPI, name); ApiResponse referencedApiResponse = getApiResponse(name);
if (referencedApiResponse != null) { if (referencedApiResponse != null) {
return referencedApiResponse; return referencedApiResponse;
} }
@ -928,7 +935,7 @@ public class ModelUtils {
return apiResponse; return apiResponse;
} }
public static ApiResponse getApiResponse(OpenAPI openAPI, String name) { public ApiResponse getApiResponse(String name) {
if (name == null) { if (name == null) {
return null; return null;
} }
@ -942,14 +949,13 @@ public class ModelUtils {
/** /**
* If a Parameter contains a reference to an other Parameter with '$ref', returns the referenced Parameter if it is found or the actual Parameter in the other cases. * If a Parameter contains a reference to an other Parameter with '$ref', returns the referenced Parameter if it is found or the actual Parameter in the other cases.
* *
* @param openAPI specification being checked
* @param parameter potentially containing a '$ref' * @param parameter potentially containing a '$ref'
* @return parameter without '$ref' * @return parameter without '$ref'
*/ */
public static Parameter getReferencedParameter(OpenAPI openAPI, Parameter parameter) { public Parameter getReferencedParameter(Parameter parameter) {
if (parameter != null && StringUtils.isNotEmpty(parameter.get$ref())) { if (parameter != null && StringUtils.isNotEmpty(parameter.get$ref())) {
String name = getSimpleRef(parameter.get$ref()); String name = getSimpleRef(parameter.get$ref());
Parameter referencedParameter = getParameter(openAPI, name); Parameter referencedParameter = getParameter(name);
if (referencedParameter != null) { if (referencedParameter != null) {
return referencedParameter; return referencedParameter;
} }
@ -957,7 +963,7 @@ public class ModelUtils {
return parameter; return parameter;
} }
public static Parameter getParameter(OpenAPI openAPI, String name) { public Parameter getParameter(String name) {
if (name == null) { if (name == null) {
return null; return null;
} }
@ -971,14 +977,13 @@ public class ModelUtils {
/** /**
* If a Callback contains a reference to an other Callback with '$ref', returns the referenced Callback if it is found or the actual Callback in the other cases. * If a Callback contains a reference to an other Callback with '$ref', returns the referenced Callback if it is found or the actual Callback in the other cases.
* *
* @param openAPI specification being checked
* @param callback potentially containing a '$ref' * @param callback potentially containing a '$ref'
* @return callback without '$ref' * @return callback without '$ref'
*/ */
public static Callback getReferencedCallback(OpenAPI openAPI, Callback callback) { public Callback getReferencedCallback(Callback callback) {
if (callback != null && StringUtils.isNotEmpty(callback.get$ref())) { if (callback != null && StringUtils.isNotEmpty(callback.get$ref())) {
String name = getSimpleRef(callback.get$ref()); String name = getSimpleRef(callback.get$ref());
Callback referencedCallback = getCallback(openAPI, name); Callback referencedCallback = getCallback(name);
if (referencedCallback != null) { if (referencedCallback != null) {
return referencedCallback; return referencedCallback;
} }
@ -986,7 +991,7 @@ public class ModelUtils {
return callback; return callback;
} }
public static Callback getCallback(OpenAPI openAPI, String name) { public Callback getCallback(String name) {
if (name == null) { if (name == null) {
return null; return null;
} }
@ -1003,7 +1008,7 @@ public class ModelUtils {
* @param requestBody request body of the operation * @param requestBody request body of the operation
* @return firstSchema * @return firstSchema
*/ */
public static Schema getSchemaFromRequestBody(RequestBody requestBody) { public Schema getSchemaFromRequestBody(RequestBody requestBody) {
return getSchemaFromContent(requestBody.getContent()); return getSchemaFromContent(requestBody.getContent());
} }
@ -1013,7 +1018,7 @@ public class ModelUtils {
* @param response api response of the operation * @param response api response of the operation
* @return firstSchema * @return firstSchema
*/ */
public static Schema getSchemaFromResponse(ApiResponse response) { public Schema getSchemaFromResponse(ApiResponse response) {
return getSchemaFromContent(response.getContent()); return getSchemaFromContent(response.getContent());
} }
@ -1035,7 +1040,7 @@ public class ModelUtils {
* @param content a 'content' section in the OAS specification. * @param content a 'content' section in the OAS specification.
* @return the Schema. * @return the Schema.
*/ */
private static Schema getSchemaFromContent(Content content) { private Schema getSchemaFromContent(Content content) {
if (content == null || content.isEmpty()) { if (content == null || content.isEmpty()) {
return null; return null;
} }
@ -1052,27 +1057,22 @@ public class ModelUtils {
/** /**
* Get the actual schema from aliases. If the provided schema is not an alias, the schema itself will be returned. * Get the actual schema from aliases. If the provided schema is not an alias, the schema itself will be returned.
* *
* @param openAPI specification being checked
* @param schema schema (alias or direct reference) * @param schema schema (alias or direct reference)
* @return actual schema * @return actual schema
*/ */
public static Schema unaliasSchema(OpenAPI openAPI, public Schema unaliasSchema(Schema schema) {
Schema schema) { return unaliasSchema(schema, Collections.<String, String>emptyMap());
return unaliasSchema(openAPI, schema, Collections.<String, String>emptyMap());
} }
/** /**
* Get the actual schema from aliases. If the provided schema is not an alias, the schema itself will be returned. * Get the actual schema from aliases. If the provided schema is not an alias, the schema itself will be returned.
* *
* @param openAPI OpenAPI document containing the schemas.
* @param schema schema (alias or direct reference) * @param schema schema (alias or direct reference)
* @param importMappings mappings of external types to be omitted by unaliasing * @param importMappings mappings of external types to be omitted by unaliasing
* @return actual schema * @return actual schema
*/ */
public static Schema unaliasSchema(OpenAPI openAPI, public Schema unaliasSchema(Schema schema, Map<String, String> importMappings) {
Schema schema, Map<String, Schema> allSchemas = getSchemas();
Map<String, String> importMappings) {
Map<String, Schema> allSchemas = getSchemas(openAPI);
if (allSchemas == null || allSchemas.isEmpty()) { if (allSchemas == null || allSchemas.isEmpty()) {
// skip the warning as the spec can have no model defined // skip the warning as the spec can have no model defined
//LOGGER.warn("allSchemas cannot be null/empty in unaliasSchema. Returned 'schema'"); //LOGGER.warn("allSchemas cannot be null/empty in unaliasSchema. Returned 'schema'");
@ -1080,7 +1080,7 @@ public class ModelUtils {
} }
if (schema != null && StringUtils.isNotEmpty(schema.get$ref())) { if (schema != null && StringUtils.isNotEmpty(schema.get$ref())) {
String simpleRef = ModelUtils.getSimpleRef(schema.get$ref()); String simpleRef = getSimpleRef(schema.get$ref());
if (importMappings.containsKey(simpleRef)) { if (importMappings.containsKey(simpleRef)) {
LOGGER.debug("Schema unaliasing of {} omitted because aliased class is to be mapped to {}", simpleRef, importMappings.get(simpleRef)); LOGGER.debug("Schema unaliasing of {} omitted because aliased class is to be mapped to {}", simpleRef, importMappings.get(simpleRef));
return schema; return schema;
@ -1096,7 +1096,7 @@ public class ModelUtils {
if (isGenerateAliasAsModel(ref)) { if (isGenerateAliasAsModel(ref)) {
return schema; // generate a model extending array return schema; // generate a model extending array
} else { } else {
return unaliasSchema(openAPI, allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())), return unaliasSchema(allSchemas.get(getSimpleRef(schema.get$ref())),
importMappings); importMappings);
} }
} else if (isComposedSchema(ref)) { } else if (isComposedSchema(ref)) {
@ -1109,19 +1109,17 @@ public class ModelUtils {
return schema; // generate a model extending map return schema; // generate a model extending map
} else { } else {
// treat it as a typical map // treat it as a typical map
return unaliasSchema(openAPI, allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())), return unaliasSchema(allSchemas.get(getSimpleRef(schema.get$ref())), importMappings);
importMappings);
} }
} }
} else if (isObjectSchema(ref)) { // model } else if (isObjectSchema(ref)) { // model
if (ref.getProperties() != null && !ref.getProperties().isEmpty()) { // has at least one property if (ref.getProperties() != null && !ref.getProperties().isEmpty()) { // has at least one property
return schema; return schema;
} else { // free form object (type: object) } else { // free form object (type: object)
return unaliasSchema(openAPI, allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())), return unaliasSchema(allSchemas.get(getSimpleRef(schema.get$ref())), importMappings);
importMappings);
} }
} else { } else {
return unaliasSchema(openAPI, allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())), importMappings); return unaliasSchema(allSchemas.get(getSimpleRef(schema.get$ref())), importMappings);
} }
} }
return schema; return schema;
@ -1138,12 +1136,11 @@ public class ModelUtils {
* any additional properties are allowed. This is equivalent to setting additionalProperties * any additional properties are allowed. This is equivalent to setting additionalProperties
* to the boolean value True or setting additionalProperties: {} * to the boolean value True or setting additionalProperties: {}
* *
* @param openAPI the object that encapsulates the OAS document.
* @param schema the input schema that may or may not have the additionalProperties keyword. * @param schema the input schema that may or may not have the additionalProperties keyword.
* @return the Schema of the additionalProperties. The null value is returned if no additional * @return the Schema of the additionalProperties. The null value is returned if no additional
* properties are allowed. * properties are allowed.
*/ */
public static Schema getAdditionalProperties(OpenAPI openAPI, Schema schema) { public Schema getAdditionalProperties(Schema schema) {
Object addProps = schema.getAdditionalProperties(); Object addProps = schema.getAdditionalProperties();
if (addProps instanceof Schema) { if (addProps instanceof Schema) {
return (Schema) addProps; return (Schema) addProps;
@ -1194,10 +1191,10 @@ public class ModelUtils {
return null; return null;
} }
public static Header getReferencedHeader(OpenAPI openAPI, Header header) { public Header getReferencedHeader(Header header) {
if (header != null && StringUtils.isNotEmpty(header.get$ref())) { if (header != null && StringUtils.isNotEmpty(header.get$ref())) {
String name = getSimpleRef(header.get$ref()); String name = getSimpleRef(header.get$ref());
Header referencedheader = getHeader(openAPI, name); Header referencedheader = getHeader(name);
if (referencedheader != null) { if (referencedheader != null) {
return referencedheader; return referencedheader;
} }
@ -1205,7 +1202,7 @@ public class ModelUtils {
return header; return header;
} }
public static Header getHeader(OpenAPI openAPI, String name) { public Header getHeader(String name) {
if (name == null) { if (name == null) {
return null; return null;
} }
@ -1216,8 +1213,8 @@ public class ModelUtils {
return null; return null;
} }
public static Map<String, List<String>> getChildrenMap(OpenAPI openAPI) { public Map<String, List<String>> getChildrenMap(OpenAPI openAPI) {
Map<String, Schema> allSchemas = getSchemas(openAPI); Map<String, Schema> allSchemas = getSchemas();
Map<String, List<Entry<String, Schema>>> groupedByParent = allSchemas.entrySet().stream() Map<String, List<Entry<String, Schema>>> groupedByParent = allSchemas.entrySet().stream()
.filter(entry -> isComposedSchema(entry.getValue())) .filter(entry -> isComposedSchema(entry.getValue()))
@ -1235,7 +1232,7 @@ public class ModelUtils {
* @param composed schema (alias or direct reference) * @param composed schema (alias or direct reference)
* @return a list of schema defined in allOf, anyOf or oneOf * @return a list of schema defined in allOf, anyOf or oneOf
*/ */
public static List<Schema> getInterfaces(ComposedSchema composed) { public List<Schema> getInterfaces(ComposedSchema composed) {
if (composed.getAllOf() != null && !composed.getAllOf().isEmpty()) { if (composed.getAllOf() != null && !composed.getAllOf().isEmpty()) {
return composed.getAllOf(); return composed.getAllOf();
} else if (composed.getAnyOf() != null && !composed.getAnyOf().isEmpty()) { } else if (composed.getAnyOf() != null && !composed.getAnyOf().isEmpty()) {
@ -1275,7 +1272,7 @@ public class ModelUtils {
* @param allSchemas all schemas * @param allSchemas all schemas
* @return the name of the parent model * @return the name of the parent model
*/ */
public static String getParentName(ComposedSchema composedSchema, Map<String, Schema> allSchemas) { public String getParentName(ComposedSchema composedSchema, Map<String, Schema> allSchemas) {
List<Schema> interfaces = getInterfaces(composedSchema); List<Schema> interfaces = getInterfaces(composedSchema);
int nullSchemaChildrenCount = 0; int nullSchemaChildrenCount = 0;
boolean hasAmbiguousParents = false; boolean hasAmbiguousParents = false;
@ -1301,7 +1298,7 @@ public class ModelUtils {
} else { } else {
// not a ref, doing nothing, except counting the number of times the 'null' type // not a ref, doing nothing, except counting the number of times the 'null' type
// is listed as composed element. // is listed as composed element.
if (ModelUtils.isNullType(schema)) { if (isNullType(schema)) {
// If there are two interfaces, and one of them is the 'null' type, // If there are two interfaces, and one of them is the 'null' type,
// then the parent is obvious and there is no need to warn about specifying // then the parent is obvious and there is no need to warn about specifying
// a determinator. // a determinator.
@ -1335,7 +1332,7 @@ public class ModelUtils {
* @param includeAncestors if true, include the indirect ancestors in the return value. If false, return the direct parents. * @param includeAncestors if true, include the indirect ancestors in the return value. If false, return the direct parents.
* @return the name of the parent model * @return the name of the parent model
*/ */
public static List<String> getAllParentsName(ComposedSchema composedSchema, Map<String, Schema> allSchemas, boolean includeAncestors) { public List<String> getAllParentsName(ComposedSchema composedSchema, Map<String, Schema> allSchemas, boolean includeAncestors) {
List<Schema> interfaces = getInterfaces(composedSchema); List<Schema> interfaces = getInterfaces(composedSchema);
List<String> names = new ArrayList<String>(); List<String> names = new ArrayList<String>();
@ -1373,7 +1370,7 @@ public class ModelUtils {
return names; return names;
} }
private static boolean hasOrInheritsDiscriminator(Schema schema, Map<String, Schema> allSchemas) { private boolean hasOrInheritsDiscriminator(Schema schema, Map<String, Schema> allSchemas) {
if (schema.getDiscriminator() != null && StringUtils.isNotEmpty(schema.getDiscriminator().getPropertyName())) { if (schema.getDiscriminator() != null && StringUtils.isNotEmpty(schema.getDiscriminator().getPropertyName())) {
return true; return true;
} }
@ -1416,7 +1413,7 @@ public class ModelUtils {
* @param schema the OAS schema. * @param schema the OAS schema.
* @return true if the schema is nullable. * @return true if the schema is nullable.
*/ */
public static boolean isNullable(Schema schema) { public boolean isNullable(Schema schema) {
if (schema == null) { if (schema == null) {
return false; return false;
} }
@ -1451,7 +1448,7 @@ public class ModelUtils {
* @param schema the OAS composed schema. * @param schema the OAS composed schema.
* @return true if the composed schema is nullable. * @return true if the composed schema is nullable.
*/ */
public static boolean isNullableComposedSchema(ComposedSchema schema) { public boolean isNullableComposedSchema(ComposedSchema schema) {
List<Schema> oneOf = schema.getOneOf(); List<Schema> oneOf = schema.getOneOf();
if (oneOf != null && oneOf.size() <= 2) { if (oneOf != null && oneOf.size() <= 2) {
for (Schema s : oneOf) { for (Schema s : oneOf) {
@ -1480,14 +1477,14 @@ public class ModelUtils {
* @param schema the OpenAPI schema * @param schema the OpenAPI schema
* @return true if the schema is the 'null' type * @return true if the schema is the 'null' type
*/ */
public static boolean isNullType(Schema schema) { public boolean isNullType(Schema schema) {
if ("null".equals(schema.getType())) { if ("null".equals(schema.getType())) {
return true; return true;
} }
return false; return false;
} }
public static void syncValidationProperties(Schema schema, IJsonSchemaValidationProperties target) { public void syncValidationProperties(Schema schema, IJsonSchemaValidationProperties target) {
if (schema != null && target != null) { if (schema != null && target != null) {
target.setPattern(schema.getPattern()); target.setPattern(schema.getPattern());
BigDecimal minimum = schema.getMinimum(); BigDecimal minimum = schema.getMinimum();
@ -1516,7 +1513,7 @@ public class ModelUtils {
} }
} }
private static ObjectMapper getRightMapper(String data) { private ObjectMapper getRightMapper(String data) {
ObjectMapper mapper; ObjectMapper mapper;
if(data.trim().startsWith("{")) { if(data.trim().startsWith("{")) {
mapper = JSON_MAPPER; mapper = JSON_MAPPER;
@ -1536,7 +1533,7 @@ public class ModelUtils {
* *
* @return A JsonNode representation of the input OAS document. * @return A JsonNode representation of the input OAS document.
*/ */
public static JsonNode readWithInfo(String location, List<AuthorizationValue> auths) throws Exception { public JsonNode readWithInfo(String location, List<AuthorizationValue> auths) throws Exception {
String data; String data;
location = location.replaceAll("\\\\","/"); location = location.replaceAll("\\\\","/");
if (location.toLowerCase(Locale.ROOT).startsWith("http")) { if (location.toLowerCase(Locale.ROOT).startsWith("http")) {
@ -1565,13 +1562,12 @@ public class ModelUtils {
* For OAS 2.0 documents, return the value of the 'swagger' attribute. * For OAS 2.0 documents, return the value of the 'swagger' attribute.
* For OAS 3.x documents, return the value of the 'openapi' attribute. * For OAS 3.x documents, return the value of the 'openapi' attribute.
* *
* @param openAPI the object that encapsulates the OAS document.
* @param location the URL of the OAS document. * @param location the URL of the OAS document.
* @param auths the list of authorization values to access the remote URL. * @param auths the list of authorization values to access the remote URL.
* *
* @return the version of the OpenAPI document. * @return the version of the OpenAPI document.
*/ */
public static SemVer getOpenApiVersion(OpenAPI openAPI, String location, List<AuthorizationValue> auths) { public SemVer getOpenApiVersion(String location, List<AuthorizationValue> auths) {
String version; String version;
try { try {
JsonNode document = readWithInfo(location, auths); JsonNode document = readWithInfo(location, auths);
@ -1593,4 +1589,46 @@ public class ModelUtils {
return new SemVer(version); return new SemVer(version);
} }
/**
* Return true if the schema value can be any type, i.e. it can be
* the null value, integer, number, string, object or array.
* One use case is when the "type" attribute in the OAS schema is unspecified.
*
* Examples:
*
* arbitraryTypeValue:
* description: This is an arbitrary type schema.
* It is not a free-form object.
* The value can be any type except the 'null' value.
* arbitraryTypeNullableValue:
* description: This is an arbitrary type schema.
* It is not a free-form object.
* The value can be any type, including the 'null' value.
* nullable: true
*
* @param schema the OAS schema.
* @return true if the schema value can be an arbitrary type.
*/
public boolean isAnyTypeSchema(Schema schema) {
if (schema == null) {
once(LOGGER).error("Schema cannot be null in isAnyTypeSchema check");
return false;
}
if (isFreeFormObject(schema)) {
// make sure it's not free form object
return false;
}
if (schema.getClass().equals(Schema.class) && schema.get$ref() == null && schema.getType() == null &&
(schema.getProperties() == null || schema.getProperties().isEmpty()) &&
schema.getAdditionalProperties() == null && schema.getNot() == null &&
schema.getEnum() == null) {
return true;
// If and when type arrays are supported in a future OAS specification,
// we could return true if the type array includes all possible JSON schema types.
}
return false;
}
} }

View File

@ -43,14 +43,16 @@ public class OpenApiEvaluator implements Validator<OpenAPI> {
OpenApiSchemaValidations schemaValidations = new OpenApiSchemaValidations(ruleConfiguration); OpenApiSchemaValidations schemaValidations = new OpenApiSchemaValidations(ruleConfiguration);
OpenApiOperationValidations operationValidations = new OpenApiOperationValidations(ruleConfiguration); OpenApiOperationValidations operationValidations = new OpenApiOperationValidations(ruleConfiguration);
ModelUtils modelUtils = new ModelUtils(specification);
if (ruleConfiguration.isEnableUnusedSchemasRecommendation()) { if (ruleConfiguration.isEnableUnusedSchemasRecommendation()) {
ValidationRule unusedSchema = ValidationRule.create(Severity.WARNING, "Unused schema", "A schema was determined to be unused.", s -> ValidationRule.Pass.empty()); ValidationRule unusedSchema = ValidationRule.create(Severity.WARNING, "Unused schema", "A schema was determined to be unused.", s -> ValidationRule.Pass.empty());
ModelUtils.getUnusedSchemas(specification).forEach(schemaName -> validationResult.addResult(Validated.invalid(unusedSchema, "Unused model: " + schemaName))); modelUtils.getUnusedSchemas().forEach(schemaName -> validationResult.addResult(Validated.invalid(unusedSchema, "Unused model: " + schemaName)));
} }
// Get list of all schemas under /components/schemas, including nested schemas defined inline and composed schema. // Get list of all schemas under /components/schemas, including nested schemas defined inline and composed schema.
// The validators must be able to validate every schema defined in the OAS document. // The validators must be able to validate every schema defined in the OAS document.
List<Schema> schemas = ModelUtils.getAllSchemas(specification); List<Schema> schemas = modelUtils.getAllSchemas(specification);
schemas.forEach(schema -> { schemas.forEach(schema -> {
SchemaWrapper wrapper = new SchemaWrapper(specification, schema); SchemaWrapper wrapper = new SchemaWrapper(specification, schema);
validationResult.consume(schemaValidations.validate(wrapper)); validationResult.consume(schemaValidations.validate(wrapper));
@ -95,7 +97,7 @@ public class OpenApiEvaluator implements Validator<OpenAPI> {
} }
parameters.forEach(parameter -> { parameters.forEach(parameter -> {
parameter = ModelUtils.getReferencedParameter(specification, parameter); parameter = modelUtils.getReferencedParameter(parameter);
ParameterWrapper wrapper = new ParameterWrapper(specification, parameter); ParameterWrapper wrapper = new ParameterWrapper(specification, parameter);
validationResult.consume(parameterValidations.validate(wrapper)); validationResult.consume(parameterValidations.validate(wrapper));
}); });

Some files were not shown because too many files have changed in this diff Show More