Merge branch 'master' into new-sync-master-to-2.3.0

This commit is contained in:
Paŭlo Ebermann
2017-03-13 21:10:53 +01:00
1040 changed files with 17614 additions and 5102 deletions

View File

@@ -6,28 +6,33 @@ import java.util.Map;
import java.util.List;
public class CodegenParameter {
public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
public boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
isCookieParam, isBodyParam, hasMore, isContainer,
secondaryParam, isCollectionFormatMulti, isPrimitiveType;
public String baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName;
public String baseName, paramName, dataType, datatypeWithEnum, dataFormat,
collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName;
//This was added for javaPlayFramework specifically to get around a bug in swagger-play. See generator for more info on the bug.
public String dataTypeForImplicitParam;
public String example; // example value (x-example)
public String jsonSchema;
public Boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime;
public Boolean isListContainer, isMapContainer;
public Boolean isFile, notFile;
public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime;
public boolean isListContainer, isMapContainer;
public boolean isFile, notFile;
public boolean isEnum;
public List<String> _enum;
public Map<String, Object> allowableValues;
public CodegenProperty items;
public Map<String, Object> vendorExtensions;
public Boolean hasValidation;
public boolean hasValidation;
/**
* Determines whether this parameter is mandatory. If the parameter is in "path",
* this property is required and its value MUST be true. Otherwise, the property
* MAY be included and its default value is false.
*/
public Boolean required;
public boolean required;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor17.
@@ -36,7 +41,7 @@ public class CodegenParameter {
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor17
*/
public Boolean exclusiveMaximum;
public boolean exclusiveMaximum;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor21
*/
@@ -44,7 +49,7 @@ public class CodegenParameter {
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor21
*/
public Boolean exclusiveMinimum;
public boolean exclusiveMinimum;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor26
*/
@@ -68,7 +73,7 @@ public class CodegenParameter {
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor49
*/
public Boolean uniqueItems;
public boolean uniqueItems;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor14
*/
@@ -156,27 +161,27 @@ public class CodegenParameter {
CodegenParameter that = (CodegenParameter) o;
if (isEnum != that.isEnum) return false;
if (isFormParam != null ? !isFormParam.equals(that.isFormParam) : that.isFormParam != null)
if (isFormParam != that.isFormParam)
return false;
if (isQueryParam != null ? !isQueryParam.equals(that.isQueryParam) : that.isQueryParam != null)
if (isQueryParam != that.isQueryParam)
return false;
if (isPathParam != null ? !isPathParam.equals(that.isPathParam) : that.isPathParam != null)
if (isPathParam != that.isPathParam)
return false;
if (isHeaderParam != null ? !isHeaderParam.equals(that.isHeaderParam) : that.isHeaderParam != null)
if (isHeaderParam != that.isHeaderParam)
return false;
if (isCookieParam != null ? !isCookieParam.equals(that.isCookieParam) : that.isCookieParam != null)
if (isCookieParam != that.isCookieParam)
return false;
if (isBodyParam != null ? !isBodyParam.equals(that.isBodyParam) : that.isBodyParam != null)
if (isBodyParam != that.isBodyParam)
return false;
if (hasMore != null ? !hasMore.equals(that.hasMore) : that.hasMore != null)
if (hasMore != that.hasMore)
return false;
if (isContainer != null ? !isContainer.equals(that.isContainer) : that.isContainer != null)
if (isContainer != that.isContainer)
return false;
if (secondaryParam != null ? !secondaryParam.equals(that.secondaryParam) : that.secondaryParam != null)
if (secondaryParam != that.secondaryParam)
return false;
if (isCollectionFormatMulti != null ? !isCollectionFormatMulti.equals(that.isCollectionFormatMulti) : that.isCollectionFormatMulti != null)
if (isCollectionFormatMulti != that.isCollectionFormatMulti)
return false;
if (isPrimitiveType != null ? !isPrimitiveType.equals(that.isPrimitiveType) : that.isPrimitiveType != null)
if (isPrimitiveType != that.isPrimitiveType)
return false;
if (baseName != null ? !baseName.equals(that.baseName) : that.baseName != null)
return false;
@@ -204,33 +209,33 @@ public class CodegenParameter {
return false;
if (jsonSchema != null ? !jsonSchema.equals(that.jsonSchema) : that.jsonSchema != null)
return false;
if (isString != null ? !isString.equals(that.isString) : that.isString != null)
if (isString != that.isString)
return false;
if (isInteger != null ? !isInteger.equals(that.isInteger) : that.isInteger != null)
if (isInteger != that.isInteger)
return false;
if (isLong != null ? !isLong.equals(that.isLong) : that.isLong != null)
if (isLong != that.isLong)
return false;
if (isFloat != null ? !isFloat.equals(that.isFloat) : that.isFloat != null)
if (isFloat != that.isFloat)
return false;
if (isDouble != null ? !isDouble.equals(that.isDouble) : that.isDouble != null)
if (isDouble != that.isDouble)
return false;
if (isByteArray != null ? !isByteArray.equals(that.isByteArray) : that.isByteArray != null)
if (isByteArray != that.isByteArray)
return false;
if (isBinary != null ? !isBinary.equals(that.isBinary) : that.isBinary != null)
if (isBinary != that.isBinary)
return false;
if (isBoolean != null ? !isBoolean.equals(that.isBoolean) : that.isBoolean != null)
if (isBoolean != that.isBoolean)
return false;
if (isDate != null ? !isDate.equals(that.isDate) : that.isDate != null)
if (isDate != that.isDate)
return false;
if (isDateTime != null ? !isDateTime.equals(that.isDateTime) : that.isDateTime != null)
if (isDateTime != that.isDateTime)
return false;
if (isListContainer != null ? !isListContainer.equals(that.isListContainer) : that.isListContainer != null)
if (isListContainer != that.isListContainer)
return false;
if (isMapContainer != null ? !isMapContainer.equals(that.isMapContainer) : that.isMapContainer != null)
if (isMapContainer != that.isMapContainer)
return false;
if (isFile != null ? !isFile.equals(that.isFile) : that.isFile != null)
if (isFile != that.isFile)
return false;
if (notFile != null ? !notFile.equals(that.notFile) : that.notFile != null)
if (notFile != that.notFile)
return false;
if (_enum != null ? !_enum.equals(that._enum) : that._enum != null)
return false;
@@ -240,17 +245,17 @@ public class CodegenParameter {
return false;
if (vendorExtensions != null ? !vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions != null)
return false;
if (hasValidation != null ? !hasValidation.equals(that.hasValidation) : that.hasValidation != null)
if (hasValidation != that.hasValidation)
return false;
if (required != null ? !required.equals(that.required) : that.required != null)
if (required != that.required)
return false;
if (maximum != null ? !maximum.equals(that.maximum) : that.maximum != null)
return false;
if (exclusiveMaximum != null ? !exclusiveMaximum.equals(that.exclusiveMaximum) : that.exclusiveMaximum != null)
if (exclusiveMaximum != that.exclusiveMaximum)
return false;
if (minimum != null ? !minimum.equals(that.minimum) : that.minimum != null)
return false;
if (exclusiveMinimum != null ? !exclusiveMinimum.equals(that.exclusiveMinimum) : that.exclusiveMinimum != null)
if (exclusiveMinimum != that.exclusiveMinimum)
return false;
if (maxLength != null ? !maxLength.equals(that.maxLength) : that.maxLength != null)
return false;
@@ -262,7 +267,7 @@ public class CodegenParameter {
return false;
if (minItems != null ? !minItems.equals(that.minItems) : that.minItems != null)
return false;
if (uniqueItems != null ? !uniqueItems.equals(that.uniqueItems) : that.uniqueItems != null)
if (uniqueItems != that.uniqueItems)
return false;
return multipleOf != null ? multipleOf.equals(that.multipleOf) : that.multipleOf == null;
@@ -270,17 +275,17 @@ public class CodegenParameter {
@Override
public int hashCode() {
int result = isFormParam != null ? isFormParam.hashCode() : 0;
result = 31 * result + (isQueryParam != null ? isQueryParam.hashCode() : 0);
result = 31 * result + (isPathParam != null ? isPathParam.hashCode() : 0);
result = 31 * result + (isHeaderParam != null ? isHeaderParam.hashCode() : 0);
result = 31 * result + (isCookieParam != null ? isCookieParam.hashCode() : 0);
result = 31 * result + (isBodyParam != null ? isBodyParam.hashCode() : 0);
result = 31 * result + (hasMore != null ? hasMore.hashCode() : 0);
result = 31 * result + (isContainer != null ? isContainer.hashCode() : 0);
result = 31 * result + (secondaryParam != null ? secondaryParam.hashCode() : 0);
result = 31 * result + (isCollectionFormatMulti != null ? isCollectionFormatMulti.hashCode() : 0);
result = 31 * result + (isPrimitiveType != null ? isPrimitiveType.hashCode() : 0);
int result = isFormParam ? 13:31;
result = 31 * result + (isQueryParam ? 13:31);
result = 31 * result + (isPathParam ? 13:31);
result = 31 * result + (isHeaderParam ? 13:31);
result = 31 * result + (isCookieParam ? 13:31);
result = 31 * result + (isBodyParam ? 13:31);
result = 31 * result + (hasMore ? 13:31);
result = 31 * result + (isContainer ? 13:31);
result = 31 * result + (secondaryParam ? 13:31);
result = 31 * result + (isCollectionFormatMulti ? 13:31);
result = 31 * result + (isPrimitiveType ? 13:31);
result = 31 * result + (baseName != null ? baseName.hashCode() : 0);
result = 31 * result + (paramName != null ? paramName.hashCode() : 0);
result = 31 * result + (dataType != null ? dataType.hashCode() : 0);
@@ -294,37 +299,37 @@ public class CodegenParameter {
result = 31 * result + (defaultValue != null ? defaultValue.hashCode() : 0);
result = 31 * result + (example != null ? example.hashCode() : 0);
result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0);
result = 31 * result + (isString != null ? isString.hashCode() : 0);
result = 31 * result + (isInteger != null ? isInteger.hashCode() : 0);
result = 31 * result + (isLong != null ? isLong.hashCode() : 0);
result = 31 * result + (isFloat != null ? isFloat.hashCode() : 0);
result = 31 * result + (isDouble != null ? isDouble.hashCode() : 0);
result = 31 * result + (isByteArray != null ? isByteArray.hashCode() : 0);
result = 31 * result + (isBinary != null ? isBinary.hashCode() : 0);
result = 31 * result + (isBoolean != null ? isBoolean.hashCode() : 0);
result = 31 * result + (isDate != null ? isDate.hashCode() : 0);
result = 31 * result + (isDateTime != null ? isDateTime.hashCode() : 0);
result = 31 * result + (isListContainer != null ? isListContainer.hashCode() : 0);
result = 31 * result + (isMapContainer != null ? isMapContainer.hashCode() : 0);
result = 31 * result + (isFile != null ? isFile.hashCode() : 0);
result = 31 * result + (notFile != null ? notFile.hashCode() : 0);
result = 31 * result + (isString ? 13:31);
result = 31 * result + (isInteger ? 13:31);
result = 31 * result + (isLong ? 13:31);
result = 31 * result + (isFloat ? 13:31);
result = 31 * result + (isDouble ? 13:31);
result = 31 * result + (isByteArray ? 13:31);
result = 31 * result + (isBinary ? 13:31);
result = 31 * result + (isBoolean ? 13:31);
result = 31 * result + (isDate ? 13:31);
result = 31 * result + (isDateTime ? 13:31);
result = 31 * result + (isListContainer ? 13:31);
result = 31 * result + (isMapContainer ? 13:31);
result = 31 * result + (isFile ? 13:31);
result = 31 * result + (notFile ? 13:31);
result = 31 * result + (isEnum ? 1 : 0);
result = 31 * result + (_enum != null ? _enum.hashCode() : 0);
result = 31 * result + (allowableValues != null ? allowableValues.hashCode() : 0);
result = 31 * result + (items != null ? items.hashCode() : 0);
result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0);
result = 31 * result + (hasValidation != null ? hasValidation.hashCode() : 0);
result = 31 * result + (required != null ? required.hashCode() : 0);
result = 31 * result + (hasValidation ? 13:31);
result = 31 * result + (required ? 13:31);
result = 31 * result + (maximum != null ? maximum.hashCode() : 0);
result = 31 * result + (exclusiveMaximum != null ? exclusiveMaximum.hashCode() : 0);
result = 31 * result + (exclusiveMaximum ? 13:31);
result = 31 * result + (minimum != null ? minimum.hashCode() : 0);
result = 31 * result + (exclusiveMinimum != null ? exclusiveMinimum.hashCode() : 0);
result = 31 * result + (exclusiveMinimum ? 13:31);
result = 31 * result + (maxLength != null ? maxLength.hashCode() : 0);
result = 31 * result + (minLength != null ? minLength.hashCode() : 0);
result = 31 * result + (pattern != null ? pattern.hashCode() : 0);
result = 31 * result + (maxItems != null ? maxItems.hashCode() : 0);
result = 31 * result + (minItems != null ? minItems.hashCode() : 0);
result = 31 * result + (uniqueItems != null ? uniqueItems.hashCode() : 0);
result = 31 * result + (uniqueItems ? 13:31);
result = 31 * result + (multipleOf != null ? multipleOf.hashCode() : 0);
return result;
}

View File

@@ -7,24 +7,22 @@ import java.util.Map;
public class CodegenResponse {
public final List<CodegenProperty> headers = new ArrayList<CodegenProperty>();
public String code, message;
public Boolean hasMore;
public boolean hasMore;
public List<Map<String, Object>> examples;
public String dataType, baseType, containerType;
public Boolean isDefault;
public Boolean simpleType;
public Boolean primitiveType;
public Boolean isMapContainer;
public Boolean isListContainer;
public Boolean isBinary = Boolean.FALSE;
public Boolean isFile = Boolean.FALSE;
public boolean hasHeaders;
public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBoolean, isDate, isDateTime;
public boolean isDefault;
public boolean simpleType;
public boolean primitiveType;
public boolean isMapContainer;
public boolean isListContainer;
public boolean isBinary = false;
public boolean isFile = false;
public Object schema;
public String jsonSchema;
public Map<String, Object> vendorExtensions;
public boolean isWildcard() {
return "0".equals(code) || "default".equals(code);
}
@Override
public String toString() {
return String.format("%s(%s)", code, containerType);
@@ -43,7 +41,7 @@ public class CodegenResponse {
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (hasMore != null ? !hasMore.equals(that.hasMore) : that.hasMore != null)
if (hasMore != that.hasMore)
return false;
if (examples != null ? !examples.equals(that.examples) : that.examples != null)
return false;
@@ -53,19 +51,19 @@ public class CodegenResponse {
return false;
if (containerType != null ? !containerType.equals(that.containerType) : that.containerType != null)
return false;
if (isDefault != null ? !isDefault.equals(that.isDefault) : that.isDefault != null)
if (isDefault != that.isDefault)
return false;
if (simpleType != null ? !simpleType.equals(that.simpleType) : that.simpleType != null)
if (simpleType != that.simpleType)
return false;
if (primitiveType != null ? !primitiveType.equals(that.primitiveType) : that.primitiveType != null)
if (primitiveType != that.primitiveType)
return false;
if (isMapContainer != null ? !isMapContainer.equals(that.isMapContainer) : that.isMapContainer != null)
if (isMapContainer != that.isMapContainer)
return false;
if (isListContainer != null ? !isListContainer.equals(that.isListContainer) : that.isListContainer != null)
if (isListContainer != that.isListContainer)
return false;
if (isBinary != null ? !isBinary.equals(that.isBinary) : that.isBinary != null)
if (isBinary != that.isBinary)
return false;
if (isFile != null ? !isFile.equals(that.isFile) : that.isFile != null)
if (isFile != that.isFile)
return false;
if (schema != null ? !schema.equals(that.schema) : that.schema != null)
return false;
@@ -80,18 +78,18 @@ public class CodegenResponse {
int result = headers.hashCode();
result = 31 * result + (code != null ? code.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + (hasMore != null ? hasMore.hashCode() : 0);
result = 31 * result + (hasMore ? 13:31);
result = 31 * result + (examples != null ? examples.hashCode() : 0);
result = 31 * result + (dataType != null ? dataType.hashCode() : 0);
result = 31 * result + (baseType != null ? baseType.hashCode() : 0);
result = 31 * result + (containerType != null ? containerType.hashCode() : 0);
result = 31 * result + (isDefault != null ? isDefault.hashCode() : 0);
result = 31 * result + (simpleType != null ? simpleType.hashCode() : 0);
result = 31 * result + (primitiveType != null ? primitiveType.hashCode() : 0);
result = 31 * result + (isMapContainer != null ? isMapContainer.hashCode() : 0);
result = 31 * result + (isListContainer != null ? isListContainer.hashCode() : 0);
result = 31 * result + (isBinary != null ? isBinary.hashCode() : 0);
result = 31 * result + (isFile != null ? isFile.hashCode() : 0);
result = 31 * result + (isDefault ? 13:31);
result = 31 * result + (simpleType ? 13:31);
result = 31 * result + (primitiveType ? 13:31);
result = 31 * result + (isMapContainer ? 13:31);
result = 31 * result + (isListContainer ? 13:31);
result = 31 * result + (isBinary ? 13:31);
result = 31 * result + (isFile ? 13:31);
result = 31 * result + (schema != null ? schema.hashCode() : 0);
result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0);
result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0);

View File

@@ -811,6 +811,7 @@ public class DefaultCodegen {
typeMapping.put("ByteArray", "byte[]");
typeMapping.put("binary", "byte[]");
typeMapping.put("file", "File");
typeMapping.put("UUID", "UUID");
instantiationTypes = new HashMap<String, String>();
@@ -1481,7 +1482,10 @@ public class DefaultCodegen {
property.title = p.getTitle();
property.getter = "get" + getterAndSetterCapitalize(name);
property.setter = "set" + getterAndSetterCapitalize(name);
property.example = toExampleValue(p);
String example = toExampleValue(p);
if(!"null".equals(example)) {
property.example = example;
}
property.defaultValue = toDefaultValue(p);
property.defaultValueWithParam = toDefaultValueWithParam(name, p);
property.jsonSchema = Json.pretty(p);
@@ -2046,10 +2050,10 @@ public class DefaultCodegen {
}
r.isDefault = response == methodResponse;
op.responses.add(r);
if (r.isBinary && r.isDefault){
if (Boolean.TRUE.equals(r.isBinary) && Boolean.TRUE.equals(r.isDefault)){
op.isResponseBinary = Boolean.TRUE;
}
if (r.isFile && r.isDefault){
if (Boolean.TRUE.equals(r.isFile) && Boolean.TRUE.equals(r.isDefault)){
op.isResponseFile = Boolean.TRUE;
}
}
@@ -2161,7 +2165,7 @@ public class DefaultCodegen {
} else if (param instanceof FormParameter) {
formParams.add(p.copy());
}
if (p.required == null || !p.required) {
if (!p.required) {
op.hasOptionalParams = true;
}
}
@@ -2179,10 +2183,8 @@ public class DefaultCodegen {
Collections.sort(allParams, new Comparator<CodegenParameter>() {
@Override
public int compare(CodegenParameter one, CodegenParameter another) {
boolean oneRequired = one.required == null ? false : one.required;
boolean anotherRequired = another.required == null ? false : another.required;
if (oneRequired == anotherRequired) return 0;
else if (oneRequired) return -1;
if (one.required == another.required) return 0;
else if (one.required) return -1;
else return 1;
}
});
@@ -2233,6 +2235,7 @@ public class DefaultCodegen {
r.jsonSchema = Json.pretty(response);
r.vendorExtensions = response.getVendorExtensions();
addHeaders(response, r.headers);
r.hasHeaders = !r.headers.isEmpty();
if (r.schema != null) {
Property responseProperty = response.getSchema();
@@ -2251,8 +2254,33 @@ public class DefaultCodegen {
}
}
r.dataType = cm.datatype;
r.isBinary = isDataTypeBinary(cm.datatype);
r.isFile = isDataTypeFile(cm.datatype);
if (Boolean.TRUE.equals(cm.isString)) {
r.isString = true;
} else if (Boolean.TRUE.equals(cm.isBoolean)) {
r.isBoolean = true;
} else if (Boolean.TRUE.equals(cm.isLong)) {
r.isLong = true;
} else if (Boolean.TRUE.equals(cm.isInteger)) {
r.isInteger = true;
} else if (Boolean.TRUE.equals(cm.isDouble)) {
r.isDouble = true;
} else if (Boolean.TRUE.equals(cm.isFloat)) {
r.isFloat = true;
} else if (Boolean.TRUE.equals(cm.isByteArray)) {
r.isByteArray = true;
} else if (Boolean.TRUE.equals(cm.isBinary)) {
r.isBinary = true;
} else if (Boolean.TRUE.equals(cm.isFile)) {
r.isFile = true;
} else if (Boolean.TRUE.equals(cm.isDate)) {
r.isDate = true;
} else if (Boolean.TRUE.equals(cm.isDateTime)) {
r.isDateTime = true;
} else {
LOGGER.debug("Property type is not primitive: " + cm.datatype);
}
if (cm.isContainer) {
r.simpleType = false;
r.containerType = cm.containerType;
@@ -2410,14 +2438,14 @@ public class DefaultCodegen {
p.minimum = qp.getMinimum() == null ? null : String.valueOf(qp.getMinimum());
}
p.exclusiveMaximum = qp.isExclusiveMaximum();
p.exclusiveMinimum = qp.isExclusiveMinimum();
p.exclusiveMaximum = qp.isExclusiveMaximum() == null ? false : qp.isExclusiveMaximum();
p.exclusiveMinimum = qp.isExclusiveMinimum() == null ? false : qp.isExclusiveMinimum();
p.maxLength = qp.getMaxLength();
p.minLength = qp.getMinLength();
p.pattern = toRegularExpression(qp.getPattern());
p.maxItems = qp.getMaxItems();
p.minItems = qp.getMinItems();
p.uniqueItems = qp.isUniqueItems();
p.uniqueItems = qp.isUniqueItems() == null ? false : qp.isUniqueItems();
p.multipleOf = qp.getMultipleOf();
// exclusive* are noop without corresponding min/max
@@ -2452,6 +2480,9 @@ public class DefaultCodegen {
p.isPrimitiveType = cp.isPrimitiveType;
p.isBinary = isDataTypeBinary(cp.datatype);
p.isFile = isDataTypeFile(cp.datatype);
if (cp.complexType != null) {
imports.add(cp.complexType);
}
}
// set boolean flag (e.g. isString)

View File

@@ -75,12 +75,12 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
StringBuilder hostBuilder = new StringBuilder();
hostBuilder.append(getScheme());
hostBuilder.append("://");
if (swagger.getHost() != null) {
if (!StringUtils.isEmpty(swagger.getHost())) {
hostBuilder.append(swagger.getHost());
} else {
hostBuilder.append("localhost");
}
if (swagger.getBasePath() != null) {
if (!StringUtils.isEmpty(swagger.getBasePath()) && !swagger.getBasePath().equals("/")) {
hostBuilder.append(swagger.getBasePath());
}
return hostBuilder.toString();
@@ -154,8 +154,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
// set a default description if none if provided
config.additionalProperties().put("appDescription",
"No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)");
config.additionalProperties().put("unescapedAppDescription", "No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)");
} else {
config.additionalProperties().put("appDescription", config.escapeText(info.getDescription()));
config.additionalProperties().put("unescapedAppDescription", info.getDescription());
}
if (info.getContact() != null) {

View File

@@ -19,6 +19,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.HashSet;
@@ -34,7 +35,7 @@ import static org.apache.commons.lang3.StringUtils.isNotEmpty;
* It also has a convenience method for creating a ClientOptInput class which is THE object DefaultGenerator.java needs
* to generate code.
*/
public class CodegenConfigurator {
public class CodegenConfigurator implements Serializable {
public static final Logger LOGGER = LoggerFactory.getLogger(CodegenConfigurator.class);
@@ -62,7 +63,7 @@ public class CodegenConfigurator {
private Map<String, String> importMappings = new HashMap<String, String>();
private Set<String> languageSpecificPrimitives = new HashSet<String>();
private Map<String, String> reservedWordMappings = new HashMap<String, String>();
private String gitUserId="GIT_USER_ID";
private String gitRepoId="GIT_REPO_ID";
private String releaseNote="Minor update";
@@ -155,7 +156,7 @@ public class CodegenConfigurator {
// check to see if the folder exists
if (!(f.exists() && f.isDirectory())) {
throw new IllegalArgumentException("Template directory " + templateDir + " does not exist.");
throw new IllegalArgumentException("Template directory " + templateDir + " does not exist.");
}
this.templateDir = f.getAbsolutePath();
@@ -266,7 +267,7 @@ public class CodegenConfigurator {
this.additionalProperties = additionalProperties;
return this;
}
public CodegenConfigurator addAdditionalProperty(String key, Object value) {
this.additionalProperties.put(key, value);
return this;
@@ -344,16 +345,16 @@ public class CodegenConfigurator {
this.httpUserAgent= httpUserAgent;
return this;
}
public Map<String, String> getReservedWordsMappings() {
return reservedWordMappings;
}
public CodegenConfigurator setReservedWordsMappings(Map<String, String> reservedWordsMappings) {
this.reservedWordMappings = reservedWordsMappings;
return this;
}
public CodegenConfigurator addAdditionalReservedWordMapping(String key, String value) {
this.reservedWordMappings.put(key, value);
return this;
@@ -367,7 +368,7 @@ public class CodegenConfigurator {
this.ignoreFileOverride = ignoreFileOverride;
return this;
}
public ClientOptInput toClientOptInput() {
Validate.notEmpty(lang, "language must be specified");
@@ -388,7 +389,7 @@ public class CodegenConfigurator {
config.importMapping().putAll(importMappings);
config.languageSpecificPrimitives().addAll(languageSpecificPrimitives);
config.reservedWordsMappings().putAll(reservedWordMappings);
checkAndSetAdditionalProperty(apiPackage, CodegenConstants.API_PACKAGE);
checkAndSetAdditionalProperty(modelPackage, CodegenConstants.MODEL_PACKAGE);
checkAndSetAdditionalProperty(invokerPackage, CodegenConstants.INVOKER_PACKAGE);

View File

@@ -1,5 +1,8 @@
package io.swagger.codegen.examples;
import static io.swagger.models.properties.StringProperty.Format.URI;
import static io.swagger.models.properties.StringProperty.Format.URL;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.properties.ArrayProperty;
@@ -11,7 +14,6 @@ import io.swagger.models.properties.DecimalProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FileProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.ObjectProperty;
@@ -20,10 +22,12 @@ import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import io.swagger.models.properties.UUIDProperty;
import io.swagger.util.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -31,6 +35,17 @@ import java.util.Map;
import java.util.Set;
public class ExampleGenerator {
private static final Logger logger = LoggerFactory.getLogger(ExampleGenerator.class);
// TODO: move constants to more appropriate location
private static final String MIME_TYPE_JSON = "application/json";
private static final String MIME_TYPE_XML = "application/xml";
private static final String EXAMPLE = "example";
private static final String CONTENT_TYPE = "contentType";
private static final String OUTPUT = "output";
private static final String NONE = "none";
protected Map<String, Model> examples;
public ExampleGenerator(Map<String, Model> examples) {
@@ -38,53 +53,76 @@ public class ExampleGenerator {
}
public List<Map<String, String>> generate(Map<String, Object> examples, List<String> mediaTypes, Property property) {
List<Map<String, String>> output = new ArrayList<Map<String, String>>();
Set<String> processedModels = new HashSet<String>();
List<Map<String, String>> output = new ArrayList<>();
Set<String> processedModels = new HashSet<>();
if (examples == null) {
if (mediaTypes == null) {
// assume application/json for this
mediaTypes = Arrays.asList("application/json"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
mediaTypes = Collections.singletonList(MIME_TYPE_JSON); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
}
for (String mediaType : mediaTypes) {
Map<String, String> kv = new HashMap<String, String>();
kv.put("contentType", mediaType);
if (property != null && mediaType.startsWith("application/json")) {
Map<String, String> kv = new HashMap<>();
kv.put(CONTENT_TYPE, mediaType);
if (property != null && mediaType.startsWith(MIME_TYPE_JSON)) {
String example = Json.pretty(resolvePropertyToExample(mediaType, property, processedModels));
if (example != null) {
kv.put("example", example);
kv.put(EXAMPLE, example);
output.add(kv);
}
} else if (property != null && mediaType.startsWith("application/xml")) {
} else if (property != null && mediaType.startsWith(MIME_TYPE_XML)) {
String example = new XmlExampleGenerator(this.examples).toXml(property);
if (example != null) {
kv.put("example", example);
kv.put(EXAMPLE, example);
output.add(kv);
}
}
}
} else {
for (Map.Entry<String, Object> entry : examples.entrySet()) {
final Map<String, String> kv = new HashMap<String, String>();
kv.put("contentType", entry.getKey());
kv.put("example", Json.pretty(entry.getValue()));
final Map<String, String> kv = new HashMap<>();
kv.put(CONTENT_TYPE, entry.getKey());
kv.put(EXAMPLE, Json.pretty(entry.getValue()));
output.add(kv);
}
}
if (output.size() == 0) {
Map<String, String> kv = new HashMap<String, String>();
kv.put("output", "none");
Map<String, String> kv = new HashMap<>();
kv.put(OUTPUT, NONE);
output.add(kv);
}
return output;
}
protected Object resolvePropertyToExample(String mediaType, Property property, Set<String> processedModels) {
private Object resolvePropertyToExample(String mediaType, Property property, Set<String> processedModels) {
logger.debug("Resolving example for property {}...", property);
if (property.getExample() != null) {
logger.debug("Example set in swagger spec, returning example: '{}'", property.getExample().toString());
return property.getExample();
} else if (property instanceof StringProperty) {
logger.debug("String property");
String defaultValue = ((StringProperty) property).getDefault();
if (defaultValue != null && !defaultValue.isEmpty()) {
logger.debug("Default value found: '{}'", defaultValue);
return defaultValue;
}
List<String> enumValues = ((StringProperty) property).getEnum();
if (enumValues != null && !enumValues.isEmpty()) {
logger.debug("Enum value found: '{}'", enumValues.get(0));
return enumValues.get(0);
}
String format = property.getFormat();
if (format != null && (URI.getName().equals(format) || URL.getName().equals(format))) {
logger.debug("URI or URL format, without default or enum, generating random one.");
return "http://example.com/aeiou";
}
logger.debug("No values found, using default string 'aeiou' as example");
return "aeiou";
} else if (property instanceof BooleanProperty) {
Boolean defaultValue = ((BooleanProperty) property).getDefault();
if (defaultValue != null) {
return defaultValue;
}
return Boolean.TRUE;
} else if (property instanceof ArrayProperty) {
Property innerType = ((ArrayProperty) property).getItems();
@@ -97,21 +135,28 @@ public class ExampleGenerator {
return "2000-01-23";
} else if (property instanceof DateTimeProperty) {
return "2000-01-23T04:56:07.000+00:00";
} else if (property instanceof DecimalProperty) {
return new BigDecimal(1.3579);
} else if (property instanceof DoubleProperty) {
return 3.149;
Double min = ((DecimalProperty) property).getMinimum() == null ? null : ((DecimalProperty) property).getMinimum().doubleValue();
Double max = ((DecimalProperty) property).getMaximum() == null ? null : ((DecimalProperty) property).getMaximum().doubleValue();
return randomNumber(min, max);
} else if (property instanceof FloatProperty) {
Double min = ((DecimalProperty) property).getMinimum() == null ? null : ((DecimalProperty) property).getMinimum().doubleValue();
Double max = ((DecimalProperty) property).getMaximum() == null ? null : ((DecimalProperty) property).getMaximum().doubleValue();
return (float) randomNumber(min, max);
} else if (property instanceof DecimalProperty) {
Double min = ((DecimalProperty) property).getMinimum() == null ? null : ((DecimalProperty) property).getMinimum().doubleValue();
Double max = ((DecimalProperty) property).getMaximum() == null ? null : ((DecimalProperty) property).getMaximum().doubleValue();
return new BigDecimal(randomNumber(min, max));
} else if (property instanceof FileProperty) {
return ""; // TODO
} else if (property instanceof FloatProperty) {
return 1.23f;
} else if (property instanceof IntegerProperty) {
return 123;
} else if (property instanceof LongProperty) {
return 123456789L;
// Properties that are not Integer or Long may still be BaseInteger
} else if (property instanceof BaseIntegerProperty) {
return 123;
Double min = ((BaseIntegerProperty) property).getMinimum() == null ? null : ((BaseIntegerProperty) property).getMinimum().doubleValue();
Double max = ((BaseIntegerProperty) property).getMaximum() == null ? null : ((BaseIntegerProperty) property).getMaximum().doubleValue();
return (long) randomNumber(min, max);
} else if (property instanceof BaseIntegerProperty) { // Includes IntegerProperty
Double min = ((BaseIntegerProperty) property).getMinimum() == null ? null : ((BaseIntegerProperty) property).getMinimum().doubleValue();
Double max = ((BaseIntegerProperty) property).getMaximum() == null ? null : ((BaseIntegerProperty) property).getMaximum().doubleValue();
return (int) randomNumber(min, max);
} else if (property instanceof MapProperty) {
Map<String, Object> mp = new HashMap<String, Object>();
if (property.getName() != null) {
@@ -126,10 +171,12 @@ public class ExampleGenerator {
return "{}";
} else if (property instanceof RefProperty) {
String simpleName = ((RefProperty) property).getSimpleRef();
logger.debug("Ref property, simple name: {}", simpleName);
Model model = examples.get(simpleName);
if (model != null) {
return resolveModelToExample(simpleName, mediaType, model, processedModels);
}
logger.warn("Ref property with empty model.");
} else if (property instanceof UUIDProperty) {
return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
}
@@ -137,16 +184,35 @@ public class ExampleGenerator {
return "";
}
public Object resolveModelToExample(String name, String mediaType, Model model, Set<String> processedModels) {
private double randomNumber(Double min, Double max) {
if (min != null && max != null) {
double range = max - min;
return Math.random() * range + min;
} else if (min != null) {
return Math.random() + min;
} else if (max != null) {
return Math.random() * max;
} else {
return Math.random() * 10;
}
}
private Object resolveModelToExample(String name, String mediaType, Model model, Set<String> processedModels) {
if (processedModels.contains(name)) {
return "";
}
if (model instanceof ModelImpl) {
processedModels.add(name);
ModelImpl impl = (ModelImpl) model;
Map<String, Object> values = new HashMap<String, Object>();
Map<String, Object> values = new HashMap<>();
if (impl.getProperties() != null) {
logger.debug("Resolving model '{}' to example", name);
if (impl.getExample() != null) {
logger.debug("Using example from spec: {}", impl.getExample());
return impl.getExample();
} else if (impl.getProperties() != null) {
logger.debug("Creating example from model values");
for (String propertyName : impl.getProperties().keySet()) {
Property property = impl.getProperties().get(propertyName);
values.put(propertyName, resolvePropertyToExample(mediaType, property, processedModels));

View File

@@ -20,7 +20,7 @@ import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import org.codehaus.plexus.util.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@@ -45,7 +45,7 @@ public class CodegenIgnoreProcessor {
if (directory.exists() && directory.isDirectory()) {
loadFromFile(targetIgnoreFile);
} else {
LOGGER.warn("Directory does not exist, or is inaccessible. No file will be evaluated.");
LOGGER.warn("Output directory does not exist, or is inaccessible. No file (.swager-codegen-ignore) will be evaluated.");
}
}

View File

@@ -318,6 +318,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
typeMapping.put("array", "java.util.List");
typeMapping.put("map", "java.util.Map");
typeMapping.put("DateTime", "java.util.Date");
typeMapping.put("UUID", "java.util.UUID");
typeMapping.remove("List");
importMapping.remove("Date");
importMapping.remove("Map");
@@ -327,6 +328,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
importMapping.remove("List");
importMapping.remove("Set");
importMapping.remove("DateTime");
importMapping.remove("UUID");
instantiationTypes.put("array", "java.util.ArrayList");
instantiationTypes.put("map", "java.util.HashMap");
}

View File

@@ -21,7 +21,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
protected String testResourcesFolder = "src/test/resources";
protected String title = "Swagger Server";
protected boolean useBeanValidation = true;
protected boolean useBeanValidation = true;
static Logger LOGGER = LoggerFactory.getLogger(AbstractJavaJAXRSServerCodegen.class);
@@ -44,7 +44,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC));
cliOptions.add(new CliOption("title", "a title describing the application"));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
}
@@ -67,13 +67,13 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER);
}
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
}
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
}
if (useBeanValidation) {
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
}
if (useBeanValidation) {
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
}
}
@@ -153,6 +153,12 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
if ( "0".equals(resp.code) ) {
resp.code = "200";
}
// set vendorExtensions.x-java-is-response-void to true as dataType is set to "void"
if (resp.dataType == null) {
resp.vendorExtensions.put("x-java-is-response-void", true);
}
}
}
@@ -220,8 +226,8 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/');
}
public void setUseBeanValidation(boolean useBeanValidation) {
this.useBeanValidation = useBeanValidation;
}
public void setUseBeanValidation(boolean useBeanValidation) {
this.useBeanValidation = useBeanValidation;
}
}

View File

@@ -1,29 +1,31 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.models.parameters.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.BodyParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.parameters.SerializableParameter;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.io.File;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.Set;
public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
@@ -194,29 +196,22 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public void processOpts() {
super.processOpts();
String curlopts = "";
if (additionalProperties.containsKey(CURL_OPTIONS)) {
setCurlOptions(additionalProperties.get(CURL_OPTIONS).toString());
additionalProperties.put("x-codegen-curl-options", curlopts);
additionalProperties.put("x-codegen-curl-options", this.curlOptions);
}
if (additionalProperties.containsKey(PROCESS_MARKDOWN)) {
setProcessMarkdown(
Boolean.parseBoolean(
additionalProperties.get(PROCESS_MARKDOWN).toString()));
setProcessMarkdown(convertPropertyToBooleanAndWriteBack(PROCESS_MARKDOWN));
}
if (additionalProperties.containsKey(GENERATE_BASH_COMPLETION)) {
setGenerateBashCompletion(
Boolean.parseBoolean(
additionalProperties.get(GENERATE_BASH_COMPLETION).toString()));
setGenerateBashCompletion(convertPropertyToBooleanAndWriteBack(GENERATE_BASH_COMPLETION));
}
if (additionalProperties.containsKey(GENERATE_ZSH_COMPLETION)) {
setGenerateZshCompletion(
Boolean.parseBoolean(
additionalProperties.get(GENERATE_ZSH_COMPLETION).toString()));
setGenerateZshCompletion(convertPropertyToBooleanAndWriteBack(GENERATE_ZSH_COMPLETION));
}
if (additionalProperties.containsKey(SCRIPT_NAME)) {
@@ -578,16 +573,17 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
List codesamples = (List)op.vendorExtensions.get("x-code-samples");
for (Object codesample : codesamples) {
ObjectNode codesample_object = (ObjectNode)codesample;
if(codesample instanceof ObjectNode) {
ObjectNode codesample_object = (ObjectNode) codesample;
if((codesample_object.get("lang").asText()).equals("Shell")) {
if ((codesample_object.get("lang").asText()).equals("Shell")) {
op.vendorExtensions.put("x-bash-codegen-sample",
escapeUnsafeCharacters(
codesample_object.get("source").asText()));
}
op.vendorExtensions.put("x-bash-codegen-sample",
escapeUnsafeCharacters(
codesample_object.get("source").asText()));
}
}
}
}

View File

@@ -113,6 +113,7 @@ public class CppRestClientCodegen extends DefaultCodegen implements CodegenConfi
typeMapping.put("file", "HttpContent");
typeMapping.put("object", "Object");
typeMapping.put("binary", "std::string");
typeMapping.put("number", "double");
super.importMapping = new HashMap<String, String>();
importMapping.put("std::vector", "#include <vector>");

View File

@@ -117,8 +117,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
super.processOpts();
if (additionalProperties.containsKey(BROWSER_CLIENT)) {
this.setBrowserClient(Boolean.parseBoolean((String) additionalProperties.get(BROWSER_CLIENT)));
additionalProperties.put(BROWSER_CLIENT, browserClient);
this.setBrowserClient(convertPropertyToBooleanAndWriteBack(BROWSER_CLIENT));
} else {
//not set, use to be passed to template
additionalProperties.put(BROWSER_CLIENT, browserClient);
@@ -149,6 +148,14 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
}
// default HIDE_GENERATION_TIMESTAMP to true
if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) {
additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString());
} else {
additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP,
Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString()));
}
// make api and model doc path available in mustache template
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);

View File

@@ -15,12 +15,12 @@ import java.util.List;
import java.util.Map;
public class FinchServerCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.petstore.client";
protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger";
protected String artifactId = "finch-server";
protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/scala";
protected String packageName = "io.swagger.petstore";
protected String packageName = "io.swagger";
public FinchServerCodegen() {
super();
@@ -156,7 +156,7 @@ public class FinchServerCodegen extends DefaultCodegen implements CodegenConfig
importMapping.put("LocalTime", "java.time.LocalTime");
cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Finch package name (e.g. io.swagger.petstore).")
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Finch package name (e.g. io.swagger).")
.defaultValue(this.packageName));
cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC));

View File

@@ -50,6 +50,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
languageSpecificPrimitives.add("datetime");
languageSpecificPrimitives.add("date");
languageSpecificPrimitives.add("file");
languageSpecificPrimitives.add("object");
typeMapping.clear();
typeMapping.put("integer", "int");
@@ -413,33 +414,9 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
@Override
public String toModelFilename(String name) {
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// remove dollar sign
name = name.replaceAll("$", "");
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + underscore(dropDots("model_" + name)));
name = "model_" + name; // e.g. return => ModelReturn (after camelize)
}
// model name starts with number
if (name.matches("^\\d.*")) {
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + underscore("model_" + name));
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
}
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
// underscore the model file name
// PhoneNumber => phone_number
return underscore(dropDots(name));
return underscore(dropDots(toModelName(name)));
}
@Override

View File

@@ -389,7 +389,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
// Query parameters appended to routes
for (CodegenParameter param : op.queryParams) {
String paramType = param.dataType;
if(param.isListContainer != null && param.isListContainer) {
if (param.isListContainer) {
paramType = makeQueryListType(paramType, param.collectionFormat);
}
path.add("QueryParam \"" + param.baseName + "\" " + paramType);
@@ -420,7 +420,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
path.add("Header \"" + param.baseName + "\" " + param.dataType);
String paramType = param.dataType;
if(param.isListContainer != null && param.isListContainer) {
if (param.isListContainer) {
paramType = makeQueryListType(paramType, param.collectionFormat);
}
type.add("Maybe " + paramType);

View File

@@ -21,30 +21,30 @@ import io.swagger.codegen.languages.features.LoggingTestFeatures;
import io.swagger.models.Operation;
public class JavaCXFClientCodegen extends AbstractJavaCodegen
implements BeanValidationFeatures, JaxbFeatures, GzipTestFeatures, LoggingTestFeatures
{
implements BeanValidationFeatures, JaxbFeatures, GzipTestFeatures, LoggingTestFeatures
{
private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFClientCodegen.class);
/**
* Name of the sub-directory in "src/main/resource" where to find the
* Mustache template for the JAX-RS Codegen.
*/
protected static final String JAXRS_TEMPLATE_DIRECTORY_NAME = "JavaJaxRS";
protected boolean useJaxbAnnotations = true;
protected boolean useBeanValidation = false;
protected boolean useGzipFeatureForTests = false;
protected boolean useLoggingFeatureForTests = false;
public JavaCXFClientCodegen()
{
super();
supportsInheritance = true;
sourceFolder = "src/gen/java";
invokerPackage = "io.swagger.api";
artifactId = "swagger-jaxrs-client";
@@ -52,9 +52,9 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
outputFolder = "generated-code/JavaJaxRS-CXF";
// clear model and api doc template as this codegen
// does not support auto-generated markdown doc at the moment
//TODO: add doc templates
@@ -63,7 +63,6 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "javax.xml.datatype.XMLGregorianCalendar"); // Map DateTime fields to Java standart class 'XMLGregorianCalendar'
importMapping.put("LocalDate", "org.joda.time.LocalDate");
@@ -72,11 +71,11 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen
cliOptions.add(CliOption.newBoolean(USE_JAXB_ANNOTATIONS, "Use JAXB annotations for XML"));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE_FOR_TESTS, "Use Gzip Feature for tests"));
cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE_FOR_TESTS, "Use Logging Feature for tests"));
}
@@ -84,7 +83,7 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen
public void processOpts()
{
super.processOpts();
if (additionalProperties.containsKey(USE_JAXB_ANNOTATIONS)) {
boolean useJaxbAnnotationsProp = convertPropertyToBooleanAndWriteBack(USE_JAXB_ANNOTATIONS);
this.setUseJaxbAnnotations(useJaxbAnnotationsProp);
@@ -94,15 +93,15 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen
boolean useBeanValidationProp = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION);
this.setUseBeanValidation(useBeanValidationProp);
}
this.setUseGzipFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE_FOR_TESTS));
this.setUseLoggingFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE_FOR_TESTS));
supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen
writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml"));
}
@Override
@@ -117,13 +116,13 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen
{
return CodegenType.CLIENT;
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
super.addOperationToGroup(tag, resourcePath, operation, co, operations);
super.addOperationToGroup(tag, resourcePath, operation, co, operations);
co.subresourceOperation = !co.path.isEmpty();
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
@@ -132,17 +131,17 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen
model.imports.remove("JsonSerialize");
model.imports.remove("ToStringSerializer");
}
@Override
public String getHelp()
{
return "Generates a Java JAXRS Client based on Apache CXF framework.";
}
public void setUseBeanValidation(boolean useBeanValidation) {
this.useBeanValidation = useBeanValidation;
}
public void setUseJaxbAnnotations(boolean useJaxbAnnotations) {
this.useJaxbAnnotations = useJaxbAnnotations;

View File

@@ -78,7 +78,6 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "javax.xml.datatype.XMLGregorianCalendar"); // Map DateTime fields to Java standart class 'XMLGregorianCalendar'
importMapping.put("LocalDate", "org.joda.time.LocalDate");

View File

@@ -2,6 +2,7 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.codegen.languages.features.GzipFeatures;
import io.swagger.codegen.languages.features.PerformBeanValidationFeatures;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
@@ -13,13 +14,17 @@ import java.util.*;
import java.util.regex.Pattern;
public class JavaClientCodegen extends AbstractJavaCodegen
implements BeanValidationFeatures, PerformBeanValidationFeatures {
implements BeanValidationFeatures, PerformBeanValidationFeatures,
GzipFeatures
{
static final String MEDIA_TYPE = "mediaType";
@SuppressWarnings("hiding")
@SuppressWarnings("hiding")
private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class);
public static final String USE_RX_JAVA = "useRxJava";
public static final String USE_RX_JAVA2 = "useRxJava2";
public static final String DO_NOT_USE_RX = "doNotUseRx";
public static final String USE_PLAY24_WS = "usePlay24WS";
public static final String PARCELABLE_MODEL = "parcelableModel";
@@ -28,10 +33,13 @@ public class JavaClientCodegen extends AbstractJavaCodegen
protected String gradleWrapperPackage = "gradle.wrapper";
protected boolean useRxJava = false;
protected boolean useRxJava2 = false;
protected boolean doNotUseRx = true; // backwards compatibility for swagger configs that specify neither rx1 nor rx2 (mustache does not allow for boolean operators so we need this extra field)
protected boolean usePlay24WS = false;
protected boolean parcelableModel = false;
protected boolean useBeanValidation = false;
protected boolean performBeanValidation = false;
protected boolean useGzipFeature = false;
public JavaClientCodegen() {
super();
@@ -43,18 +51,20 @@ public class JavaClientCodegen extends AbstractJavaCodegen
modelPackage = "io.swagger.client.model";
cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library."));
cliOptions.add(CliOption.newBoolean(USE_RX_JAVA2, "Whether to use the RxJava2 adapter with the retrofit2 library."));
cliOptions.add(CliOption.newBoolean(PARCELABLE_MODEL, "Whether to generate models for Android that implement Parcelable with the okhttp-gson library."));
cliOptions.add(CliOption.newBoolean(USE_PLAY24_WS, "Use Play! 2.4 Async HTTP client (Play WS API)"));
cliOptions.add(CliOption.newBoolean(SUPPORT_JAVA6, "Whether to support Java6 with the Jersey1 library."));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
cliOptions.add(CliOption.newBoolean(PERFORM_BEANVALIDATION, "Perform BeanValidation"));
cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE, "Send gzip-encoded requests"));
supportedLibraries.put("jersey1", "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0. Enable Java6 support using '-DsupportJava6=true'.");
supportedLibraries.put("jersey1", "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0. Enable Java6 support using '-DsupportJava6=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.");
supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0");
supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.22.2. JSON processing: Jackson 2.7.0");
supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2. Enable Parcelable modles on Android using '-DparcelableModel=true'");
supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2. Enable Parcelable modles on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.");
supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead.");
supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.3)");
supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2). Enable the RxJava adapter using '-DuseRxJava[2]=true'. (RxJava 1.x or 2.x)");
CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
libraryOption.setEnum(supportedLibraries);
@@ -84,9 +94,17 @@ public class JavaClientCodegen extends AbstractJavaCodegen
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(USE_RX_JAVA)) {
if (additionalProperties.containsKey(USE_RX_JAVA) && additionalProperties.containsKey(USE_RX_JAVA2)) {
LOGGER.warn("You specified both RxJava versions 1 and 2 but they are mutually exclusive. Defaulting to v2.");
} else if (additionalProperties.containsKey(USE_RX_JAVA)) {
this.setUseRxJava(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA).toString()));
}
if (additionalProperties.containsKey(USE_RX_JAVA2)) {
this.setUseRxJava2(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA2).toString()));
}
if (!useRxJava && !useRxJava2) {
additionalProperties.put(DO_NOT_USE_RX, true);
}
if (additionalProperties.containsKey(USE_PLAY24_WS)) {
this.setUsePlay24WS(Boolean.valueOf(additionalProperties.get(USE_PLAY24_WS).toString()));
}
@@ -106,6 +124,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen
this.setPerformBeanValidation(convertPropertyToBooleanAndWriteBack(PERFORM_BEANVALIDATION));
}
if (additionalProperties.containsKey(USE_GZIP_FEATURE)) {
this.setUseGzipFeature(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE));
}
final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/");
final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/");
@@ -161,6 +183,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
supportingFiles.add(new SupportingFile("ProgressRequestBody.mustache", invokerFolder, "ProgressRequestBody.java"));
supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java"));
supportingFiles.add(new SupportingFile("GzipRequestInterceptor.mustache", invokerFolder, "GzipRequestInterceptor.java"));
additionalProperties.put("gson", "true");
} else if (usesAnyRetrofitLibrary()) {
supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java"));
@@ -233,7 +256,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
if ( isMultipartType(operation.consumes) ) {
operation.isMultipart = Boolean.TRUE;
}
}
else {
operation.prioritizedContentTypes = prioritizeContentTypes(operation.consumes);
}
@@ -341,6 +364,16 @@ public class JavaClientCodegen extends AbstractJavaCodegen
public void setUseRxJava(boolean useRxJava) {
this.useRxJava = useRxJava;
doNotUseRx = false;
}
public void setUseRxJava2(boolean useRxJava2) {
this.useRxJava2 = useRxJava2;
doNotUseRx = false;
}
public void setDoNotUseRx(boolean doNotUseRx) {
this.doNotUseRx = doNotUseRx;
}
public void setUsePlay24WS(boolean usePlay24WS) {
@@ -360,6 +393,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen
this.performBeanValidation = performBeanValidation;
}
public void setUseGzipFeature(boolean useGzipFeature) {
this.useGzipFeature = useGzipFeature;
}
final private static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application\\/json(;.*)?");
final private static Pattern JSON_VENDOR_MIME_PATTERN = Pattern.compile("(?i)application\\/vnd.(.*)+json(;.*)?");

View File

@@ -21,9 +21,9 @@ import io.swagger.models.Swagger;
import io.swagger.models.properties.Property;
import io.swagger.util.Json;
public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen
{
public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen
{
public JavaJAXRSSpecServerCodegen()
{
super();
@@ -48,7 +48,6 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen
additionalProperties.put("title", title);
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "javax.xml.datatype.XMLGregorianCalendar"); // Map DateTime fields to Java standart class 'XMLGregorianCalendar'
importMapping.put("LocalDate", "org.joda.time.LocalDate");
@@ -60,7 +59,7 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen
break;
}
}
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY);
@@ -71,20 +70,20 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen
cliOptions.add(library);
}
@Override
public void processOpts()
{
super.processOpts();
supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen
writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml"));
writeOptional(outputFolder, new SupportingFile("RestApplication.mustache",
(sourceFolder + '/' + invokerPackage).replace(".", "/"), "RestApplication.java"));
}
}
@Override
public String getName()
@@ -119,7 +118,7 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen
opList.add(co);
co.baseName = basePath;
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
@@ -130,10 +129,10 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen
model.imports.remove("JsonValue");
model.imports.remove("JsonProperty");
}
@Override
public void preprocessSwagger(Swagger swagger) {
//copy input swagger to output folder
//copy input swagger to output folder
try {
String swaggerJson = Json.pretty(swagger);
FileUtils.writeStringToFile(new File(outputFolder + File.separator + "swagger.json"), swaggerJson);

View File

@@ -0,0 +1,248 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import java.io.File;
import java.util.List;
import java.util.Map;
public class JavaPlayFrameworkCodegen extends AbstractJavaCodegen implements BeanValidationFeatures {
public static final String TITLE = "title";
public static final String CONFIG_PACKAGE = "configPackage";
public static final String BASE_PACKAGE = "basePackage";
public static final String CONTROLLER_ONLY = "controllerOnly";
public static final String SINGLE_CONTENT_TYPES = "singleContentTypes";
public static final String RESPONSE_WRAPPER = "responseWrapper";
public static final String USE_TAGS = "useTags";
protected String title = "swagger-petstore";
protected String configPackage = "io.swagger.configuration";
protected String basePackage = "io.swagger";
protected boolean controllerOnly = false;
protected boolean singleContentTypes = false;
protected String responseWrapper = "";
protected boolean useTags = false;
protected boolean useBeanValidation = true;
public JavaPlayFrameworkCodegen() {
super();
outputFolder = "generated-code/javaPlayFramework";
apiTestTemplateFiles.clear();
embeddedTemplateDir = templateDir = "JavaPlayFramework";
apiPackage = "controllers";
modelPackage = "apimodels";
invokerPackage = "io.swagger.api";
artifactId = "swagger-java-playframework";
projectFolder = "";
sourceFolder = projectFolder + File.separator + "app";
projectTestFolder = projectFolder + File.separator + "test";
testFolder = projectTestFolder;
additionalProperties.put(CONFIG_PACKAGE, configPackage);
additionalProperties.put(BASE_PACKAGE, basePackage);
additionalProperties.put("jackson", "true");
cliOptions.add(new CliOption(TITLE, "server title name or client service name"));
cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code"));
cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code"));
cliOptions.add(CliOption.newBoolean(CONTROLLER_ONLY, "Whether to generate only API interface stubs without the server files."));
cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation."));
cliOptions.add(new CliOption(RESPONSE_WRAPPER, "wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)"));
cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames"));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
}
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
@Override
public String getName() {
return "java-play-framework";
}
@Override
public String getHelp() {
return "Generates a Java Play Framework Server application.";
}
@Override
public void processOpts() {
super.processOpts();
// clear model and api doc template as this codegen
// does not support auto-generated markdown doc at the moment
//TODO: add doc templates
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
if (additionalProperties.containsKey(TITLE)) {
this.setTitle((String) additionalProperties.get(TITLE));
}
if (additionalProperties.containsKey(CONFIG_PACKAGE)) {
this.setConfigPackage((String) additionalProperties.get(CONFIG_PACKAGE));
}
if (additionalProperties.containsKey(BASE_PACKAGE)) {
this.setBasePackage((String) additionalProperties.get(BASE_PACKAGE));
}
if (additionalProperties.containsKey(CONTROLLER_ONLY)) {
this.setControllerOnly(Boolean.valueOf(additionalProperties.get(CONTROLLER_ONLY).toString()));
}
if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) {
this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString()));
}
if (additionalProperties.containsKey(RESPONSE_WRAPPER)) {
this.setResponseWrapper((String) additionalProperties.get(RESPONSE_WRAPPER));
}
if (additionalProperties.containsKey(USE_TAGS)) {
this.setUseTags(Boolean.valueOf(additionalProperties.get(USE_TAGS).toString()));
}
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
}
if (useBeanValidation) {
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
}
//Root folder
supportingFiles.add(new SupportingFile("README.mustache", "", "README"));
supportingFiles.add(new SupportingFile("LICENSE.mustache", "", "LICENSE"));
supportingFiles.add(new SupportingFile("build.mustache", "", "build.sbt"));
//Project folder
supportingFiles.add(new SupportingFile("buildproperties.mustache", "project", "build.properties"));
supportingFiles.add(new SupportingFile("plugins.mustache", "project", "plugins.sbt"));
//Conf folder
supportingFiles.add(new SupportingFile("logback.mustache", "conf", "logback.xml"));
supportingFiles.add(new SupportingFile("application.mustache", "conf", "application.conf"));
supportingFiles.add(new SupportingFile("routes.mustache", "conf", "routes"));
//App/Utils folder
supportingFiles.add(new SupportingFile("swaggerUtils.mustache", "app/swagger", "SwaggerUtils.java"));
//App/Controllers
supportingFiles.add(new SupportingFile("apiDocController.mustache", "app/controllers", "ApiDocController.java"));
//We remove the default api.mustache that is used
apiTemplateFiles.remove("api.mustache");
apiTemplateFiles.put("newApiController.mustache", "Controller.java");
if (!this.controllerOnly) {
apiTemplateFiles.put("newApi.mustache", "ControllerImp.java");
}
additionalProperties.put("javaVersion", "1.8");
additionalProperties.put("jdk8", "true");
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "OffsetDateTime");
importMapping.put("LocalDate", "java.time.LocalDate");
importMapping.put("OffsetDateTime", "java.time.OffsetDateTime");
// Some well-known Spring or Spring-Cloud response wrappers
switch (this.responseWrapper) {
case "Future":
case "Callable":
case "CompletableFuture":
additionalProperties.put(RESPONSE_WRAPPER, "java.util.concurrent" + this.responseWrapper);
break;
default:
break;
}
}
public void setTitle(String title) {
this.title = title;
}
public void setConfigPackage(String configPackage) {
this.configPackage = configPackage;
}
public void setBasePackage(String configPackage) {
this.basePackage = configPackage;
}
public void setControllerOnly(boolean controllerOnly) { this.controllerOnly = controllerOnly; }
public void setSingleContentTypes(boolean singleContentTypes) {
this.singleContentTypes = singleContentTypes;
}
public void setResponseWrapper(String responseWrapper) { this.responseWrapper = responseWrapper; }
public void setUseTags(boolean useTags) {
this.useTags = useTags;
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
//This is to fix this bug in the swagger-play project: https://github.com/swagger-api/swagger-play/issues/131
//We need to explicitly add the model package name in front of the dataType because if we don't, the
//implicitParam is not valid and show error when loading the documentation
//This can be removed safely after the bug has been fixed
for (CodegenParameter param : operation.allParams) {
if (!param.isPathParam ) {
if (!param.isPrimitiveType && !param.isListContainer && !param.isMapContainer) {
param.dataTypeForImplicitParam = String.format("%s.%s", modelPackage, param.dataType);
} else {
param.dataTypeForImplicitParam = param.dataType;
}
}
}
if (operation.path.contains("{")) {
operation.path = operation.path.replace("{", ":").replace("}", "");
}
if (operation.returnType != null) {
if (operation.returnType.startsWith("List")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("List<".length(), end).trim();
operation.returnContainer = "List";
}
} else if (operation.returnType.startsWith("Map")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim();
operation.returnContainer = "Map";
}
} else if (operation.returnType.startsWith("Set")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Set<".length(), end).trim();
operation.returnContainer = "Set";
}
}
}
}
}
return objs;
}
public void setUseBeanValidation(boolean useBeanValidation) {
this.useBeanValidation = useBeanValidation;
}
}

View File

@@ -0,0 +1,231 @@
package io.swagger.codegen.languages;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.BooleanUtils;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.codegen.languages.features.JbossFeature;
import io.swagger.codegen.languages.features.SwaggerFeatures;
import io.swagger.models.Operation;
public class JavaResteasyEapServerCodegen extends AbstractJavaJAXRSServerCodegen
implements JbossFeature, BeanValidationFeatures, SwaggerFeatures {
protected boolean useBeanValidation = true;
protected boolean generateJbossDeploymentDescriptor = true;
protected boolean useSwaggerFeature = false;
public JavaResteasyEapServerCodegen() {
super();
artifactId = "swagger-jaxrs-resteasy-eap-server";
outputFolder = "generated-code/JavaJaxRS-Resteasy-eap";
apiTemplateFiles.put("apiServiceImpl.mustache", ".java");
apiTestTemplateFiles.clear(); // TODO: add test template
// clear model and api doc template as AbstractJavaJAXRSServerCodegen
// does not support auto-generated markdown doc at the moment
//TODO: add doc templates
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
dateLibrary = "legacy";// TODO: change to joda
embeddedTemplateDir = templateDir = "JavaJaxRS" + File.separator + "resteasy" + File.separator + "eap";
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
cliOptions.add(CliOption.newBoolean(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, "Generate Jboss Deployment Descriptor"));
cliOptions.add(CliOption.newBoolean(USE_SWAGGER_FEATURE, "Use dynamic Swagger generator"));
}
@Override
public String getName() {
return "jaxrs-resteasy-eap";
}
@Override
public String getHelp() {
return "Generates a Java JAXRS-Resteasy Server application.";
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)) {
boolean generateJbossDeploymentDescriptorProp = convertPropertyToBooleanAndWriteBack(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR);
this.setGenerateJbossDeploymentDescriptor(generateJbossDeploymentDescriptorProp);
}
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
}
if (useBeanValidation) {
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
}
if (additionalProperties.containsKey(USE_SWAGGER_FEATURE)) {
this.setUseSwaggerFeature(convertPropertyToBoolean(USE_SWAGGER_FEATURE));
}
if (useSwaggerFeature) {
writePropertyBack(USE_SWAGGER_FEATURE, useSwaggerFeature);
}
writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml"));
writeOptional(outputFolder, new SupportingFile("gradle.mustache", "", "build.gradle"));
writeOptional(outputFolder, new SupportingFile("settingsGradle.mustache", "", "settings.gradle"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));
writeOptional(outputFolder, new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml"));
supportingFiles.add(new SupportingFile("JacksonConfig.mustache", (projectFolder + File.separator + "java" + '/' + invokerPackage).replace(".", "/"), "JacksonConfig.java"));
if (generateJbossDeploymentDescriptor) {
writeOptional(outputFolder, new SupportingFile("jboss-web.mustache", ("src/main/webapp/WEB-INF"), "jboss-web.xml"));
}
writeOptional(outputFolder, new SupportingFile("RestApplication.mustache", (projectFolder + File.separator + "java" + '/' + invokerPackage).replace(".", "/"), "RestApplication.java"));
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
String basePath = resourcePath;
if (basePath.startsWith("/")) {
basePath = basePath.substring(1);
}
int pos = basePath.indexOf("/");
if (pos > 0) {
basePath = basePath.substring(0, pos);
}
if (basePath == "") {
basePath = "default";
} else {
if (co.path.startsWith("/" + basePath)) {
co.path = co.path.substring(("/" + basePath).length());
}
co.subresourceOperation = !co.path.isEmpty();
}
List<CodegenOperation> opList = operations.get(basePath);
if (opList == null) {
opList = new ArrayList<CodegenOperation>();
operations.put(basePath, opList);
}
opList.add(co);
co.baseName = basePath;
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
if (operation.hasConsumes == Boolean.TRUE) {
Map<String, String> firstType = operation.consumes.get(0);
if (firstType != null) {
if ("multipart/form-data".equals(firstType.get("mediaType"))) {
operation.isMultipart = Boolean.TRUE;
}
}
}
List<CodegenResponse> responses = operation.responses;
if (responses != null) {
for (CodegenResponse resp : responses) {
if ("0".equals(resp.code)) {
resp.code = "200";
}
}
}
if (operation.returnType == null) {
operation.returnType = "Void";
} else if (operation.returnType.startsWith("List")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("List<".length(), end).trim();
operation.returnContainer = "List";
}
} else if (operation.returnType.startsWith("Map")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim();
operation.returnContainer = "Map";
}
} else if (operation.returnType.startsWith("Set")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Set<".length(), end).trim();
operation.returnContainer = "Set";
}
}
}
}
return objs;
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
// Add imports for Jackson
if (!BooleanUtils.toBoolean(model.isEnum)) {
model.imports.add("JsonProperty");
if (BooleanUtils.toBoolean(model.hasEnums)) {
model.imports.add("JsonValue");
}
}
}
@Override
public Map<String, Object> postProcessModelsEnum(Map<String, Object> objs) {
objs = super.postProcessModelsEnum(objs);
// Add imports for Jackson
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
cm.imports.add(importMapping.get("JsonValue"));
Map<String, String> item = new HashMap<String, String>();
item.put("import", importMapping.get("JsonValue"));
imports.add(item);
}
}
return objs;
}
public void setUseBeanValidation(boolean useBeanValidation) {
this.useBeanValidation = useBeanValidation;
}
public void setGenerateJbossDeploymentDescriptor(boolean generateJbossDeploymentDescriptor) {
this.generateJbossDeploymentDescriptor = generateJbossDeploymentDescriptor;
}
public void setUseSwaggerFeature(boolean useSwaggerFeature) {
this.useSwaggerFeature = useSwaggerFeature;
}
}

View File

@@ -202,7 +202,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString()));
}
if (additionalProperties.containsKey(PROJECT_NAME)) {
setProjectName(((String) additionalProperties.get(PROJECT_NAME)));
}
@@ -228,19 +227,19 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE));
}
if (additionalProperties.containsKey(USE_PROMISES)) {
setUsePromises(Boolean.parseBoolean((String)additionalProperties.get(USE_PROMISES)));
setUsePromises(convertPropertyToBooleanAndWriteBack(USE_PROMISES));
}
if (additionalProperties.containsKey(USE_INHERITANCE)) {
setUseInheritance(Boolean.parseBoolean((String)additionalProperties.get(USE_INHERITANCE)));
setUseInheritance(convertPropertyToBooleanAndWriteBack(USE_INHERITANCE));
} else {
supportsInheritance = true;
supportsMixins = true;
}
if (additionalProperties.containsKey(EMIT_MODEL_METHODS)) {
setEmitModelMethods(Boolean.parseBoolean((String)additionalProperties.get(EMIT_MODEL_METHODS)));
setEmitModelMethods(convertPropertyToBooleanAndWriteBack(EMIT_MODEL_METHODS));
}
if (additionalProperties.containsKey(EMIT_JS_DOC)) {
setEmitJSDoc(Boolean.parseBoolean((String)additionalProperties.get(EMIT_JS_DOC)));
setEmitJSDoc(convertPropertyToBooleanAndWriteBack(EMIT_JS_DOC));
}
}
@@ -710,7 +709,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
CodegenParameter lastRequired = null;
CodegenParameter lastOptional = null;
for (CodegenParameter p : op.allParams) {
if (p.required != null && p.required) {
if (p.required) {
lastRequired = p;
} else {
lastOptional = p;
@@ -778,12 +777,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
+ (StringUtils.isEmpty(modelPackage) ? "" : (modelPackage + "/")) + dataType;
}
/*
private String getJSDocTypeWithBraces(CodegenModel cm, CodegenProperty cp) {
return "{" + getJSDocType(cm, cp) + "}";
}
*/
private String getJSDocType(CodegenModel cm, CodegenProperty cp) {
if (Boolean.TRUE.equals(cp.isContainer)) {
if (cp.containerType.equals("array"))
@@ -805,12 +798,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return cp.isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.datatype : cp.baseType);
}
/*
private String getJSDocTypeWithBraces(CodegenParameter cp) {
return "{" + getJSDocType(cp) + "}";
}
*/
private String getJSDocType(CodegenParameter cp) {
String dataType = trimBrackets(cp.dataType);
if (isModelledType(cp))
@@ -828,13 +815,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return cp.isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.dataType : cp.baseType);
}
/*
private String getJSDocTypeWithBraces(CodegenOperation co) {
String jsDocType = getJSDocType(co);
return jsDocType == null ? null : "{" + jsDocType + "}";
}
*/
private String getJSDocType(CodegenOperation co) {
String returnType = trimBrackets(co.returnType);
if (returnType != null) {
@@ -866,7 +846,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
List<String> argList = new ArrayList<String>();
boolean hasOptionalParams = false;
for (CodegenParameter p : operation.allParams) {
if (p.required != null && p.required) {
if (p.required) {
argList.add(p.paramName);
} else {
hasOptionalParams = true;
@@ -950,15 +930,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return !defaultIncludes.contains(type)
&& !languageSpecificPrimitives.contains(type);
}
/*
@Override
public String findCommonPrefixOfVars(List<String> vars) {
String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()]));
// exclude trailing characters that should be part of a valid variable
// e.g. ["status-on", "status-off"] => "status-" (not "status-o")
return prefix.replaceAll("[a-zA-Z0-9]+\\z", "");
}
*/
private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
// This generator uses inline classes to define enums, which breaks when

View File

@@ -17,6 +17,7 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
@@ -519,7 +520,10 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
return "'" + dp.getDefault() + "'";
if (Pattern.compile("\r\n|\r|\n").matcher(dp.getDefault()).find())
return "'''" + dp.getDefault() + "'''";
else
return "'" + dp.getDefault() + "'";
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;

View File

@@ -272,7 +272,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
CodegenParameter lastRequired = null;
CodegenParameter lastOptional = null;
for (CodegenParameter p : op.allParams) {
if (p.required != null && p.required) {
if (p.required) {
lastRequired = p;
} else {
lastOptional = p;

View File

@@ -3,6 +3,7 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
@@ -13,6 +14,10 @@ import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage;
@@ -213,4 +218,28 @@ public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
String path = new String(op.path);
String[] items = path.split("/", -1);
String opsPath = "";
int pathParamIndex = 0;
for (int i = 0; i < items.length; ++i) {
if (items[i].matches("^\\{(.*)\\}$")) { // wrap in {}
// camelize path variable
items[i] = "{" + camelize(items[i].substring(1, items[i].length()-1), true) + "}";
}
}
op.path = StringUtils.join(items, "/");
}
return objs;
}
}

View File

@@ -23,6 +23,7 @@ public class SpringCodegen extends AbstractJavaCodegen implements BeanValidation
public static final String USE_TAGS = "useTags";
public static final String SPRING_MVC_LIBRARY = "spring-mvc";
public static final String SPRING_CLOUD_LIBRARY = "spring-cloud";
public static final String IMPLICIT_HEADERS = "implicitHeaders";
protected String title = "swagger-petstore";
protected String configPackage = "io.swagger.configuration";
@@ -34,7 +35,8 @@ public class SpringCodegen extends AbstractJavaCodegen implements BeanValidation
protected boolean async = false;
protected String responseWrapper = "";
protected boolean useTags = false;
protected boolean useBeanValidation = true;
protected boolean useBeanValidation = true;
protected boolean implicitHeaders = false;
public SpringCodegen() {
super();
@@ -63,6 +65,7 @@ public class SpringCodegen extends AbstractJavaCodegen implements BeanValidation
cliOptions.add(new CliOption(RESPONSE_WRAPPER, "wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)"));
cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames"));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
cliOptions.add(CliOption.newBoolean(IMPLICIT_HEADERS, "Use of @ApiImplicitParams for headers."));
supportedLibraries.put(DEFAULT_LIBRARY, "Spring-boot Server application using the SpringFox integration.");
supportedLibraries.put(SPRING_MVC_LIBRARY, "Spring-MVC Server application using the SpringFox integration.");
@@ -162,6 +165,11 @@ public class SpringCodegen extends AbstractJavaCodegen implements BeanValidation
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
}
if (additionalProperties.containsKey(IMPLICIT_HEADERS)) {
this.setImplicitHeaders(Boolean.valueOf(additionalProperties.get(IMPLICIT_HEADERS).toString()));
}
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
@@ -410,12 +418,36 @@ public class SpringCodegen extends AbstractJavaCodegen implements BeanValidation
operation.returnContainer = "Set";
}
}
if(implicitHeaders){
removeHeadersFromAllParams(operation.allParams);
}
}
}
return objs;
}
/**
* This method removes header parameters from the list of parameters and also
* corrects last allParams hasMore state.
* @param allParams list of all parameters
*/
private void removeHeadersFromAllParams(List<CodegenParameter> allParams) {
if(allParams.isEmpty()){
return;
}
final ArrayList<CodegenParameter> copy = new ArrayList<>(allParams);
allParams.clear();
for(CodegenParameter p : copy){
if(!p.isHeaderParam){
allParams.add(p);
}
}
allParams.get(allParams.size()-1).hasMore =false;
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
if(library.equals(SPRING_CLOUD_LIBRARY)) {
@@ -468,6 +500,10 @@ public class SpringCodegen extends AbstractJavaCodegen implements BeanValidation
this.useTags = useTags;
}
public void setImplicitHeaders(boolean implicitHeaders) {
this.implicitHeaders = implicitHeaders;
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);

View File

@@ -1,15 +1,24 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Info;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.Info;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -113,6 +122,11 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
op.httpMethod = op.httpMethod.toLowerCase();
for (CodegenResponse response : op.responses){
if ("0".equals(response.code)){
response.code = "default";
}
}
}
return objs;
}
@@ -158,7 +172,7 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi
CodegenParameter lastRequired = null;
CodegenParameter lastOptional = null;
for (CodegenParameter p : op.allParams) {
if (p.required != null && p.required) {
if (p.required) {
lastRequired = p;
} else {
lastOptional = p;

View File

@@ -4,6 +4,7 @@ import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
@@ -41,7 +42,7 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC));
additionalProperties.put("appName", "Swagger Sample");
additionalProperties.put("appDescription", "A sample swagger server");
additionalProperties.put("infoUrl", "https://helloreverb.com");
@@ -96,12 +97,17 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
return super.getTypeDeclaration(p);
}
@Override
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
op.httpMethod = op.httpMethod.toLowerCase();
for (CodegenResponse response : op.responses) {
if ("0".equals(response.code)) {
response.code = "default";
}
}
}
return objs;
}

View File

@@ -52,4 +52,16 @@ public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig {
LOGGER.error(e.getMessage(), e);
}
}
@Override
public String escapeQuotationMark(String input) {
// just return the original string
return input;
}
@Override
public String escapeUnsafeCharacters(String input) {
// just return the original string
return input;
}
}

View File

@@ -61,4 +61,17 @@ public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfi
LOGGER.error(e.getMessage(), e);
}
}
@Override
public String escapeQuotationMark(String input) {
// just return the original string
return input;
}
@Override
public String escapeUnsafeCharacters(String input) {
// just return the original string
return input;
}
}

View File

@@ -184,7 +184,7 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
// Setup unwrapRequired option, which makes all the properties with "required" non-optional
if (additionalProperties.containsKey(UNWRAP_REQUIRED)) {
setUnwrapRequired(Boolean.parseBoolean(String.valueOf(additionalProperties.get(UNWRAP_REQUIRED))));
setUnwrapRequired(convertPropertyToBooleanAndWriteBack(UNWRAP_REQUIRED));
}
additionalProperties.put(UNWRAP_REQUIRED, unwrapRequired);
@@ -207,9 +207,8 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
// Setup swiftUseApiNamespace option, which makes all the API classes inner-class of {{projectName}}API
if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) {
swiftUseApiNamespace = Boolean.parseBoolean(String.valueOf(additionalProperties.get(SWIFT_USE_API_NAMESPACE)));
setSwiftUseApiNamespace(convertPropertyToBooleanAndWriteBack(SWIFT_USE_API_NAMESPACE));
}
additionalProperties.put(SWIFT_USE_API_NAMESPACE, swiftUseApiNamespace);
if (!additionalProperties.containsKey(POD_AUTHORS)) {
additionalProperties.put(POD_AUTHORS, DEFAULT_POD_AUTHORS);
@@ -496,6 +495,10 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
this.responseAs = responseAs;
}
public void setSwiftUseApiNamespace(boolean swiftUseApiNamespace) {
this.swiftUseApiNamespace = swiftUseApiNamespace;
}
@Override
public String toEnumValue(String value, String datatype) {
return String.valueOf(value);

View File

@@ -184,9 +184,8 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
// Setup unwrapRequired option, which makes all the properties with "required" non-optional
if (additionalProperties.containsKey(UNWRAP_REQUIRED)) {
setUnwrapRequired(Boolean.parseBoolean(String.valueOf(additionalProperties.get(UNWRAP_REQUIRED))));
setUnwrapRequired(convertPropertyToBooleanAndWriteBack(UNWRAP_REQUIRED));
}
additionalProperties.put(UNWRAP_REQUIRED, unwrapRequired);
// Setup unwrapRequired option, which makes all the properties with "required" non-optional
if (additionalProperties.containsKey(RESPONSE_AS)) {
@@ -207,9 +206,8 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
// Setup swiftUseApiNamespace option, which makes all the API classes inner-class of {{projectName}}API
if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) {
swiftUseApiNamespace = Boolean.parseBoolean(String.valueOf(additionalProperties.get(SWIFT_USE_API_NAMESPACE)));
setSwiftUseApiNamespace(convertPropertyToBooleanAndWriteBack(SWIFT_USE_API_NAMESPACE));
}
additionalProperties.put(SWIFT_USE_API_NAMESPACE, swiftUseApiNamespace);
if (!additionalProperties.containsKey(POD_AUTHORS)) {
additionalProperties.put(POD_AUTHORS, DEFAULT_POD_AUTHORS);
@@ -531,6 +529,10 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
this.responseAs = responseAs;
}
public void setSwiftUseApiNamespace(boolean swiftUseApiNamespace) {
this.swiftUseApiNamespace = swiftUseApiNamespace;
}
@Override
public String toEnumValue(String value, String datatype) {
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {

View File

@@ -4,7 +4,7 @@ public interface BeanValidationFeatures {
// Language supports generating BeanValidation-Annotations
public static final String USE_BEANVALIDATION = "useBeanValidation";
public void setUseBeanValidation(boolean useBeanValidation);
}

View File

@@ -5,8 +5,7 @@ package io.swagger.codegen.languages.features;
*
*/
public interface CXFServerFeatures
extends CXFFeatures, SwaggerFeatures, SpringFeatures, JbossFeature, BeanValidationExtendedFeatures,
SwaggerUIFeatures
extends CXFFeatures, SwaggerFeatures, SpringFeatures, JbossFeature, BeanValidationExtendedFeatures, SwaggerUIFeatures
{
public static final String USE_WADL_FEATURE = "useWadlFeature";

View File

@@ -4,7 +4,7 @@ public interface PerformBeanValidationFeatures {
// Language supports performing BeanValidation
public static final String PERFORM_BEANVALIDATION = "performBeanValidation";
public void setPerformBeanValidation(boolean performBeanValidation);
}

View File

@@ -14,5 +14,5 @@ public interface SpringFeatures extends BeanValidationFeatures {
public void setUseSpringAnnotationConfig(boolean useSpringAnnotationConfig);
}

View File

@@ -1,6 +1,6 @@
package io.swagger.codegen.languages.features;
public interface SwaggerFeatures extends CXFFeatures {
public interface SwaggerFeatures {
public static final String USE_SWAGGER_FEATURE = "useSwaggerFeature";