Latest from master - merge conflict resolution

This commit is contained in:
Gayathri
2017-04-12 09:03:54 -05:00
3494 changed files with 154303 additions and 26738 deletions

View File

@@ -13,6 +13,7 @@ import java.io.Writer;
import java.util.Scanner;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -56,13 +57,17 @@ public abstract class AbstractGenerator {
if (is == null) {
is = new FileInputStream(new File(name)); // May throw but never return a null value
}
return new InputStreamReader(is);
return new InputStreamReader(is, "UTF-8");
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
throw new RuntimeException("can't load template " + name);
}
private String buildLibraryFilePath(String dir, String library, String file) {
return dir + File.separator + "libraries" + File.separator + library + File.separator + file;
}
/**
* Get the template file path with template dir prepended, and use the
* library template if exists.
@@ -72,23 +77,38 @@ public abstract class AbstractGenerator {
* @return String Full template file path
*/
public String getFullTemplateFile(CodegenConfig config, String templateFile) {
String template = config.templateDir() + File.separator + templateFile;
//1st the code will check if there's a <template folder>/libraries/<library> folder containing the file
//2nd it will check for the file in the specified <template folder> folder
//3rd it will check if there's an <embedded template>/libraries/<library> folder containing the file
//4th and last it will assume the file is in <embedded template> folder.
//check the supplied template library folder for the file
final String library = config.getLibrary();
if (StringUtils.isNotEmpty(library)) {
//look for the file in the library subfolder of the supplied template
final String libTemplateFile = buildLibraryFilePath(config.templateDir(), library, templateFile);
if (new File(libTemplateFile).exists()) {
return libTemplateFile;
}
}
//check the supplied template main folder for the file
final String template = config.templateDir() + File.separator + templateFile;
if (new File(template).exists()) {
return template;
} else {
String library = config.getLibrary();
if (library != null && !"".equals(library)) {
String libTemplateFile = config.embeddedTemplateDir() + File.separator +
"libraries" + File.separator + library + File.separator +
templateFile;
if (embeddedTemplateExists(libTemplateFile)) {
// Fall back to the template file embedded/packaged in the JAR file...
return libTemplateFile;
}
}
// Fall back to the template file embedded/packaged in the JAR file...
return config.embeddedTemplateDir() + File.separator + templateFile;
}
//try the embedded template library folder next
if (StringUtils.isNotEmpty(library)) {
final String embeddedLibTemplateFile = buildLibraryFilePath(config.embeddedTemplateDir(), library, templateFile);
if (embeddedTemplateExists(embeddedLibTemplateFile)) {
// Fall back to the template file embedded/packaged in the JAR file library folder...
return embeddedLibTemplateFile;
}
}
// Fall back to the template file embedded/packaged in the JAR file...
return config.embeddedTemplateDir() + File.separator + templateFile;
}
public String readResourceContents(String resourceFilePath) {

View File

@@ -25,9 +25,9 @@ import io.swagger.parser.SwaggerParser;
*/
@Deprecated
public class Codegen extends DefaultGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(Codegen.class);
static Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>();
static String configString;
static String debugInfoOptions = "\nThe following additional debug options are available for all codegen targets:" +

View File

@@ -14,7 +14,7 @@ import com.samskivert.mustache.Mustache.Compiler;
public interface CodegenConfig {
CodegenType getTag();
String getName();
String getHelp();
@@ -118,6 +118,8 @@ public interface CodegenConfig {
Map<String, String> modelDocTemplateFiles();
Set<String> languageSpecificPrimitives();
Map<String, String> reservedWordsMappings();
void preprocessSwagger(Swagger swagger);
@@ -197,4 +199,8 @@ public interface CodegenConfig {
String getHttpUserAgent();
String getCommonTemplateDir();
void setIgnoreFilePathOverride(String ignoreFileOverride);
String getIgnoreFilePathOverride();
}

View File

@@ -12,10 +12,21 @@ public class CodegenConstants {
public static final String TEMPLATE_DIR = "templateDir";
public static final String ALLOW_UNICODE_IDENTIFIERS = "allowUnicodeIdentifiers";
public static final String ALLOW_UNICODE_IDENTIFIERS_DESC = "boolean, toggles whether unicode identifiers are allowed in names or not, default is false";
public static final String INVOKER_PACKAGE = "invokerPackage";
public static final String INVOKER_PACKAGE_DESC = "root package for generated code";
public static final String PHP_INVOKER_PACKAGE = "phpInvokerPackage";
public static final String PHP_INVOKER_PACKAGE_DESC = "root package for generated php code";
public static final String PERL_MODULE_NAME = "perlModuleName";
public static final String PERL_MODULE_NAME_DESC = "root module name for generated perl code";
public static final String PYTHON_PACKAGE_NAME = "pythonPackageName";
public static final String PYTHON_PACKAGE_NAME_DESC = "package name for generated python code";
public static final String GROUP_ID = "groupId";
public static final String GROUP_ID_DESC = "groupId in generated pom.xml";
@@ -25,12 +36,45 @@ public class CodegenConstants {
public static final String ARTIFACT_VERSION = "artifactVersion";
public static final String ARTIFACT_VERSION_DESC = "artifact version in generated pom.xml";
public static final String ARTIFACT_URL = "artifactUrl";
public static final String ARTIFACT_URL_DESC = "artifact URL in generated pom.xml";
public static final String ARTIFACT_DESCRIPTION = "artifactDescription";
public static final String ARTIFACT_DESCRIPTION_DESC = "artifact description in generated pom.xml";
public static final String SCM_CONNECTION = "scmConnection";
public static final String SCM_CONNECTION_DESC = "SCM connection in generated pom.xml";
public static final String SCM_DEVELOPER_CONNECTION = "scmDeveloperConnection";
public static final String SCM_DEVELOPER_CONNECTION_DESC = "SCM developer connection in generated pom.xml";
public static final String SCM_URL = "scmUrl";
public static final String SCM_URL_DESC = "SCM URL in generated pom.xml";
public static final String DEVELOPER_NAME = "developerName";
public static final String DEVELOPER_NAME_DESC = "developer name in generated pom.xml";
public static final String DEVELOPER_EMAIL = "developerEmail";
public static final String DEVELOPER_EMAIL_DESC = "developer email in generated pom.xml";
public static final String DEVELOPER_ORGANIZATION = "developerOrganization";
public static final String DEVELOPER_ORGANIZATION_DESC = "developer organization in generated pom.xml";
public static final String DEVELOPER_ORGANIZATION_URL = "developerOrganizationUrl";
public static final String DEVELOPER_ORGANIZATION_URL_DESC = "developer organization URL in generated pom.xml";
public static final String LICENSE_NAME = "licenseName";
public static final String LICENSE_NAME_DESC = "The name of the license";
public static final String LICENSE_URL = "licenseUrl";
public static final String LICENSE_URL_DESC = "The URL of the license";
public static final String SOURCE_FOLDER = "sourceFolder";
public static final String SOURCE_FOLDER_DESC = "source folder for generated code";
public static final String IMPL_FOLDER = "implFolder";
public static final String IMPL_FOLDER_DESC = "folder for generated implementation code";
public static final String LOCAL_VARIABLE_PREFIX = "localVariablePrefix";
public static final String LOCAL_VARIABLE_PREFIX_DESC = "prefix for generated code members and local variables";
@@ -48,13 +92,13 @@ public class CodegenConstants {
public static final String USE_DATETIME_OFFSET = "useDateTimeOffset";
public static final String USE_DATETIME_OFFSET_DESC = "Use DateTimeOffset to model date-time properties";
public static final String ENSURE_UNIQUE_PARAMS = "ensureUniqueParams";
public static final String ENSURE_UNIQUE_PARAMS_DESC = "Whether to ensure parameter names are unique in an operation (rename parameters that are not).";
public static final String PACKAGE_NAME = "packageName";
public static final String PACKAGE_VERSION = "packageVersion";
public static final String PACKAGE_TITLE = "packageTitle";
public static final String PACKAGE_TITLE_DESC = "Specifies an AssemblyTitle for the .NET Framework global assembly attributes stored in the AssemblyInfo file.";
public static final String PACKAGE_PRODUCTNAME = "packageProductName";
@@ -65,7 +109,7 @@ public class CodegenConstants {
public static final String PACKAGE_COMPANY_DESC = "Specifies an AssemblyCompany for the .NET Framework global assembly attributes stored in the AssemblyInfo file.";
public static final String PACKAGE_COPYRIGHT = "packageCopyright";
public static final String PACKAGE_COPYRIGHT_DESC = "Specifies an AssemblyCopyright for the .NET Framework global assembly attributes stored in the AssemblyInfo file.";
public static final String POD_VERSION = "podVersion";
public static final String OPTIONAL_METHOD_ARGUMENT = "optionalMethodArgument";
@@ -77,15 +121,18 @@ public class CodegenConstants {
public static final String USE_COLLECTION = "useCollection";
public static final String USE_COLLECTION_DESC = "Deserialize array types to Collection<T> instead of List<T>.";
public static final String INTERFACE_PREFIX = "interfacePrefix";
public static final String INTERFACE_PREFIX_DESC = "Prefix interfaces with a community standard or widely accepted prefix.";
public static final String RETURN_ICOLLECTION = "returnICollection";
public static final String RETURN_ICOLLECTION_DESC = "Return ICollection<T> instead of the concrete type.";
public static final String OPTIONAL_PROJECT_FILE = "optionalProjectFile";
public static final String OPTIONAL_PROJECT_FILE_DESC = "Generate {PackageName}.csproj.";
public static final String OPTIONAL_PROJECT_GUID = "packageGuid";
public static final String OPTIONAL_PROJECT_GUID_DESC = "The GUID that will be associated with the C# project";
public static final String MODEL_PROPERTY_NAMING = "modelPropertyNaming";
public static final String MODEL_PROPERTY_NAMING_DESC = "Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name";
@@ -128,9 +175,15 @@ public class CodegenConstants {
public static final String GENERATE_MODEL_TESTS_DESC = "Specifies that model tests are to be generated.";
public static final String HIDE_GENERATION_TIMESTAMP = "hideGenerationTimestamp";
public static final String HIDE_GENERATION_TIMESTAMP_DESC = "Hides the generation timestamp.";
public static final String HIDE_GENERATION_TIMESTAMP_DESC = "Hides the generation timestamp when files are generated.";
public static final String GENERATE_PROPERTY_CHANGED = "generatePropertyChanged";
public static final String GENERATE_PROPERTY_CHANGED_DESC = "Specifies that models support raising property changed events.";
public static final String NON_PUBLIC_API = "nonPublicApi";
public static final String NON_PUBLIC_API_DESC = "Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.";
public static final String IGNORE_FILE_OVERRIDE = "ignoreFileOverride";
public static final String IGNORE_FILE_OVERRIDE_DESC = "Specifies an override location for the .swagger-codegen-ignore file. Most useful on initial generation.";
}

View File

@@ -39,8 +39,8 @@ public class CodegenModel {
public Set<String> allMandatory;
public Set<String> imports = new TreeSet<String>();
public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, isArrayModel, hasChildren;
public Boolean hasOnlyReadOnly = true; // true if all properties are read-only
public boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, isArrayModel, hasChildren;
public boolean hasOnlyReadOnly = true; // true if all properties are read-only
public ExternalDocs externalDocs;
public Map<String, Object> vendorExtensions;
@@ -115,15 +115,15 @@ public class CodegenModel {
return false;
if (imports != null ? !imports.equals(that.imports) : that.imports != null)
return false;
if (hasVars != null ? !hasVars.equals(that.hasVars) : that.hasVars != null)
if (hasVars != that.hasVars)
return false;
if (emptyVars != null ? !emptyVars.equals(that.emptyVars) : that.emptyVars != null)
if (emptyVars != that.emptyVars)
return false;
if (hasMoreModels != null ? !hasMoreModels.equals(that.hasMoreModels) : that.hasMoreModels != null)
if (hasMoreModels != that.hasMoreModels)
return false;
if (hasEnums != null ? !hasEnums.equals(that.hasEnums) : that.hasEnums != null)
if (hasEnums != that.hasEnums)
return false;
if (isEnum != null ? !isEnum.equals(that.isEnum) : that.isEnum != null)
if (isEnum != that.isEnum)
return false;
if (externalDocs != null ? !externalDocs.equals(that.externalDocs) : that.externalDocs != null)
return false;
@@ -163,11 +163,11 @@ public class CodegenModel {
result = 31 * result + (mandatory != null ? mandatory.hashCode() : 0);
result = 31 * result + (allMandatory != null ? allMandatory.hashCode() : 0);
result = 31 * result + (imports != null ? imports.hashCode() : 0);
result = 31 * result + (hasVars != null ? hasVars.hashCode() : 0);
result = 31 * result + (emptyVars != null ? emptyVars.hashCode() : 0);
result = 31 * result + (hasMoreModels != null ? hasMoreModels.hashCode() : 0);
result = 31 * result + (hasEnums != null ? hasEnums.hashCode() : 0);
result = 31 * result + (isEnum != null ? isEnum.hashCode() : 0);
result = 31 * result + (hasVars ? 13:31);
result = 31 * result + (emptyVars ? 13:31);
result = 31 * result + (hasMoreModels ? 13:31);
result = 31 * result + (hasEnums ? 13:31);
result = 31 * result + (isEnum ? 13:31);
result = 31 * result + (externalDocs != null ? externalDocs.hashCode() : 0);
result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0);
result = 31 * result + Objects.hash(hasOnlyReadOnly);

View File

@@ -11,10 +11,10 @@ import java.util.Arrays;
public class CodegenOperation {
public final List<CodegenProperty> responseHeaders = new ArrayList<CodegenProperty>();
public Boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams,
public boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams,
returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer,
isListContainer, isMultipart, hasMore = Boolean.TRUE,
isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE,
isListContainer, isMultipart, hasMore = true,
isResponseBinary = false, isResponseFile = false, hasReference = false,
isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy,
isRestful;
public String path, operationId, returnType, httpMethod, returnBaseType,
@@ -36,6 +36,7 @@ public class CodegenOperation {
public Map<String, Object> vendorExtensions;
public String nickname; // legacy support
public String operationIdLowerCase; // for mardown documentation
public String operationIdCamelCase; // for class names
/**
* Check if there's at least one parameter
@@ -189,33 +190,35 @@ public class CodegenOperation {
if (responseHeaders != null ? !responseHeaders.equals(that.responseHeaders) : that.responseHeaders != null)
return false;
if (hasAuthMethods != null ? !hasAuthMethods.equals(that.hasAuthMethods) : that.hasAuthMethods != null)
if (hasAuthMethods != that.hasAuthMethods)
return false;
if (hasConsumes != null ? !hasConsumes.equals(that.hasConsumes) : that.hasConsumes != null)
if (hasConsumes != that.hasConsumes)
return false;
if (hasProduces != null ? !hasProduces.equals(that.hasProduces) : that.hasProduces != null)
if (hasProduces != that.hasProduces)
return false;
if (hasParams != null ? !hasParams.equals(that.hasParams) : that.hasParams != null)
if (hasParams != that.hasParams)
return false;
if (hasOptionalParams != null ? !hasOptionalParams.equals(that.hasOptionalParams) : that.hasOptionalParams != null)
if (hasOptionalParams != that.hasOptionalParams)
return false;
if (returnTypeIsPrimitive != null ? !returnTypeIsPrimitive.equals(that.returnTypeIsPrimitive) : that.returnTypeIsPrimitive != null)
if (returnTypeIsPrimitive != that.returnTypeIsPrimitive)
return false;
if (returnSimpleType != null ? !returnSimpleType.equals(that.returnSimpleType) : that.returnSimpleType != null)
if (returnSimpleType != that.returnSimpleType)
return false;
if (subresourceOperation != null ? !subresourceOperation.equals(that.subresourceOperation) : that.subresourceOperation != null)
if (subresourceOperation != that.subresourceOperation)
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 (isMultipart != null ? !isMultipart.equals(that.isMultipart) : that.isMultipart != null)
if (isMultipart != that.isMultipart)
return false;
if (hasMore != null ? !hasMore.equals(that.hasMore) : that.hasMore != null)
if (hasMore != that.hasMore)
return false;
if (isResponseBinary != null ? !isResponseBinary.equals(that.isResponseBinary) : that.isResponseBinary != null)
if (isResponseBinary != that.isResponseBinary)
return false;
if (hasReference != null ? !hasReference.equals(that.hasReference) : that.hasReference != null)
if (hasReference != that.hasReference)
return false;
if (isResponseFile != that.isResponseFile)
return false;
if (path != null ? !path.equals(that.path) : that.path != null)
return false;
@@ -277,27 +280,30 @@ public class CodegenOperation {
return false;
if ( prioritizedContentTypes != null ? !prioritizedContentTypes.equals(that.prioritizedContentTypes) : that.prioritizedContentTypes != null )
return false;
return operationIdLowerCase != null ? operationIdLowerCase.equals(that.operationIdLowerCase) : that.operationIdLowerCase == null;
if ( operationIdLowerCase != null ? !operationIdLowerCase.equals(that.operationIdLowerCase) : that.operationIdLowerCase != null )
return false;
return operationIdCamelCase != null ? operationIdCamelCase.equals(that.operationIdCamelCase) : that.operationIdCamelCase == null;
}
@Override
public int hashCode() {
int result = responseHeaders.hashCode();
result = 31 * result + (hasAuthMethods != null ? hasAuthMethods.hashCode() : 0);
result = 31 * result + (hasConsumes != null ? hasConsumes.hashCode() : 0);
result = 31 * result + (hasProduces != null ? hasProduces.hashCode() : 0);
result = 31 * result + (hasParams != null ? hasParams.hashCode() : 0);
result = 31 * result + (hasOptionalParams != null ? hasOptionalParams.hashCode() : 0);
result = 31 * result + (returnTypeIsPrimitive != null ? returnTypeIsPrimitive.hashCode() : 0);
result = 31 * result + (returnSimpleType != null ? returnSimpleType.hashCode() : 0);
result = 31 * result + (subresourceOperation != null ? subresourceOperation.hashCode() : 0);
result = 31 * result + (isMapContainer != null ? isMapContainer.hashCode() : 0);
result = 31 * result + (isListContainer != null ? isListContainer.hashCode() : 0);
result = 31 * result + (isMultipart != null ? isMultipart.hashCode() : 0);
result = 31 * result + (hasMore != null ? hasMore.hashCode() : 0);
result = 31 * result + (isResponseBinary != null ? isResponseBinary.hashCode() : 0);
result = 31 * result + (hasReference != null ? hasReference.hashCode() : 0);
result = 31 * result + (hasAuthMethods ? 13:31);
result = 31 * result + (hasConsumes ? 13:31);
result = 31 * result + (hasProduces ? 13:31);
result = 31 * result + (hasParams ? 13:31);
result = 31 * result + (hasOptionalParams ? 13:31);
result = 31 * result + (returnTypeIsPrimitive ? 13:31);
result = 31 * result + (returnSimpleType ? 13:31);
result = 31 * result + (subresourceOperation ? 13:31);
result = 31 * result + (isMapContainer ? 13:31);
result = 31 * result + (isListContainer ? 13:31);
result = 31 * result + (isMultipart ? 13:31);
result = 31 * result + (hasMore ? 13:31);
result = 31 * result + (isResponseBinary ? 13:31);
result = 31 * result + (isResponseFile ? 13:31);
result = 31 * result + (hasReference ? 13:31);
result = 31 * result + (path != null ? path.hashCode() : 0);
result = 31 * result + (operationId != null ? operationId.hashCode() : 0);
result = 31 * result + (returnType != null ? returnType.hashCode() : 0);
@@ -329,6 +335,7 @@ public class CodegenOperation {
result = 31 * result + (nickname != null ? nickname.hashCode() : 0);
result = 31 * result + (prioritizedContentTypes != null ? prioritizedContentTypes.hashCode() : 0);
result = 31 * result + (operationIdLowerCase != null ? operationIdLowerCase.hashCode() : 0);
result = 31 * result + (operationIdCamelCase != null ? operationIdCamelCase.hashCode() : 0);
return result;
}
}

View File

@@ -6,72 +6,74 @@ 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;
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.
*/
public Number maximum;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor17
*/
public Boolean exclusiveMaximum;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor21
*/
public Number minimum;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor21
*/
public Boolean exclusiveMinimum;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor26
*/
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor17.
*/
public String maximum;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor17
*/
public boolean exclusiveMaximum;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor21
*/
public String minimum;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor21
*/
public boolean exclusiveMinimum;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor26
*/
public Integer maxLength;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor29
*/
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor29
*/
public Integer minLength;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor33
*/
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor33
*/
public String pattern;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor42
*/
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor42
*/
public Integer maxItems;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor45
*/
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor45
*/
public Integer minItems;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor49
*/
public Boolean uniqueItems;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor14
*/
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor49
*/
public boolean uniqueItems;
/**
* See http://json-schema.org/latest/json-schema-validation.html#anchor14
*/
public Number multipleOf;
public CodegenParameter copy() {
@@ -90,6 +92,7 @@ public class CodegenParameter {
output.collectionFormat = this.collectionFormat;
output.isCollectionFormatMulti = this.isCollectionFormatMulti;
output.description = this.description;
output.unescapedDescription = this.unescapedDescription;
output.baseType = this.baseType;
output.isFormParam = this.isFormParam;
output.isQueryParam = this.isQueryParam;
@@ -155,27 +158,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;
@@ -203,33 +206,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;
@@ -239,17 +242,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;
@@ -261,7 +264,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;
@@ -269,17 +272,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);
@@ -293,37 +296,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,9 +7,11 @@ import java.util.Map;
import java.util.Objects;
public class CodegenProperty implements Cloneable {
public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum,
dataFormat, name, min, max, defaultValue, defaultValueWithParam, baseType, containerType;
public String baseName, complexType, getter, setter, description, datatype,
datatypeWithEnum, dataFormat, name, min, max, defaultValue, defaultValueWithParam,
baseType, containerType, title;
/** The 'description' string without escape charcters needed by some programming languages/targets */
public String unescapedDescription;
/**
@@ -30,26 +32,29 @@ public class CodegenProperty implements Cloneable {
public String example;
public String jsonSchema;
public Double minimum;
public Double maximum;
public Boolean exclusiveMinimum;
public Boolean exclusiveMaximum;
public Boolean hasMore, required, secondaryParam;
public Boolean hasMoreNonReadOnly; // for model constructor, true if next properyt is not readonly
public Boolean isPrimitiveType, isContainer, isNotContainer;
public Boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime;
public Boolean isListContainer, isMapContainer;
public String minimum;
public String maximum;
public boolean exclusiveMinimum;
public boolean exclusiveMaximum;
public boolean hasMore, required, secondaryParam;
public boolean hasMoreNonReadOnly; // for model constructor, true if next properyt is not readonly
public boolean isPrimitiveType, isContainer, isNotContainer;
public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isFile, isBoolean, isDate, isDateTime;
public boolean isListContainer, isMapContainer;
public boolean isEnum;
public Boolean isReadOnly = false;
public boolean isReadOnly = false;
public List<String> _enum;
public Map<String, Object> allowableValues;
public CodegenProperty items;
public Map<String, Object> vendorExtensions;
public Boolean hasValidation; // true if pattern, maximum, etc are set (only used in the mustache template)
public Boolean isInherited;
public boolean hasValidation; // true if pattern, maximum, etc are set (only used in the mustache template)
public boolean isInherited;
public String nameInCamelCase; // property name in camel case
// enum name based on the property name, usually use as a prefix (e.g. VAR_NAME) for enum name (e.g. VAR_NAME_VALUE1)
public String enumName;
public String enumName;
public Integer maxItems;
public Integer minItems;
@Override
public String toString() {
@@ -74,17 +79,18 @@ public class CodegenProperty implements Cloneable {
result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode());
result = prime * result + ((defaultValueWithParam == null) ? 0 : defaultValueWithParam.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
result = prime * result + ((example == null) ? 0 : example.hashCode());
result = prime * result + ((exclusiveMaximum == null) ? 0 : exclusiveMaximum.hashCode());
result = prime * result + ((exclusiveMinimum == null) ? 0 : exclusiveMinimum.hashCode());
result = prime * result + (exclusiveMaximum ? 13:31);
result = prime * result + (exclusiveMinimum ? 13:31);
result = prime * result + ((getter == null) ? 0 : getter.hashCode());
result = prime * result + ((hasMore == null) ? 0 : hasMore.hashCode());
result = prime * result + ((hasMoreNonReadOnly == null) ? 0 : hasMoreNonReadOnly.hashCode());
result = prime * result + ((isContainer == null) ? 0 : isContainer.hashCode());
result = prime * result + (hasMore ? 13:31);
result = prime * result + ((hasMoreNonReadOnly ? 13:31));
result = prime * result + ((isContainer ? 13:31));
result = prime * result + (isEnum ? 1231 : 1237);
result = prime * result + ((isNotContainer == null) ? 0 : isNotContainer.hashCode());
result = prime * result + ((isPrimitiveType == null) ? 0 : isPrimitiveType.hashCode());
result = prime * result + ((isReadOnly == null) ? 0 : isReadOnly.hashCode());
result = prime * result + ((isNotContainer ? 13:31));
result = prime * result + ((isPrimitiveType ? 13:31));
result = prime * result + ((isReadOnly ? 13:31));
result = prime * result + ((items == null) ? 0 : items.hashCode());
result = prime * result + ((jsonSchema == null) ? 0 : jsonSchema.hashCode());
result = prime * result + ((max == null) ? 0 : max.hashCode());
@@ -95,27 +101,30 @@ public class CodegenProperty implements Cloneable {
result = prime * result + ((minimum == null) ? 0 : minimum.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((pattern == null) ? 0 : pattern.hashCode());
result = prime * result + ((required == null) ? 0 : required.hashCode());
result = prime * result + ((secondaryParam == null) ? 0 : secondaryParam.hashCode());
result = prime * result + ((required ? 13:31));
result = prime * result + ((secondaryParam ? 13:31));
result = prime * result + ((setter == null) ? 0 : setter.hashCode());
result = prime * result + ((unescapedDescription == null) ? 0 : unescapedDescription.hashCode());
result = prime * result + ((vendorExtensions == null) ? 0 : vendorExtensions.hashCode());
result = prime * result + ((hasValidation == null) ? 0 : hasValidation.hashCode());
result = prime * result + ((isString == null) ? 0 : isString.hashCode());
result = prime * result + ((isInteger == null) ? 0 : isInteger.hashCode());
result = prime * result + ((isLong == null) ? 0 : isLong.hashCode());
result = prime * result + ((isFloat == null) ? 0 : isFloat.hashCode());
result = prime * result + ((isDouble == null) ? 0 : isDouble.hashCode());
result = prime * result + ((isByteArray == null) ? 0 : isByteArray.hashCode());
result = prime * result + ((isBinary == null) ? 0 : isBinary.hashCode());
result = prime * result + ((isBoolean == null) ? 0 : isBoolean.hashCode());
result = prime * result + ((isDate == null) ? 0 : isDate.hashCode());
result = prime * result + ((isDateTime == null) ? 0 : isDateTime.hashCode());
result = prime * result + ((isMapContainer == null) ? 0 : isMapContainer.hashCode());
result = prime * result + ((isListContainer == null) ? 0 : isListContainer.hashCode());
result = prime * result + ((hasValidation ? 13:31));
result = prime * result + ((isString ? 13:31));
result = prime * result + ((isInteger ? 13:31));
result = prime * result + ((isLong ?13:31));
result = prime * result + ((isFloat ? 13:31));
result = prime * result + ((isDouble ? 13:31));
result = prime * result + ((isByteArray ? 13:31));
result = prime * result + ((isBinary ? 13:31));
result = prime * result + ((isFile ? 13:31));
result = prime * result + ((isBoolean ? 13:31));
result = prime * result + ((isDate ? 13:31));
result = prime * result + ((isDateTime ? 13:31));
result = prime * result + ((isMapContainer ? 13:31));
result = prime * result + ((isListContainer ? 13:31));
result = prime * result + Objects.hashCode(isInherited);
result = prime * result + Objects.hashCode(nameInCamelCase);
result = prime * result + Objects.hashCode(enumName);
result = prime * result + ((maxItems == null) ? 0 : maxItems.hashCode());
result = prime * result + ((minItems == null) ? 0 : minItems.hashCode());
return result;
}
@@ -143,6 +152,9 @@ public class CodegenProperty implements Cloneable {
if ((this.description == null) ? (other.description != null) : !this.description.equals(other.description)) {
return false;
}
if ((this.title == null) ? (other.title != null) : !this.title.equals(other.title)) {
return false;
}
if ((this.datatype == null) ? (other.datatype != null) : !this.datatype.equals(other.datatype)) {
return false;
}
@@ -191,31 +203,31 @@ public class CodegenProperty implements Cloneable {
if (this.maximum != other.maximum && (this.maximum == null || !this.maximum.equals(other.maximum))) {
return false;
}
if (this.exclusiveMinimum != other.exclusiveMinimum && (this.exclusiveMinimum == null || !this.exclusiveMinimum.equals(other.exclusiveMinimum))) {
if (this.exclusiveMinimum != other.exclusiveMinimum) {
return false;
}
if (this.exclusiveMaximum != other.exclusiveMaximum && (this.exclusiveMaximum == null || !this.exclusiveMaximum.equals(other.exclusiveMaximum))) {
if (this.exclusiveMaximum != other.exclusiveMaximum) {
return false;
}
if (this.required != other.required && (this.required == null || !this.required.equals(other.required))) {
if (this.required != other.required) {
return false;
}
if (this.secondaryParam != other.secondaryParam && (this.secondaryParam == null || !this.secondaryParam.equals(other.secondaryParam))) {
if (this.secondaryParam != other.secondaryParam) {
return false;
}
if (this.isPrimitiveType != other.isPrimitiveType && (this.isPrimitiveType == null || !this.isPrimitiveType.equals(other.isPrimitiveType))) {
if (this.isPrimitiveType != other.isPrimitiveType) {
return false;
}
if (this.isContainer != other.isContainer && (this.isContainer == null || !this.isContainer.equals(other.isContainer))) {
if (this.isContainer != other.isContainer) {
return false;
}
if (this.isNotContainer != other.isNotContainer && (this.isNotContainer == null || !this.isNotContainer.equals(other.isNotContainer))) {
if (this.isNotContainer != other.isNotContainer) {
return false;
}
if (this.isEnum != other.isEnum) {
return false;
}
if (this.isReadOnly != other.isReadOnly && (this.isReadOnly == null || !this.isReadOnly.equals(other.isReadOnly))) {
if (this.isReadOnly != other.isReadOnly) {
return false;
}
if (this._enum != other._enum && (this._enum == null || !this._enum.equals(other._enum))) {
@@ -229,45 +241,48 @@ public class CodegenProperty implements Cloneable {
return false;
}
if (this.hasValidation != other.hasValidation && (this.hasValidation == null || !this.hasValidation.equals(other.hasValidation))) {
if (this.hasValidation != other.hasValidation) {
return false;
}
if (this.isString != other.isString && (this.isString == null || !this.isString.equals(other.isString))) {
if (this.isString != other.isString) {
return false;
}
if (this.isInteger != other.isInteger && (this.isInteger == null || !this.isInteger.equals(other.isInteger))) {
if (this.isInteger != other.isInteger) {
return false;
}
if (this.isLong != other.isLong && (this.isLong == null || !this.isLong.equals(other.isLong))) {
if (this.isLong != other.isLong) {
return false;
}
if (this.isFloat != other.isFloat && (this.isFloat == null || !this.isFloat.equals(other.isFloat))) {
if (this.isFloat != other.isFloat) {
return false;
}
if (this.isDouble != other.isDouble && (this.isDouble == null || !this.isDouble.equals(other.isDouble))) {
if (this.isDouble != other.isDouble) {
return false;
}
if (this.isByteArray != other.isByteArray && (this.isByteArray == null || !this.isByteArray.equals(other.isByteArray))) {
if (this.isByteArray != other.isByteArray) {
return false;
}
if (this.isBoolean != other.isBoolean && (this.isBoolean == null || !this.isBoolean.equals(other.isBoolean))) {
if (this.isBoolean != other.isBoolean) {
return false;
}
if (this.isDate != other.isDate && (this.isDate == null || !this.isDate.equals(other.isDate))) {
if (this.isDate != other.isDate) {
return false;
}
if (this.isDateTime != other.isDateTime && (this.isDateTime == null || !this.isDateTime.equals(other.isDateTime))) {
if (this.isDateTime != other.isDateTime) {
return false;
}
if (this.isBinary != other.isBinary && (this.isBinary == null || !this.isBinary.equals(other.isBinary))) {
if (this.isBinary != other.isBinary) {
return false;
}
if (this.isListContainer != other.isListContainer && (this.isListContainer == null || !this.isListContainer.equals(other.isListContainer))) {
if (this.isFile != other.isFile) {
return false;
}
if (this.isMapContainer != other.isMapContainer && (this.isMapContainer == null || !this.isMapContainer.equals(other.isMapContainer))) {
if (this.isListContainer != other.isListContainer) {
return false;
}
if (this.isMapContainer != other.isMapContainer) {
return false;
}
if (!Objects.equals(this.isInherited, other.isInherited)) {
@@ -279,14 +294,20 @@ public class CodegenProperty implements Cloneable {
if (!Objects.equals(this.enumName, other.enumName)) {
return false;
}
if (this.maxItems != other.maxItems && (this.maxItems == null || !this.maxItems.equals(other.maxItems))) {
return false;
}
if (this.minItems != other.minItems && (this.minItems == null || !this.minItems.equals(other.minItems))) {
return false;
}
return true;
}
@Override
public CodegenProperty clone() {
try {
CodegenProperty cp = (CodegenProperty) super.clone();
if (this._enum != null) {
CodegenProperty cp = (CodegenProperty) super.clone();
if (this._enum != null) {
cp._enum = new ArrayList<String>(this._enum);
}
if (this.allowableValues != null) {
@@ -295,14 +316,14 @@ public class CodegenProperty implements Cloneable {
if (this.items != null) {
cp.items = this.items;
}
if(this.vendorExtensions != null){
if(this.vendorExtensions != null){
cp.vendorExtensions = new HashMap<String, Object>(this.vendorExtensions);
}
return cp;
return cp;
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
}

View File

@@ -7,21 +7,21 @@ 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 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 boolean isWildcard() {
return "0".equals(code) || "default".equals(code);
}
public Map<String, Object> vendorExtensions;
@Override
public String toString() {
@@ -41,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;
@@ -51,20 +51,24 @@ 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 != that.isFile)
return false;
if (schema != null ? !schema.equals(that.schema) : that.schema != null)
return false;
if (vendorExtensions != null ? !vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions != null)
return false;
return jsonSchema != null ? jsonSchema.equals(that.jsonSchema) : that.jsonSchema == null;
}
@@ -74,19 +78,21 @@ 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 + (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);
return result;
}
}

View File

@@ -36,6 +36,7 @@ import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
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;
@@ -91,6 +92,7 @@ public class DefaultCodegen {
protected Map<String, String> modelTestTemplateFiles = new HashMap<String, String>();
protected Map<String, String> apiDocTemplateFiles = new HashMap<String, String>();
protected Map<String, String> modelDocTemplateFiles = new HashMap<String, String>();
protected Map<String, String> reservedWordsMappings = new HashMap<String, String>();
protected String templateDir;
protected String embeddedTemplateDir;
protected String commonTemplateDir = "_common";
@@ -105,6 +107,7 @@ public class DefaultCodegen {
protected String library;
protected Boolean sortParamsByRequiredFlag = true;
protected Boolean ensureUniqueParams = true;
protected Boolean allowUnicodeIdentifiers = false;
protected String gitUserId, gitRepoId, releaseNote;
protected String httpUserAgent;
protected Boolean hideGenerationTimestamp = true;
@@ -113,6 +116,8 @@ public class DefaultCodegen {
// Then translated back during JSON encoding and decoding
protected Map<String, String> specialCharReplacements = new HashMap<String, String>();
protected String ignoreFilePathOverride;
public List<CliOption> cliOptions() {
return cliOptions;
}
@@ -140,6 +145,11 @@ public class DefaultCodegen {
.get(CodegenConstants.ENSURE_UNIQUE_PARAMS).toString()));
}
if (additionalProperties.containsKey(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS)) {
this.setAllowUnicodeIdentifiers(Boolean.valueOf(additionalProperties
.get(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS).toString()));
}
if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_PREFIX)){
this.setModelNamePrefix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_PREFIX));
}
@@ -147,7 +157,6 @@ public class DefaultCodegen {
if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_SUFFIX)){
this.setModelNameSuffix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_SUFFIX));
}
}
// override with any special post-processing for all models
@@ -184,12 +193,18 @@ public class DefaultCodegen {
for (String name : allModels.keySet()) {
CodegenModel cm = allModels.get(name);
CodegenModel parent = allModels.get(cm.parent);
// if a discriminator exists on the parent, don't add this child to the inheritance heirarchy
// TODO Determine what to do if the parent discriminator name == the grandparent discriminator name
while (parent != null) {
if (parent.children == null) {
parent.children = new ArrayList<CodegenModel>();
parent.children = new ArrayList<CodegenModel>();
}
parent.children.add(cm);
parent = allModels.get(parent.parent);
if (parent.discriminator == null) {
parent = allModels.get(parent.parent);
} else {
parent = null;
}
}
}
}
@@ -302,6 +317,10 @@ public class DefaultCodegen {
* @return the sanitized variable name for enum
*/
public String toEnumVarName(String value, String datatype) {
if (value.length() == 0) {
return "EMPTY";
}
String var = value.replaceAll("\\W+", "_").toUpperCase();
if (var.matches("\\d.*")) {
return "_" + var;
@@ -345,7 +364,7 @@ public class DefaultCodegen {
// override with any special handling of the JMustache compiler
@SuppressWarnings("unused")
public Compiler processCompiler(Compiler compiler) {
return compiler;
return compiler;
}
// override with any special text escaping logic
@@ -463,6 +482,10 @@ public class DefaultCodegen {
public Map<String, String> modelDocTemplateFiles() {
return modelDocTemplateFiles;
}
public Map<String, String> reservedWordsMappings() {
return reservedWordsMappings;
}
public Map<String, String> apiTestTemplateFiles() {
return apiTestTemplateFiles;
@@ -564,6 +587,10 @@ public class DefaultCodegen {
this.ensureUniqueParams = ensureUniqueParams;
}
public void setAllowUnicodeIdentifiers(Boolean allowUnicodeIdentifiers) {
this.allowUnicodeIdentifiers = allowUnicodeIdentifiers;
}
/**
* Return the regular expression/JSON schema pattern (http://json-schema.org/latest/json-schema-validation.html#anchor33)
*
@@ -783,6 +810,8 @@ public class DefaultCodegen {
typeMapping.put("integer", "Integer");
typeMapping.put("ByteArray", "byte[]");
typeMapping.put("binary", "byte[]");
typeMapping.put("file", "File");
typeMapping.put("UUID", "UUID");
instantiationTypes = new HashMap<String, String>();
@@ -817,6 +846,10 @@ public class DefaultCodegen {
cliOptions.add(CliOption.newBoolean(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants
.ENSURE_UNIQUE_PARAMS_DESC).defaultValue(Boolean.TRUE.toString()));
//name formatting options
cliOptions.add(CliOption.newBoolean(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, CodegenConstants
.ALLOW_UNICODE_IDENTIFIERS_DESC).defaultValue(Boolean.FALSE.toString()));
// initialize special character mapping
initalizeSpecialCharacterMapping();
}
@@ -1087,6 +1120,8 @@ public class DefaultCodegen {
datatype = "ByteArray";
} else if (p instanceof BinaryProperty) {
datatype = "binary";
} else if (p instanceof FileProperty) {
datatype = "file";
} else if (p instanceof BooleanProperty) {
datatype = "boolean";
} else if (p instanceof DateProperty) {
@@ -1189,7 +1224,8 @@ public class DefaultCodegen {
}
/**
* Output the proper model name (capitalized)
* Output the proper model name (capitalized).
* In case the name belongs to the TypeSystem it won't be renamed.
*
* @param name the name of the model
* @return capitalized model name
@@ -1241,7 +1277,6 @@ public class DefaultCodegen {
if (model instanceof ArrayModel) {
ArrayModel am = (ArrayModel) model;
ArrayProperty arrayProperty = new ArrayProperty(am.getItems());
m.hasEnums = false; // Otherwise there will be a NullPointerException in JavaClientCodegen.fromModel
m.isArrayModel = true;
m.arrayModelType = fromProperty(name, arrayProperty).complexType;
addParentContainer(m, name, arrayProperty);
@@ -1257,6 +1292,18 @@ public class DefaultCodegen {
allProperties = new LinkedHashMap<String, Property>();
allRequired = new ArrayList<String>();
m.allVars = new ArrayList<CodegenProperty>();
int modelImplCnt = 0; // only one inline object allowed in a ComposedModel
for (Model innerModel: ((ComposedModel)model).getAllOf()) {
if (innerModel instanceof ModelImpl) {
if (m.discriminator == null) {
m.discriminator = ((ModelImpl) innerModel).getDiscriminator();
}
if (modelImplCnt++ > 1) {
LOGGER.warn("More than one inline schema specified in allOf:. Only the first one is recognized. All others are ignored.");
break; // only one ModelImpl with discriminator allowed in allOf
}
}
}
} else {
allProperties = null;
allRequired = null;
@@ -1432,22 +1479,45 @@ public class DefaultCodegen {
property.nameInCamelCase = camelize(property.name, false);
property.description = escapeText(p.getDescription());
property.unescapedDescription = p.getDescription();
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);
property.isReadOnly = p.getReadOnly();
if (p.getReadOnly() != null) {
property.isReadOnly = p.getReadOnly();
}
property.vendorExtensions = p.getVendorExtensions();
String type = getSwaggerType(p);
if (p instanceof AbstractNumericProperty) {
AbstractNumericProperty np = (AbstractNumericProperty) p;
property.minimum = np.getMinimum();
property.maximum = np.getMaximum();
property.exclusiveMinimum = np.getExclusiveMinimum();
property.exclusiveMaximum = np.getExclusiveMaximum();
if (np.getMinimum() != null) {
if (p instanceof BaseIntegerProperty) { // int, long
property.minimum = String.valueOf(np.getMinimum().longValue());
} else { // double, decimal
property.minimum = String.valueOf(np.getMinimum());
}
}
if (np.getMaximum() != null) {
if (p instanceof BaseIntegerProperty) { // int, long
property.maximum = String.valueOf(np.getMaximum().longValue());
} else { // double, decimal
property.maximum = String.valueOf(np.getMaximum());
}
}
if (np.getExclusiveMinimum() != null) {
property.exclusiveMinimum = np.getExclusiveMinimum();
}
if (np.getExclusiveMaximum() != null) {
property.exclusiveMaximum = np.getExclusiveMaximum();
}
// check if any validation rule defined
// exclusive* are noop without corresponding min/max
@@ -1548,6 +1618,9 @@ public class DefaultCodegen {
if (p instanceof BinaryProperty) {
property.isBinary = true;
}
if (p instanceof FileProperty) {
property.isFile = true;
}
if (p instanceof UUIDProperty) {
property.isString = true;
}
@@ -1654,16 +1727,18 @@ public class DefaultCodegen {
property.baseType = getSwaggerType(p);
if (p instanceof ArrayProperty) {
if (p instanceof ArrayProperty) {
property.isContainer = true;
property.isListContainer = true;
property.containerType = "array";
property.baseType = getSwaggerType(p);
// handle inner property
ArrayProperty ap = (ArrayProperty) p;
property.maxItems = ap.getMaxItems();
property.minItems = ap.getMinItems();
CodegenProperty cp = fromProperty(property.name, ap.getItems());
updatePropertyForArray(property, cp);
} else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
property.isContainer = true;
property.isMapContainer = true;
property.containerType = "map";
@@ -1688,6 +1763,7 @@ public class DefaultCodegen {
LOGGER.warn("skipping invalid array property " + Json.pretty(property));
return;
}
property.dataFormat = innerProperty.dataFormat;
if (!languageSpecificPrimitives.contains(innerProperty.baseType)) {
property.complexType = innerProperty.baseType;
} else {
@@ -1724,6 +1800,7 @@ public class DefaultCodegen {
property.isPrimitiveType = true;
}
property.items = innerProperty;
property.dataFormat = innerProperty.dataFormat;
// inner item is Enum
if (isPropertyInnerMostEnum(property)) {
// isEnum is set to true when the type is an enum
@@ -1850,7 +1927,7 @@ public class DefaultCodegen {
* @return Codegen Operation object
*/
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions) {
return fromOperation(path, httpMethod, operation, definitions, null);
return fromOperation(path, httpMethod, operation, definitions, null);
}
/**
@@ -1973,9 +2050,12 @@ 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 (Boolean.TRUE.equals(r.isFile) && Boolean.TRUE.equals(r.isDefault)){
op.isResponseFile = Boolean.TRUE;
}
}
op.responses.get(op.responses.size() - 1).hasMore = false;
@@ -2010,14 +2090,14 @@ public class DefaultCodegen {
}
}
if (cm.isContainer != null) {
if (cm.isContainer) {
op.returnContainer = cm.containerType;
if ("map".equals(cm.containerType)) {
op.isMapContainer = Boolean.TRUE;
op.isMapContainer = true;
} else if ("list".equalsIgnoreCase(cm.containerType)) {
op.isListContainer = Boolean.TRUE;
op.isListContainer = true;
} else if ("array".equalsIgnoreCase(cm.containerType)) {
op.isListContainer = Boolean.TRUE;
op.isListContainer = true;
}
} else {
op.returnSimpleType = true;
@@ -2085,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;
}
}
@@ -2103,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;
}
});
@@ -2155,7 +2233,9 @@ public class DefaultCodegen {
r.schema = response.getSchema();
r.examples = toExamples(response.getExamples());
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();
@@ -2174,12 +2254,38 @@ public class DefaultCodegen {
}
}
r.dataType = cm.datatype;
r.isBinary = isDataTypeBinary(cm.datatype);
if (cm.isContainer != null) {
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;
r.isMapContainer = "map".equals(cm.containerType);
r.isListContainer = "list".equals(cm.containerType);
r.isListContainer = "list".equalsIgnoreCase(cm.containerType) || "array".equalsIgnoreCase(cm.containerType);
} else {
r.simpleType = true;
}
@@ -2212,16 +2318,25 @@ public class DefaultCodegen {
p.jsonSchema = Json.pretty(param);
if (System.getProperty("debugParser") != null) {
LOGGER.info("working on Parameter " + param);
LOGGER.info("working on Parameter " + param.getName());
}
// move the defaultValue for headers, forms and params
if (param instanceof QueryParameter) {
p.defaultValue = ((QueryParameter) param).getDefaultValue();
QueryParameter qp = (QueryParameter) param;
if(qp.getDefaultValue() != null) {
p.defaultValue = qp.getDefaultValue().toString();
}
} else if (param instanceof HeaderParameter) {
p.defaultValue = ((HeaderParameter) param).getDefaultValue();
HeaderParameter hp = (HeaderParameter) param;
if(hp.getDefaultValue() != null) {
p.defaultValue = hp.getDefaultValue().toString();
}
} else if (param instanceof FormParameter) {
p.defaultValue = ((FormParameter) param).getDefaultValue();
FormParameter fp = (FormParameter) param;
if(fp.getDefaultValue() != null) {
p.defaultValue = fp.getDefaultValue().toString();
}
}
p.vendorExtensions = param.getVendorExtensions();
@@ -2232,7 +2347,7 @@ public class DefaultCodegen {
String collectionFormat = null;
String type = qp.getType();
if (null == type) {
LOGGER.warn("Type is NULL for Serializable Parameter: " + param);
LOGGER.warn("Type is NULL for Serializable Parameter: " + param.getName());
}
if ("array".equals(type)) { // for array parameter
Property inner = qp.getItems();
@@ -2314,16 +2429,23 @@ public class DefaultCodegen {
}
// validation
p.maximum = qp.getMaximum();
p.exclusiveMaximum = qp.isExclusiveMaximum();
p.minimum = qp.getMinimum();
p.exclusiveMinimum = qp.isExclusiveMinimum();
// handle maximum, minimum properly for int/long by removing the trailing ".0"
if ("integer".equals(qp.getType())) {
p.maximum = qp.getMaximum() == null ? null : String.valueOf(qp.getMaximum().longValue());
p.minimum = qp.getMinimum() == null ? null : String.valueOf(qp.getMinimum().longValue());
} else {
p.maximum = qp.getMaximum() == null ? null : String.valueOf(qp.getMaximum());
p.minimum = qp.getMinimum() == null ? null : String.valueOf(qp.getMinimum());
}
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
@@ -2345,7 +2467,7 @@ public class DefaultCodegen {
if (model instanceof ModelImpl) {
ModelImpl impl = (ModelImpl) model;
CodegenModel cm = fromModel(bp.getName(), impl);
if (cm.emptyVars != null && cm.emptyVars == false) {
if (!cm.emptyVars) {
p.dataType = getTypeDeclaration(cm.classname);
imports.add(p.dataType);
} else {
@@ -2357,6 +2479,10 @@ public class DefaultCodegen {
p.dataType = cp.datatype;
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)
@@ -2449,6 +2575,8 @@ public class DefaultCodegen {
p.example = "BINARY_DATA_HERE";
} else if (Boolean.TRUE.equals(p.isByteArray)) {
p.example = "B";
} else if (Boolean.TRUE.equals(p.isFile)) {
p.example = "/path/to/file.txt";
} else if (Boolean.TRUE.equals(p.isDate)) {
p.example = "2013-10-20";
} else if (Boolean.TRUE.equals(p.isDateTime)) {
@@ -2469,6 +2597,10 @@ public class DefaultCodegen {
return dataType.toLowerCase().startsWith("byte");
}
public boolean isDataTypeFile(String dataType) {
return dataType.toLowerCase().equals("file");
}
/**
* Convert map of Swagger SecuritySchemeDefinition objects to a list of Codegen Security objects
*
@@ -2478,7 +2610,7 @@ public class DefaultCodegen {
@SuppressWarnings("static-method")
public List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes) {
if (schemes == null) {
return Collections.emptyList();
return Collections.emptyList();
}
List<CodegenSecurity> secs = new ArrayList<CodegenSecurity>(schemes.size());
@@ -2502,8 +2634,8 @@ public class DefaultCodegen {
sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isOAuth = false;
sec.isBasic = true;
} else {
final OAuth2Definition oauth2Definition = (OAuth2Definition) schemeDefinition;
sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false;
final OAuth2Definition oauth2Definition = (OAuth2Definition) schemeDefinition;
sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false;
sec.isOAuth = true;
sec.flow = oauth2Definition.getFlow();
if (sec.flow == null) {
@@ -2695,6 +2827,7 @@ public class DefaultCodegen {
}
co.operationId = uniqueName;
co.operationIdLowerCase = uniqueName.toLowerCase();
co.operationIdCamelCase = DefaultCodegen.camelize(uniqueName);
opList.add(co);
co.baseName = tag;
}
@@ -2822,8 +2955,8 @@ public class DefaultCodegen {
LOGGER.warn("null property for " + key);
} else {
final CodegenProperty cp = fromProperty(key, prop);
cp.required = mandatory.contains(key) ? true : null;
m.hasRequired = Boolean.TRUE.equals(m.hasRequired) || Boolean.TRUE.equals(cp.required);
cp.required = mandatory.contains(key) ? true : false;
m.hasRequired = m.hasRequired || cp.required;
if (cp.isEnum) {
// FIXME: if supporting inheritance, when called a second time for allProperties it is possible for
// m.hasEnums to be set incorrectly if allProperties has enumerations but properties does not.
@@ -2843,7 +2976,7 @@ public class DefaultCodegen {
}
}
if (cp.isContainer != null) {
if (cp.isContainer) {
addImport(m, typeMapping.get("array"));
}
@@ -3138,11 +3271,11 @@ public class DefaultCodegen {
// encountered so far and hopefully make it easier for others to add more special
// cases in the future.
// better error handling when map/array type is invalid
if (name == null) {
LOGGER.error("String to be sanitized is null. Default to ERROR_UNKNOWN");
return "ERROR_UNKNOWN";
}
// better error handling when map/array type is invalid
if (name == null) {
LOGGER.error("String to be sanitized is null. Default to ERROR_UNKNOWN");
return "ERROR_UNKNOWN";
}
// if the name is just '$', map it to 'value' for the time being.
if ("$".equals(name)) {
@@ -3171,7 +3304,14 @@ public class DefaultCodegen {
// remove everything else other than word, number and _
// $php_variable => php_variable
return name.replaceAll("[^a-zA-Z0-9_]", "");
if (allowUnicodeIdentifiers) { //could be converted to a single line with ?: operator
name = Pattern.compile("\\W", Pattern.UNICODE_CHARACTER_CLASS).matcher(name).replaceAll("");
}
else {
name = name.replaceAll("\\W", "");
}
return name;
}
/**
@@ -3264,6 +3404,10 @@ public class DefaultCodegen {
} else if (Boolean.TRUE.equals(property.isBinary)) {
parameter.isByteArray = true;
parameter.isPrimitiveType = true;
} else if (Boolean.TRUE.equals(property.isFile)) {
parameter.isFile = true;
// file is *not* a primitive type
//parameter.isPrimitiveType = true;
} else if (Boolean.TRUE.equals(property.isDate)) {
parameter.isDate = true;
parameter.isPrimitiveType = true;
@@ -3359,11 +3503,44 @@ public class DefaultCodegen {
public boolean convertPropertyToBooleanAndWriteBack(String propertyKey) {
boolean booleanValue = false;
if (additionalProperties.containsKey(propertyKey)) {
booleanValue = Boolean.valueOf(additionalProperties.get(propertyKey).toString());
booleanValue = convertPropertyToBoolean(propertyKey);
// write back as boolean
additionalProperties.put(propertyKey, booleanValue);
writePropertyBack(propertyKey, booleanValue);
}
return booleanValue;
}
/**
* Provides an override location, if any is specified, for the .swagger-codegen-ignore.
*
* This is originally intended for the first generation only.
*
* @return a string of the full path to an override ignore file.
*/
public String getIgnoreFilePathOverride() {
return ignoreFilePathOverride;
}
/**
* Sets an override location for the .swagger-codegen.ignore location for the first code generation.
*
* @param ignoreFileOverride The full path to an ignore file
*/
public void setIgnoreFilePathOverride(final String ignoreFileOverride) {
this.ignoreFilePathOverride = ignoreFileOverride;
}
public boolean convertPropertyToBoolean(String propertyKey) {
boolean booleanValue = false;
if (additionalProperties.containsKey(propertyKey)) {
booleanValue = Boolean.valueOf(additionalProperties.get(propertyKey).toString());
}
return booleanValue;
}
public void writePropertyBack(String propertyKey, boolean value) {
additionalProperties.put(propertyKey, value);
}
}

View File

@@ -42,7 +42,21 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
this.swagger = opts.getSwagger();
this.config = opts.getConfig();
this.config.additionalProperties().putAll(opts.getOpts().getProperties());
ignoreProcessor = new CodegenIgnoreProcessor(this.config.getOutputDir());
String ignoreFileLocation = this.config.getIgnoreFilePathOverride();
if(ignoreFileLocation != null) {
final File ignoreFile = new File(ignoreFileLocation);
if(ignoreFile.exists() && ignoreFile.canRead()) {
this.ignoreProcessor = new CodegenIgnoreProcessor(ignoreFile);
} else {
LOGGER.warn("Ignore file specified at {} is not valid. This will fall back to an existing ignore file if present in the output directory.", ignoreFileLocation);
}
}
if(this.ignoreProcessor == null) {
this.ignoreProcessor = new CodegenIgnoreProcessor(this.config.getOutputDir());
}
return this;
}
@@ -61,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();
@@ -113,7 +127,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
config.processOpts();
config.preprocessSwagger(swagger);
config.additionalProperties().put("generatedDate", DateTime.now().toString());
config.additionalProperties().put("generatorClass", config.getClass().toString());
config.additionalProperties().put("generatorClass", config.getClass().getName());
config.additionalProperties().put("inputSpec", config.getInputSpec());
if (swagger.getVendorExtensions() != null) {
config.vendorExtensions().putAll(swagger.getVendorExtensions());
@@ -140,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) {
@@ -474,7 +490,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
if (!of.isDirectory()) {
of.mkdirs();
}
String outputFilename = outputFolder + File.separator + support.destinationFilename;
String outputFilename = outputFolder + File.separator + support.destinationFilename.replace('/', File.separatorChar);
if (!config.shouldOverwrite(outputFilename)) {
LOGGER.info("Skipped overwriting " + outputFilename);
continue;
@@ -526,6 +542,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
if (in != null) {
LOGGER.info("writing file " + outputFile);
IOUtils.copy(in, out);
out.close();
} else {
LOGGER.error("can't open " + templateFile + " for input");
}
@@ -656,7 +673,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
private File processTemplateToFile(Map<String, Object> templateData, String templateName, String outputFilename) throws IOException {
if(ignoreProcessor.allowsFile(new File(outputFilename.replaceAll("//", "/")))) {
String adjustedOutputFilename = outputFilename.replaceAll("//", "/").replace('/', File.separatorChar);
if(ignoreProcessor.allowsFile(new File(adjustedOutputFilename))) {
String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile);
Mustache.Compiler compiler = Mustache.compiler();
@@ -671,11 +689,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
.defaultValue("")
.compile(template);
writeToFile(outputFilename, tmpl.execute(templateData));
return new File(outputFilename);
writeToFile(adjustedOutputFilename, tmpl.execute(templateData));
return new File(adjustedOutputFilename);
}
LOGGER.info("Skipped generation of " + outputFilename + " due to rule in .swagger-codegen-ignore");
LOGGER.info("Skipped generation of " + adjustedOutputFilename + " due to rule in .swagger-codegen-ignore");
return null;
}
@@ -870,7 +888,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
if (os != null && os.size() > 0) {
CodegenOperation op = os.get(os.size() - 1);
op.hasMore = null;
op.hasMore = false;
}
}
return operations;

View File

@@ -15,7 +15,7 @@ import config.ConfigParser;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
public class AuthParser {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthParser.class);
public static List<AuthorizationValue> parse(String urlEncodedAuthStr) {
@@ -25,7 +25,8 @@ public class AuthParser {
for (String part : parts) {
String[] kvPair = part.split(":");
if (kvPair.length == 2) {
auths.add(new AuthorizationValue(URLDecoder.decode(kvPair[0]), URLDecoder.decode(kvPair[1]), "header")); // FIXME replace the deprecated method by decode(string, encoding). Which encoding is used ? Default UTF-8 ?
// FIXME replace the deprecated method by decode(string, encoding). Which encoding is used ? Default UTF-8 ?
auths.add(new AuthorizationValue(URLDecoder.decode(kvPair[0]), URLDecoder.decode(kvPair[1]), "header"));
}
}
}
@@ -53,5 +54,4 @@ public class AuthParser {
return 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);
@@ -54,18 +55,21 @@ public class CodegenConfigurator {
private String artifactId;
private String artifactVersion;
private String library;
private String ignoreFileOverride;
private Map<String, String> systemProperties = new HashMap<String, String>();
private Map<String, String> instantiationTypes = new HashMap<String, String>();
private Map<String, String> typeMappings = new HashMap<String, String>();
private Map<String, String> additionalProperties = new HashMap<String, String>();
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
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";
private String httpUserAgent;
private final Map<String, String> dynamicProperties = new HashMap<String, String>(); //the map that holds the JsonAnySetter/JsonAnyGetter values
private final Map<String, Object> dynamicProperties = new HashMap<String, Object>(); //the map that holds the JsonAnySetter/JsonAnyGetter values
public CodegenConfigurator() {
this.setOutputDir(".");
@@ -152,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();
@@ -255,16 +259,16 @@ public class CodegenConfigurator {
return this;
}
public Map<String, String> getAdditionalProperties() {
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
public CodegenConfigurator setAdditionalProperties(Map<String, String> additionalProperties) {
public CodegenConfigurator setAdditionalProperties(Map<String, Object> additionalProperties) {
this.additionalProperties = additionalProperties;
return this;
}
public CodegenConfigurator addAdditionalProperty(String key, String value) {
public CodegenConfigurator addAdditionalProperty(String key, Object value) {
this.additionalProperties.put(key, value);
return this;
}
@@ -342,6 +346,29 @@ public class CodegenConfigurator {
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;
}
public String getIgnoreFileOverride() {
return ignoreFileOverride;
}
public CodegenConfigurator setIgnoreFileOverride(final String ignoreFileOverride) {
this.ignoreFileOverride = ignoreFileOverride;
return this;
}
public ClientOptInput toClientOptInput() {
Validate.notEmpty(lang, "language must be specified");
@@ -355,11 +382,13 @@ public class CodegenConfigurator {
config.setInputSpec(inputSpec);
config.setOutputDir(outputDir);
config.setSkipOverwrite(skipOverwrite);
config.setIgnoreFilePathOverride(ignoreFileOverride);
config.instantiationTypes().putAll(instantiationTypes);
config.typeMapping().putAll(typeMappings);
config.importMapping().putAll(importMappings);
config.languageSpecificPrimitives().addAll(languageSpecificPrimitives);
config.reservedWordsMappings().putAll(reservedWordMappings);
checkAndSetAdditionalProperty(apiPackage, CodegenConstants.API_PACKAGE);
checkAndSetAdditionalProperty(modelPackage, CodegenConstants.MODEL_PACKAGE);
@@ -398,12 +427,12 @@ public class CodegenConfigurator {
@JsonAnySetter
public CodegenConfigurator addDynamicProperty(String name, Object value) {
dynamicProperties.put(name, value.toString());
dynamicProperties.put(name, value);
return this;
}
@JsonAnyGetter
public Map<String, String> getDynamicProperties() {
public Map<String, Object> getDynamicProperties() {
return dynamicProperties;
}

View File

@@ -58,6 +58,13 @@ public final class CodegenConfiguratorUtils {
}
}
public static void applyReservedWordsMappingsKvp(String reservedWordMappings, CodegenConfigurator configurator) {
final Map<String, String> map = createMapFromKeyValuePairs(reservedWordMappings);
for (Map.Entry<String, String> entry : map.entrySet()) {
configurator.addAdditionalReservedWordMapping(entry.getKey(), entry.getValue());
}
}
private static Set<String> createSetFromCsvList(String csvProperty) {
final List<String> values = OptionUtils.splitCommaSeparatedList(csvProperty);
return new HashSet<String>(values);
@@ -74,4 +81,6 @@ public final class CodegenConfiguratorUtils {
return result;
}
}

View File

@@ -1,8 +1,12 @@
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;
import io.swagger.models.properties.BaseIntegerProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
@@ -10,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;
@@ -19,71 +22,111 @@ 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;
import java.util.Map;
import java.util.Random;
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;
private Random random;
public ExampleGenerator(Map<String, Model> examples) {
this.examples = examples;
// use a fixed seed to make the "random" numbers reproducible.
this.random = new Random("ExampleGenerator".hashCode());
}
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();
@@ -93,21 +136,31 @@ public class ExampleGenerator {
};
}
} else if (property instanceof DateProperty) {
return "2000-01-23T04:56:07.000+00:00";
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;
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) {
@@ -122,10 +175,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";
}
@@ -133,16 +188,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 random.nextDouble() * range + min;
} else if (min != null) {
return random.nextDouble() + min;
} else if (max != null) {
return random.nextDouble() * max;
} else {
return random.nextDouble() * 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

@@ -9,12 +9,21 @@ import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.DecimalProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.BaseIntegerProperty;
import io.swagger.models.properties.AbstractNumericProperty;
import io.swagger.models.properties.PasswordProperty;
import io.swagger.models.properties.UUIDProperty;
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;
import java.util.Collection;
import java.util.Collections;
@@ -25,6 +34,7 @@ import java.util.Map;
import java.util.Set;
public class XmlExampleGenerator {
protected final Logger LOGGER = LoggerFactory.getLogger(XmlExampleGenerator.class);
public static String NEWLINE = "\n";
public static String TAG_START = "<";
public static String CLOSE_TAG = ">";
@@ -163,45 +173,44 @@ public class XmlExampleGenerator {
return sb.toString();
}
/**
* Get the example string value for the given Property.
*
* If an example value was not provided in the specification, a default will be generated.
*
* @param property Property to get example string for
*
* @return Example String
*/
protected String getExample(Property property) {
if (property instanceof DateTimeProperty) {
if (property.getExample() != null) {
return property.getExample().toString();
} else {
return "2000-01-23T04:56:07.000Z";
}
} else if (property instanceof StringProperty) {
if (property.getExample() != null) {
return property.getExample().toString();
} else {
return "string";
}
if (property.getExample() != null) {
return property.getExample().toString();
} else if (property instanceof DateTimeProperty) {
return "2000-01-23T04:56:07.000Z";
} else if (property instanceof DateProperty) {
if (property.getExample() != null) {
return property.getExample().toString();
} else {
return "2000-01-23T04:56:07.000Z";
}
} else if (property instanceof IntegerProperty) {
if (property.getExample() != null) {
return property.getExample().toString();
} else {
return "0";
}
return "2000-01-23";
} else if (property instanceof BooleanProperty) {
if (property.getExample() != null) {
return property.getExample().toString();
} else {
return "true";
}
return "true";
} else if (property instanceof LongProperty) {
if (property.getExample() != null) {
return property.getExample().toString();
} else {
return "123456";
}
return "123456789";
} else if (property instanceof DoubleProperty) { // derived from DecimalProperty so make sure this is first
return "3.149";
} else if (property instanceof DecimalProperty) {
return "1.3579";
} else if (property instanceof PasswordProperty) {
return "********";
} else if (property instanceof UUIDProperty) {
return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
// do these last in case the specific types above are derived from these classes
} else if (property instanceof StringProperty) {
return "aeiou";
} else if (property instanceof BaseIntegerProperty) {
return "123";
} else if (property instanceof AbstractNumericProperty) {
return "1.23";
}
return "not implemented " + property;
LOGGER.warn("default example value not implemented for " + property);
return "";
}
@SuppressWarnings("static-method")

View File

@@ -8,34 +8,71 @@ import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Presents a processing utility for parsing and evaluating files containing common ignore patterns. (.swagger-codegen-ignore)
*/
public class CodegenIgnoreProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(CodegenIgnoreProcessor.class);
private final String outputPath;
private File ignoreFile = null;
private List<Rule> exclusionRules = new ArrayList<>();
private List<Rule> inclusionRules = new ArrayList<>();
public CodegenIgnoreProcessor(String outputPath) {
this.outputPath = outputPath;
final File directory = new File(outputPath);
if(directory.exists() && directory.isDirectory()){
final File codegenIgnore = new File(directory, ".swagger-codegen-ignore");
if(codegenIgnore.exists() && codegenIgnore.isFile()){
try {
loadCodegenRules(codegenIgnore);
} catch (IOException e) {
LOGGER.error("Could not process .swagger-codegen-ignore.", e.getMessage());
}
} else {
// log info message
LOGGER.info("No .swagger-codegen-ignore file found.");
}
/**
* Loads the default ignore file (.swagger-codegen-ignore) from the specified path.
*
* @param baseDirectory The base directory of the files to be processed. This contains the ignore file.
*/
public CodegenIgnoreProcessor(final String baseDirectory) {
this(baseDirectory, ".swagger-codegen-ignore");
}
/**
* Loads the specified ignore file by name ([ignoreFile]) from the specified path.
*
* @param baseDirectory The base directory of the files to be processed. This contains the ignore file.
* @param ignoreFile The file containing ignore patterns.
*/
@SuppressWarnings("WeakerAccess")
public CodegenIgnoreProcessor(final String baseDirectory, final String ignoreFile) {
final File directory = new File(baseDirectory);
final File targetIgnoreFile = new File(directory, ignoreFile);
if (directory.exists() && directory.isDirectory()) {
loadFromFile(targetIgnoreFile);
} else {
LOGGER.warn("Output directory does not exist, or is inaccessible. No file (.swager-codegen-ignore) will be evaluated.");
}
}
void loadCodegenRules(File codegenIgnore) throws IOException {
/**
* Constructs an instance of {@link CodegenIgnoreProcessor} from an ignore file defined by {@code targetIgnoreFile}.
*
* @param targetIgnoreFile The ignore file location.
*/
public CodegenIgnoreProcessor(final File targetIgnoreFile) {
loadFromFile(targetIgnoreFile);
}
private void loadFromFile(File targetIgnoreFile) {
if (targetIgnoreFile.exists() && targetIgnoreFile.isFile()) {
try {
loadCodegenRules(targetIgnoreFile);
this.ignoreFile = targetIgnoreFile;
} catch (IOException e) {
LOGGER.error(String.format("Could not process %s.", targetIgnoreFile.getName()), e.getMessage());
}
} else {
// log info message
LOGGER.info(String.format("No %s file found.", targetIgnoreFile.getName()));
}
}
void loadCodegenRules(final File codegenIgnore) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(codegenIgnore))) {
String line;
@@ -61,8 +98,17 @@ public class CodegenIgnoreProcessor {
}
}
public boolean allowsFile(File targetFile) {
File file = new File(new File(this.outputPath).toURI().relativize(targetFile.toURI()).getPath());
/**
* Determines whether or not a file defined by {@code toEvaluate} is allowed,
* under the exclusion rules from the ignore file being processed.
*
* @param targetFile The file to check against exclusion rules from the ignore file.
* @return {@code false} if file matches any pattern in the ignore file (disallowed), otherwise {@code true} (allowed).
*/
public boolean allowsFile(final File targetFile) {
if(this.ignoreFile == null) return true;
File file = new File(this.ignoreFile.getParentFile().toURI().relativize(targetFile.toURI()).getPath());
Boolean directoryExcluded = false;
Boolean exclude = false;
if(exclusionRules.size() == 0 && inclusionRules.size() == 0) {
@@ -124,10 +170,23 @@ public class CodegenIgnoreProcessor {
return Boolean.FALSE.equals(exclude);
}
/**
* Allows a consumer to manually inspect explicit "inclusion rules". That is, patterns in the ignore file which have been negated.
*
* @return A {@link ImmutableList#copyOf(Collection)} of rules which possibly negate exclusion rules in the ignore file.
*/
public List<Rule> getInclusionRules() {
return ImmutableList.copyOf(inclusionRules);
}
/**
* Allows a consumer to manually inspect all "exclusion rules". That is, patterns in the ignore file which represent
* files and directories to be excluded, unless explicitly overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules.
*
* NOTE: Existence in this list doesn't mean a file is excluded. The rule can be overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules.
*
* @return A {@link ImmutableList#copyOf(Collection)} of rules which define exclusions by patterns in the ignore file.
*/
public List<Rule> getExclusionRules() {
return ImmutableList.copyOf(exclusionRules);
}

View File

@@ -51,6 +51,8 @@ public abstract class Rule {
* Example: **\/*.bak excludes all backup. Adding !/test.bak will include test.bak in the project root.
* <p>
* NOTE: It is not possible to re-include a file if a parent directory of that file is excluded.
*
* @return {@code true} if the rule is negated (inverse), otherwise {@code false} (normal).
*/
public Boolean getNegated() {
return this.syntax != null && this.syntax.size() > 0 && this.syntax.get(0).getToken() == IgnoreLineParser.Token.NEGATE;

View File

@@ -27,6 +27,8 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
protected String packageCompany = "Swagger";
protected String packageCopyright = "No Copyright";
protected String interfacePrefix = "I";
protected String sourceFolder = "src";
// TODO: Add option for test folder output location. Nice to allow e.g. ./test instead of ./src.
@@ -60,10 +62,10 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
setReservedWordsLowerCase(
Arrays.asList(
// set client as a reserved word to avoid conflicts with IO.Swagger.Client
// set "client" as a reserved word to avoid conflicts with IO.Swagger.Client
// this is a workaround and can be removed if c# api client is updated to use
// fully qualified name
"client",
"client", "parameter",
// local variable names in API methods (endpoints)
"localVarPath", "localVarPathParams", "localVarQueryParams", "localVarHeaderParams",
"localVarFormParams", "localVarFileParams", "localVarStatusCode", "localVarResponse",
@@ -254,6 +256,19 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES)) {
setOptionalEmitDefaultValue(Boolean.valueOf(additionalProperties.get(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES).toString()));
}
if (additionalProperties.containsKey(CodegenConstants.INTERFACE_PREFIX)) {
String useInterfacePrefix = additionalProperties.get(CodegenConstants.INTERFACE_PREFIX).toString();
if("false".equals(useInterfacePrefix.toLowerCase())) {
setInterfacePrefix("");
} else if(!"true".equals(useInterfacePrefix.toLowerCase())) {
// NOTE: if user passes "true" explicitly, we use the default I- prefix. The other supported case here is a custom prefix.
setInterfacePrefix(sanitizeName(useInterfacePrefix));
}
}
// This either updates additionalProperties with the above fixes, or sets the default if the option was not specified.
additionalProperties.put(CodegenConstants.INTERFACE_PREFIX, interfacePrefix);
}
@Override
@@ -401,10 +416,13 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
}
return name;
}
}
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@@ -466,7 +484,13 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
return "\"" + dp.getDefault() + "\"";
String _default = dp.getDefault();
if (dp.getEnum() == null) {
return "\"" + _default + "\"";
} else {
// convert to enum var name later in postProcessModels
return _default;
}
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
@@ -590,31 +614,43 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
}
public void setPackageTitle(String packageTitle) {
this.packageTitle = packageTitle;
}
this.packageTitle = packageTitle;
}
public void setPackageProductName(String packageProductName) {
this.packageProductName = packageProductName;
}
this.packageProductName = packageProductName;
}
public void setPackageDescription(String packageDescription) {
this.packageDescription = packageDescription;
}
public void setPackageDescription(String packageDescription) {
this.packageDescription = packageDescription;
}
public void setPackageCompany(String packageCompany) {
this.packageCompany = packageCompany;
}
this.packageCompany = packageCompany;
}
public void setPackageCopyright(String packageCopyright) {
this.packageCopyright = packageCopyright;
}
this.packageCopyright = packageCopyright;
}
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
}
public String getInterfacePrefix() {
return interfacePrefix;
}
public void setInterfacePrefix(final String interfacePrefix) {
this.interfacePrefix = interfacePrefix;
}
@Override
public String toEnumVarName(String name, String datatype) {
if (name.length() == 0) {
return "Empty";
}
// for symbol, e.g. $, #
if (getSymbolName(name) != null) {
return camelize(getSymbolName(name));

View File

@@ -52,6 +52,17 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
protected String groupId = "io.swagger";
protected String artifactId = "swagger-java";
protected String artifactVersion = "1.0.0";
protected String artifactUrl = "https://github.com/swagger-api/swagger-codegen";
protected String artifactDescription = "Swagger Java";
protected String developerName = "Swagger";
protected String developerEmail = "apiteam@swagger.io";
protected String developerOrganization = "Swagger";
protected String developerOrganizationUrl = "http://swagger.io";
protected String scmConnection = "scm:git:git@github.com:swagger-api/swagger-codegen.git";
protected String scmDeveloperConnection = "scm:git:git@github.com:swagger-api/swagger-codegen.git";
protected String scmUrl = "https://github.com/swagger-api/swagger-codegen";
protected String licenseName = "Unlicense";
protected String licenseUrl = "http://unlicense.org";
protected String projectFolder = "src" + File.separator + "main";
protected String projectTestFolder = "src" + File.separator + "test";
protected String sourceFolder = projectFolder + File.separator + "java";
@@ -109,7 +120,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
instantiationTypes.put("map", "HashMap");
typeMapping.put("date", "Date");
typeMapping.put("file", "File");
typeMapping.put("UUID", "String");
cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC));
@@ -117,6 +127,17 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
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));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_URL, CodegenConstants.ARTIFACT_URL_DESC));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_DESCRIPTION, CodegenConstants.ARTIFACT_DESCRIPTION_DESC));
cliOptions.add(new CliOption(CodegenConstants.SCM_CONNECTION, CodegenConstants.SCM_CONNECTION_DESC));
cliOptions.add(new CliOption(CodegenConstants.SCM_DEVELOPER_CONNECTION, CodegenConstants.SCM_DEVELOPER_CONNECTION_DESC));
cliOptions.add(new CliOption(CodegenConstants.SCM_URL, CodegenConstants.SCM_URL_DESC));
cliOptions.add(new CliOption(CodegenConstants.DEVELOPER_NAME, CodegenConstants.DEVELOPER_NAME_DESC));
cliOptions.add(new CliOption(CodegenConstants.DEVELOPER_EMAIL, CodegenConstants.DEVELOPER_EMAIL_DESC));
cliOptions.add(new CliOption(CodegenConstants.DEVELOPER_ORGANIZATION, CodegenConstants.DEVELOPER_ORGANIZATION_DESC));
cliOptions.add(new CliOption(CodegenConstants.DEVELOPER_ORGANIZATION_URL, CodegenConstants.DEVELOPER_ORGANIZATION_URL_DESC));
cliOptions.add(new CliOption(CodegenConstants.LICENSE_NAME, CodegenConstants.LICENSE_NAME_DESC));
cliOptions.add(new CliOption(CodegenConstants.LICENSE_URL, CodegenConstants.LICENSE_URL_DESC));
cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC));
cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC));
cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC));
@@ -187,6 +208,72 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
}
if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_URL)) {
this.setArtifactUrl((String) additionalProperties.get(CodegenConstants.ARTIFACT_URL));
} else {
additionalProperties.put(CodegenConstants.ARTIFACT_URL, artifactUrl);
}
if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_DESCRIPTION)) {
this.setArtifactDescription((String) additionalProperties.get(CodegenConstants.ARTIFACT_DESCRIPTION));
} else {
additionalProperties.put(CodegenConstants.ARTIFACT_DESCRIPTION, artifactDescription);
}
if (additionalProperties.containsKey(CodegenConstants.SCM_CONNECTION)) {
this.setScmConnection((String) additionalProperties.get(CodegenConstants.SCM_CONNECTION));
} else {
additionalProperties.put(CodegenConstants.SCM_CONNECTION, scmConnection);
}
if (additionalProperties.containsKey(CodegenConstants.SCM_DEVELOPER_CONNECTION)) {
this.setScmDeveloperConnection((String) additionalProperties.get(CodegenConstants.SCM_DEVELOPER_CONNECTION));
} else {
additionalProperties.put(CodegenConstants.SCM_DEVELOPER_CONNECTION, scmDeveloperConnection);
}
if (additionalProperties.containsKey(CodegenConstants.SCM_URL)) {
this.setScmUrl((String) additionalProperties.get(CodegenConstants.SCM_URL));
} else {
additionalProperties.put(CodegenConstants.SCM_URL, scmUrl);
}
if (additionalProperties.containsKey(CodegenConstants.DEVELOPER_NAME)) {
this.setDeveloperName((String) additionalProperties.get(CodegenConstants.DEVELOPER_NAME));
} else {
additionalProperties.put(CodegenConstants.DEVELOPER_NAME, developerName);
}
if (additionalProperties.containsKey(CodegenConstants.DEVELOPER_EMAIL)) {
this.setDeveloperEmail((String) additionalProperties.get(CodegenConstants.DEVELOPER_EMAIL));
} else {
additionalProperties.put(CodegenConstants.DEVELOPER_EMAIL, developerEmail);
}
if (additionalProperties.containsKey(CodegenConstants.DEVELOPER_ORGANIZATION)) {
this.setDeveloperOrganization((String) additionalProperties.get(CodegenConstants.DEVELOPER_ORGANIZATION));
} else {
additionalProperties.put(CodegenConstants.DEVELOPER_ORGANIZATION, developerOrganization);
}
if (additionalProperties.containsKey(CodegenConstants.DEVELOPER_ORGANIZATION_URL)) {
this.setDeveloperOrganizationUrl((String) additionalProperties.get(CodegenConstants.DEVELOPER_ORGANIZATION_URL));
} else {
additionalProperties.put(CodegenConstants.DEVELOPER_ORGANIZATION_URL, developerOrganizationUrl);
}
if (additionalProperties.containsKey(CodegenConstants.LICENSE_NAME)) {
this.setLicenseName((String) additionalProperties.get(CodegenConstants.LICENSE_NAME));
} else {
additionalProperties.put(CodegenConstants.LICENSE_NAME, licenseName);
}
if (additionalProperties.containsKey(CodegenConstants.LICENSE_URL)) {
this.setLicenseUrl((String) additionalProperties.get(CodegenConstants.LICENSE_URL));
} else {
additionalProperties.put(CodegenConstants.LICENSE_URL, licenseUrl);
}
if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
}
@@ -230,6 +317,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");
@@ -239,6 +327,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");
}
@@ -270,6 +359,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
if("joda".equals(dateLibrary)) {
additionalProperties.put("joda", "true");
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "DateTime");
@@ -313,6 +403,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@@ -411,11 +504,22 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override
public String toModelName(final String name) {
final String sanitizedName = sanitizeName(modelNamePrefix + name + modelNameSuffix);
final String sanitizedName = sanitizeName(name);
String nameWithPrefixSuffix = sanitizedName;
if (!StringUtils.isEmpty(modelNamePrefix)) {
// add '_' so that model name can be camelized correctly
nameWithPrefixSuffix = modelNamePrefix + "_" + nameWithPrefixSuffix;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
// add '_' so that model name can be camelized correctly
nameWithPrefixSuffix = nameWithPrefixSuffix + "_" + modelNameSuffix;
}
// camelize the model name
// phone_number => PhoneNumber
final String camelizedName = camelize(sanitizedName);
final String camelizedName = camelize(nameWithPrefixSuffix);
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(camelizedName)) {
@@ -425,7 +529,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
// model name starts with number
if (name.matches("^\\d.*")) {
if (camelizedName.matches("^\\d.*")) {
final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
return modelName;
@@ -445,10 +549,20 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
if (inner == null) {
LOGGER.warn(ap.getName() + "(array property) does not have a proper inner type defined");
// TODO maybe better defaulting to StringProperty than returning null
return null;
}
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
if (inner == null) {
LOGGER.warn(mp.getName() + "(map property) does not have a proper inner type defined");
// TODO maybe better defaulting to StringProperty than returning null
return null;
}
return getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">";
}
return super.getTypeDeclaration(p);
@@ -464,6 +578,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} else {
pattern = "new ArrayList<%s>()";
}
if (ap.getItems() == null) {
return null;
}
return String.format(pattern, getTypeDeclaration(ap.getItems()));
} else if (p instanceof MapProperty) {
final MapProperty ap = (MapProperty) p;
@@ -473,6 +590,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} else {
pattern = "new HashMap<String, %s>()";
}
if (ap.getAdditionalProperties() == null) {
return null;
}
return String.format(pattern, getTypeDeclaration(ap.getAdditionalProperties()));
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
@@ -587,21 +707,16 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type;
// don't apply renaming on types from the typeMapping
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type) || type.indexOf(".") >= 0 ||
type.equals("Map") || type.equals("List") ||
type.equals("File") || type.equals("Date")) {
return type;
}
} else {
type = swaggerType;
return typeMapping.get(swaggerType);
}
if (null == type) {
if (null == swaggerType) {
LOGGER.error("No Type defined for Property " + p);
}
return toModelName(type);
return toModelName(swaggerType);
}
@Override
@@ -781,6 +896,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override
public String toEnumVarName(String value, String datatype) {
if (value.length() == 0) {
return "EMPTY";
}
// for symbol, e.g. $, #
if (getSymbolName(value) != null) {
return getSymbolName(value).toUpperCase();
@@ -821,7 +940,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
op.path = sanitizePath(op.path);
return op;
}
private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
// This generator uses inline classes to define enums, which breaks when
// dealing with models that have subTypes. To clean this up, we will analyze
@@ -863,7 +982,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
int count = 0, numVars = codegenProperties.size();
for(CodegenProperty codegenProperty : codegenProperties) {
count += 1;
codegenProperty.hasMore = (count < numVars) ? true : null;
codegenProperty.hasMore = (count < numVars) ? true : false;
}
codegenModel.vars = codegenProperties;
}
@@ -895,6 +1014,50 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
this.artifactVersion = artifactVersion;
}
public void setArtifactUrl(String artifactUrl) {
this.artifactUrl = artifactUrl;
}
public void setArtifactDescription(String artifactDescription) {
this.artifactDescription = artifactDescription;
}
public void setScmConnection(String scmConnection) {
this.scmConnection = scmConnection;
}
public void setScmDeveloperConnection(String scmDeveloperConnection) {
this.scmDeveloperConnection = scmDeveloperConnection;
}
public void setScmUrl(String scmUrl) {
this.scmUrl = scmUrl;
}
public void setDeveloperName(String developerName) {
this.developerName = developerName;
}
public void setDeveloperEmail(String developerEmail) {
this.developerEmail = developerEmail;
}
public void setDeveloperOrganization(String developerOrganization) {
this.developerOrganization = developerOrganization;
}
public void setDeveloperOrganizationUrl(String developerOrganizationUrl) {
this.developerOrganizationUrl = developerOrganizationUrl;
}
public void setLicenseName(String licenseName) {
this.licenseName = licenseName;
}
public void setLicenseUrl(String licenseUrl) {
this.licenseUrl = licenseUrl;
}
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
}
@@ -957,7 +1120,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
return sb.toString();
}
public void setSupportJava6(boolean value) {
this.supportJava6 = value;
}
@@ -966,4 +1129,22 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
return escapeText(pattern);
}
public boolean convertPropertyToBoolean(String propertyKey) {
boolean booleanValue = false;
if (additionalProperties.containsKey(propertyKey)) {
booleanValue = Boolean.valueOf(additionalProperties.get(propertyKey).toString());
}
return booleanValue;
}
public void writePropertyBack(String propertyKey, boolean value) {
additionalProperties.put(propertyKey, value);
}
@Override
public String sanitizeTag(String tag) {
return camelize(sanitizeName(tag));
}
}

View File

@@ -1,16 +1,27 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import io.swagger.codegen.CliOption;
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.languages.features.BeanValidationFeatures;
import io.swagger.codegen.languages.features.UseGenericResponseFeatures;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen {
public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen implements BeanValidationFeatures {
/**
* Name of the sub-directory in "src/main/resource" where to find the
* Mustache template for the JAX-RS Codegen.
@@ -19,10 +30,12 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
protected String implFolder = "src/main/java";
protected String testResourcesFolder = "src/test/resources";
protected String title = "Swagger Server";
protected boolean useBeanValidation = true;
static Logger LOGGER = LoggerFactory.getLogger(AbstractJavaJAXRSServerCodegen.class);
public AbstractJavaJAXRSServerCodegen()
{
public AbstractJavaJAXRSServerCodegen() {
super();
sourceFolder = "src/gen/java";
@@ -40,6 +53,8 @@ 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(new CliOption("serverPort", "The port on which the server should be started"));
}
@@ -48,8 +63,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
// ===============
@Override
public CodegenType getTag()
{
public CodegenType getTag() {
return CodegenType.SERVER;
}
@@ -60,6 +74,15 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
if (additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) {
implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER);
}
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
}
if (useBeanValidation) {
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
}
}
@Override
@@ -68,15 +91,19 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
swagger.setBasePath("");
}
String host = swagger.getHost();
String port = "8080"; // Default value for a JEE Server
if ( host != null ) {
String[] parts = host.split(":");
if ( parts.length > 1 ) {
port = parts[1];
if (!this.additionalProperties.containsKey("serverPort")) {
final String host = swagger.getHost();
String port = "8080"; // Default value for a JEE Server
if ( host != null ) {
String[] parts = host.split(":");
if ( parts.length > 1 ) {
port = parts[1];
}
}
this.additionalProperties.put("serverPort", port);
}
this.additionalProperties.put("serverPort", port);
if ( swagger.getPaths() != null ) {
for ( String pathname : swagger.getPaths().keySet() ) {
Path path = swagger.getPath(pathname);
@@ -138,6 +165,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);
}
}
}
@@ -204,4 +237,10 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
private String implFileFolder(String output) {
return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/');
}
public void setUseBeanValidation(boolean useBeanValidation) {
this.useBeanValidation = useBeanValidation;
}
}

View File

@@ -251,8 +251,11 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
.replaceAll(regLastPathSeparator+ "$", "");
}
@Override
public String escapeReservedWord(String name) {
@Override
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@@ -589,6 +592,10 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
@Override
public String toEnumVarName(String name, String datatype) {
if (name.length() == 0) {
return "EMPTY";
}
// for symbol, e.g. $, #
if (getSymbolName(name) != null) {
return (getSymbolName(name)).toUpperCase();

View File

@@ -67,7 +67,10 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
}
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}

View File

@@ -26,6 +26,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
protected String modelPropertyNaming= "camelCase";
protected Boolean supportsES6 = true;
protected HashSet<String> languageGenericTypes;
public AbstractTypeScriptClientCodegen() {
super();
@@ -58,6 +59,11 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
"any",
"Error"
));
languageGenericTypes = new HashSet<String>(Arrays.asList(
"Array"
));
instantiationTypes.put("array", "Array");
typeMapping = new HashMap<String, String>();
@@ -97,94 +103,96 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
}
if (additionalProperties.containsKey(CodegenConstants.SUPPORTS_ES6)) {
setSupportsES6(Boolean.valueOf((String)additionalProperties.get(CodegenConstants.SUPPORTS_ES6)));
setSupportsES6(Boolean.valueOf(additionalProperties.get(CodegenConstants.SUPPORTS_ES6).toString()));
additionalProperties.put("supportsES6", getSupportsES6());
}
}
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
@Override
public String modelFileFolder() {
return outputFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String modelFileFolder() {
return outputFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String toParamName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$"))
return name;
// camelize the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*"))
name = escapeReservedWord(name);
@Override
public String toParamName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$"))
return name;
// camelize the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*"))
name = escapeReservedWord(name);
return name;
}
@Override
public String toVarName(String name) {
// should be the same as variable name
return getNameUsingModelPropertyNaming(name);
}
@Override
public String toModelName(String name) {
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
@Override
public String toVarName(String name) {
// should be the same as variable name
return getNameUsingModelPropertyNaming(name);
}
@Override
public String toModelName(String name) {
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
String modelName = camelize("model_" + name);
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
// model name starts with number
if (name.matches("^\\d.*")) {
String modelName = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
if (languageSpecificPrimitives.contains(name)) {
String modelName = camelize("model_" + name);
LOGGER.warn(name + " (model name matches existing language type) cannot be used as a model name. Renamed to " + modelName);
return modelName;
}
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
String modelName = camelize("model_" + name);
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
// model name starts with number
if (name.matches("^\\d.*")) {
String modelName = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
if (languageSpecificPrimitives.contains(name)) {
String modelName = camelize("model_" + name);
LOGGER.warn(name + " (model name matches existing language type) cannot be used as a model name. Renamed to " + modelName);
return modelName;
}
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
@@ -280,6 +288,10 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
@Override
public String toEnumVarName(String name, String datatype) {
if (name.length() == 0) {
return "Empty";
}
// for symbol, e.g. $, #
if (getSymbolName(name) != null) {
return camelize(getSymbolName(name));

View File

@@ -154,6 +154,9 @@ public class AkkaScalaClientCodegen extends AbstractScalaCodegen implements Code
@Override
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "`" + name + "`";
}
@@ -228,7 +231,7 @@ public class AkkaScalaClientCodegen extends AbstractScalaCodegen implements Code
}
private String formatIdentifier(String name, boolean capitalized) {
String identifier = camelize(name, true);
String identifier = camelize(sanitizeName(name), true);
if (capitalized) {
identifier = StringUtils.capitalize(identifier);
}
@@ -287,6 +290,11 @@ public class AkkaScalaClientCodegen extends AbstractScalaCodegen implements Code
}
}
@Override
public String toModelName(final String name) {
return formatIdentifier(name, true);
}
private static abstract class CustomLambda implements Mustache.Lambda {
@Override
public void execute(Template.Fragment frag, Writer out) throws IOException {
@@ -298,7 +306,6 @@ public class AkkaScalaClientCodegen extends AbstractScalaCodegen implements Code
public abstract String formatFragment(String fragment);
}
private static class JavadocLambda extends CustomLambda {
@Override
public String formatFragment(String fragment) {

View File

@@ -119,7 +119,10 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
}
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@@ -390,7 +393,6 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
// need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string
additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel);
LOGGER.info("CodegenConstants.SERIALIZABLE_MODEL = " + additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL));
//make api and model doc path available in mustache template
additionalProperties.put( "apiDocPath", apiDocPath );

View File

@@ -14,9 +14,7 @@ import static java.util.UUID.randomUUID;
public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
protected String sourceFolder = "src" + File.separator + packageName;
private final String packageGuid = "{" + randomUUID().toString().toUpperCase() + "}";
private String packageGuid = "{" + randomUUID().toString().toUpperCase() + "}";
@SuppressWarnings("hiding")
protected Logger LOGGER = LoggerFactory.getLogger(AspNetCoreServerCodegen.class);
@@ -24,6 +22,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
public AspNetCoreServerCodegen() {
super();
setSourceFolder("src");
outputFolder = "generated-code" + File.separator + this.getName();
modelTemplateFiles.put("model.mustache", ".cs");
@@ -45,6 +44,10 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
"C# package version.",
this.packageVersion);
addOption(CodegenConstants.OPTIONAL_PROJECT_GUID,
CodegenConstants.OPTIONAL_PROJECT_GUID_DESC,
null);
addOption(CodegenConstants.SOURCE_FOLDER,
CodegenConstants.SOURCE_FOLDER_DESC,
sourceFolder);
@@ -86,43 +89,67 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_GUID)) {
setPackageGuid((String) additionalProperties.get(CodegenConstants.OPTIONAL_PROJECT_GUID));
}
additionalProperties.put("packageGuid", packageGuid);
additionalProperties.put("dockerTag", this.packageName.toLowerCase());
apiPackage = packageName + ".Controllers";
modelPackage = packageName + ".Models";
String packageFolder = sourceFolder + File.separator + packageName;
supportingFiles.add(new SupportingFile("NuGet.Config", "", "NuGet.Config"));
supportingFiles.add(new SupportingFile("global.json", "", "global.json"));
supportingFiles.add(new SupportingFile("build.sh.mustache", "", "build.sh"));
supportingFiles.add(new SupportingFile("build.bat.mustache", "", "build.bat"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("Solution.mustache", "", this.packageName + ".sln"));
supportingFiles.add(new SupportingFile("Dockerfile.mustache", this.sourceFolder, "Dockerfile"));
supportingFiles.add(new SupportingFile("gitignore", this.sourceFolder, ".gitignore"));
supportingFiles.add(new SupportingFile("appsettings.json", this.sourceFolder, "appsettings.json"));
supportingFiles.add(new SupportingFile("Dockerfile.mustache", packageFolder, "Dockerfile"));
supportingFiles.add(new SupportingFile("gitignore", packageFolder, ".gitignore"));
supportingFiles.add(new SupportingFile("appsettings.json", packageFolder, "appsettings.json"));
supportingFiles.add(new SupportingFile("project.json.mustache", this.sourceFolder, "project.json"));
supportingFiles.add(new SupportingFile("Startup.mustache", this.sourceFolder, "Startup.cs"));
supportingFiles.add(new SupportingFile("Program.mustache", this.sourceFolder, "Program.cs"));
supportingFiles.add(new SupportingFile("web.config", this.sourceFolder, "web.config"));
supportingFiles.add(new SupportingFile("project.json.mustache", packageFolder, "project.json"));
supportingFiles.add(new SupportingFile("Startup.mustache", packageFolder, "Startup.cs"));
supportingFiles.add(new SupportingFile("Program.mustache", packageFolder, "Program.cs"));
supportingFiles.add(new SupportingFile("web.config", packageFolder, "web.config"));
supportingFiles.add(new SupportingFile("Project.xproj.mustache", this.sourceFolder, this.packageName + ".xproj"));
supportingFiles.add(new SupportingFile("Project.xproj.mustache", packageFolder, this.packageName + ".xproj"));
supportingFiles.add(new SupportingFile("Properties" + File.separator + "launchSettings.json", this.sourceFolder + File.separator + "Properties", "launchSettings.json"));
supportingFiles.add(new SupportingFile("Properties" + File.separator + "launchSettings.json", packageFolder + File.separator + "Properties", "launchSettings.json"));
supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "README.md", this.sourceFolder + File.separator + "wwwroot", "README.md"));
supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "index.html", this.sourceFolder + File.separator + "wwwroot", "index.html"));
supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "web.config", this.sourceFolder + File.separator + "wwwroot", "web.config"));
supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "README.md", packageFolder + File.separator + "wwwroot", "README.md"));
supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "index.html", packageFolder + File.separator + "wwwroot", "index.html"));
supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "web.config", packageFolder + File.separator + "wwwroot", "web.config"));
}
@Override
public void setSourceFolder(final String sourceFolder) {
if(sourceFolder == null) {
LOGGER.warn("No sourceFolder specified, using default");
this.sourceFolder = "src" + File.separator + this.packageName;
} else if(!sourceFolder.equals("src") && !sourceFolder.startsWith("src")) {
LOGGER.warn("ASP.NET Core requires source code exists under src. Adjusting.");
this.sourceFolder = "src" + File.separator + sourceFolder;
} else {
this.sourceFolder = sourceFolder;
}
}
public void setPackageGuid(String packageGuid) {
this.packageGuid = packageGuid;
}
@Override
public String apiFileFolder() {
return outputFolder + File.separator + sourceFolder + File.separator + "Controllers";
return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + "Controllers";
}
@Override
public String modelFileFolder() {
return outputFolder + File.separator + sourceFolder + File.separator + "Models";
return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + "Models";
}
@Override

View File

@@ -60,7 +60,7 @@ public class AsyncScalaClientCodegen extends AbstractScalaCodegen implements Cod
importMapping.remove("Map");
importMapping.put("DateTime", "org.joda.time.DateTime");
importMapping.put("ListBuffer", "scala.collections.mutable.ListBuffer");
importMapping.put("ListBuffer", "scala.collection.mutable.ListBuffer");
typeMapping = new HashMap<String, String>();
typeMapping.put("enum", "NSString");
@@ -97,4 +97,10 @@ public class AsyncScalaClientCodegen extends AbstractScalaCodegen implements Cod
public String getHelp() {
return "Generates an Asynchronous Scala client library.";
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
}

View File

@@ -0,0 +1,658 @@
package io.swagger.codegen.languages;
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 java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String apiVersion = "1.0.0";
protected String curlOptions;
protected boolean processMarkdown = false;
protected String scriptName = "client.sh";
protected boolean generateBashCompletion = false;
protected boolean generateZshCompletion = false;
protected String hostEnvironmentVariable;
protected String basicAuthEnvironmentVariable;
protected String apiKeyAuthEnvironmentVariable;
public static final String CURL_OPTIONS = "curlOptions";
public static final String PROCESS_MARKDOWN = "processMarkdown";
public static final String SCRIPT_NAME = "scriptName";
public static final String
GENERATE_BASH_COMPLETION = "generateBashCompletion";
public static final String
GENERATE_ZSH_COMPLETION = "generateZshCompletion";
public static final String
HOST_ENVIRONMENT_VARIABLE_NAME = "hostEnvironmentVariable";
public static final String
BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME = "basicAuthEnvironmentVariable";
public static final String
APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME = "apiKeyAuthEnvironmentVariable";
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see io.swagger.codegen.CodegenType
*/
public CodegenType getTag() {
return CodegenType.CLIENT;
}
/**
* Configures a friendly name for the generator. This will be used by
* the generator to select the library with the -l flag.
*
* @return the friendly name for the generator
*/
public String getName() {
return "bash";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with
* help tips, parameters here
*
* @return A string value for the help message
*/
public String getHelp() {
return "Generates a Bash client script based on cURL.";
}
public BashClientCodegen() {
super();
/**
* Set the output folder here
*/
outputFolder = "generated-code/bash";
/**
* No model files.
*/
modelTemplateFiles.clear();
/**
* No API files.
*/
apiTemplateFiles.clear();
/**
* Templates location for client script and bash completion template.
*/
embeddedTemplateDir = templateDir = "bash";
/**
* Allow the user to force the script to always include certain cURL
* comamnds
*/
cliOptions.add(CliOption.newString(CURL_OPTIONS, "Default cURL options"));
cliOptions.add(CliOption.newBoolean(PROCESS_MARKDOWN,
"Convert all Markdown Markup into terminal formatting"));
cliOptions.add(CliOption.newString(SCRIPT_NAME,
"The name of the script that will be generated "+
"(e.g. petstore-cli)"));
cliOptions.add(CliOption.newBoolean(GENERATE_BASH_COMPLETION,
"Whether to generate the Bash completion script"));
cliOptions.add(CliOption.newBoolean(GENERATE_ZSH_COMPLETION,
"Whether to generate the Zsh completion script"));
cliOptions.add(CliOption.newString(HOST_ENVIRONMENT_VARIABLE_NAME,
"Name of environment variable where host can be defined "+
"(e.g. PETSTORE_HOST='http://petstore.swagger.io:8080')"));
cliOptions.add(CliOption.newString(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME,
"Name of environment variable where username and password "
+
"can be defined (e.g. PETSTORE_CREDS='username:password')"));
cliOptions.add(CliOption.newBoolean(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME,
"Name of environment variable where API key "
+
"can be defined (e.g. PETSTORE_APIKEY='kjhasdGASDa5asdASD')"));
/**
* Bash reserved words.
*/
reservedWords = new HashSet<String> (
Arrays.asList(
"case",
"do",
"done",
"elif",
"else",
"esac",
"fi",
"for",
"function",
"if",
"in",
"select",
"then",
"time",
"until",
"while")
);
typeMapping.clear();
typeMapping.put("array", "array");
typeMapping.put("map", "map");
typeMapping.put("List", "array");
typeMapping.put("boolean", "boolean");
typeMapping.put("string", "string");
typeMapping.put("int", "integer");
typeMapping.put("float", "float");
typeMapping.put("number", "integer");
typeMapping.put("DateTime", "string");
typeMapping.put("long", "integer");
typeMapping.put("short", "integer");
typeMapping.put("char", "string");
typeMapping.put("double", "float");
typeMapping.put("object", "map");
typeMapping.put("integer", "integer");
typeMapping.put("ByteArray", "string");
typeMapping.put("binary", "binary");
/**
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files.
*/
additionalProperties.put("apiVersion", apiVersion);
/**
* Language Specific Primitives. These types will not trigger imports by
* the client generator
*/
languageSpecificPrimitives = new HashSet<String>();
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(CURL_OPTIONS)) {
setCurlOptions(additionalProperties.get(CURL_OPTIONS).toString());
additionalProperties.put("x-codegen-curl-options", this.curlOptions);
}
if (additionalProperties.containsKey(PROCESS_MARKDOWN)) {
setProcessMarkdown(convertPropertyToBooleanAndWriteBack(PROCESS_MARKDOWN));
}
if (additionalProperties.containsKey(GENERATE_BASH_COMPLETION)) {
setGenerateBashCompletion(convertPropertyToBooleanAndWriteBack(GENERATE_BASH_COMPLETION));
}
if (additionalProperties.containsKey(GENERATE_ZSH_COMPLETION)) {
setGenerateZshCompletion(convertPropertyToBooleanAndWriteBack(GENERATE_ZSH_COMPLETION));
}
if (additionalProperties.containsKey(SCRIPT_NAME)) {
setScriptName(additionalProperties.get(SCRIPT_NAME).toString());
}
additionalProperties.put("x-codegen-script-name", scriptName);
if (additionalProperties.containsKey(HOST_ENVIRONMENT_VARIABLE_NAME)) {
setHostEnvironmentVariable(
additionalProperties.get(HOST_ENVIRONMENT_VARIABLE_NAME).toString());
additionalProperties.put("x-codegen-host-env", hostEnvironmentVariable);
}
if (additionalProperties.containsKey(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME)) {
setBasicAuthEnvironmentVariable(
additionalProperties.get(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME).toString());
additionalProperties.put("x-codegen-basicauth-env", basicAuthEnvironmentVariable);
}
if (additionalProperties.containsKey(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME)) {
setApiKeyAuthEnvironmentVariable(
additionalProperties.get(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME).toString());
additionalProperties.put("x-codegen-apikey-env", apiKeyAuthEnvironmentVariable);
}
supportingFiles.add(new SupportingFile(
"client.mustache", "", scriptName));
supportingFiles.add(new SupportingFile(
"bash-completion.mustache", "", scriptName+".bash-completion"));
supportingFiles.add(new SupportingFile(
"zsh-completion.mustache", "", "_"+scriptName));
supportingFiles.add(new SupportingFile(
"README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile(
"Dockerfile.mustache", "", "Dockerfile"));
}
public void setCurlOptions(String curlOptions) {
this.curlOptions = curlOptions;
}
public void setProcessMarkdown(boolean processMarkdown) {
this.processMarkdown = processMarkdown;
}
public void setScriptName(String scriptName) {
this.scriptName = scriptName;
}
public void setGenerateBashCompletion(boolean generateBashCompletion) {
this.generateBashCompletion = generateBashCompletion;
}
public void setGenerateZshCompletion(boolean generateZshCompletion) {
this.generateZshCompletion = generateZshCompletion;
}
public void setHostEnvironmentVariable(String hostEnvironmentVariable) {
this.hostEnvironmentVariable = hostEnvironmentVariable;
}
public void setBasicAuthEnvironmentVariable(String
basicAuthEnvironmentVariable) {
this.basicAuthEnvironmentVariable = basicAuthEnvironmentVariable;
}
public void setApiKeyAuthEnvironmentVariable(String
apiKeyAuthEnvironmentVariable) {
this.apiKeyAuthEnvironmentVariable = apiKeyAuthEnvironmentVariable;
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle
* escaping those terms here. This logic is only called if a variable
* matches the reseved words.
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
/**
* Location to write model files. You can use the modelPackage() as defined
* when the class is instantiated.
*/
public String modelFileFolder() {
return outputFolder;
}
/**
* Location to write api files. You can use the apiPackage() as defined when
* the class is instantiated.
*/
@Override
public String apiFileFolder() {
return outputFolder;
}
/**
* Optional - type declaration. This is a String which is used by the
* templates to instantiate your types. There is typically special handling
* for different property types
*
* @return a string value used as the `dataType` field for model templates,
* `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
}
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
/**
* Optional - swagger type conversion. This is used to map swagger types in
* a `Property` into either language specific types via `typeMapping` or into
* complex models if there is not a mapping.
*
* @return a string value of the type or complex model for this property
* @see io.swagger.models.properties.Property
*/
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if(typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type))
return type;
}
else
type = swaggerType;
return toModelName(type);
}
/**
* Convert Swagger Parameter object to Codegen Parameter object
*
* @param param Swagger parameter object
* @param imports set of imports for library/package/module
* @return Codegen Parameter object
*/
@Override
public CodegenParameter fromParameter(Parameter param, Set<String> imports) {
CodegenParameter p = super.fromParameter(param, imports);
if(param instanceof BodyParameter) {
Model model = ((BodyParameter)param).getSchema();
}
else if(param instanceof SerializableParameter) {
/**
* Currently it's not possible to specify in the codegen other collection
* formats than 'multi'
*/
SerializableParameter sparam = (SerializableParameter)param;
if( sparam.getCollectionFormat() != null
&& !sparam.getCollectionFormat().isEmpty()) {
String collectionFormat = sparam.getCollectionFormat();
if(sparam.isExclusiveMaximum()!=null && sparam.isExclusiveMaximum()) {
p.vendorExtensions.put("x-codegen-collection-max-items",
sparam.getMaxItems());
}
if(sparam.isExclusiveMinimum()!=null && sparam.isExclusiveMinimum()) {
p.vendorExtensions.put("x-codegen-collection-min-items",
sparam.getMinItems());
}
if( (collectionFormat.equals("multi"))
&& (param.getIn().equals("query")) ) {
/**
* 'multi' is only supported for query parameters
*/
p.vendorExtensions.put("x-codegen-collection-multi", true);
}
else if(collectionFormat.equals("csv")) {
p.vendorExtensions.put("x-codegen-collection-csv", true);
}
else if(collectionFormat.equals("ssv")) {
p.vendorExtensions.put("x-codegen-collection-ssv", true);
}
else if(collectionFormat.equals("tsv")) {
p.vendorExtensions.put("x-codegen-collection-tsv", true);
}
else if(collectionFormat.equals("pipes")) {
p.vendorExtensions.put("x-codegen-collection-pipes", true);
}
else {
/** Unsupported collection format */
}
}
}
return p;
}
/**
* Override with any special text escaping logic
*/
@SuppressWarnings("static-method")
public String escapeText(String input) {
if (input == null) {
return input;
}
/**
* Trim the input text always.
*/
String result = input.trim();
/**
* remove standalone '\'
*
* replace " with \"
* outter unescape to retain the original multi-byte characters
*/
result = escapeUnsafeCharacters(
StringEscapeUtils.unescapeJava(
StringEscapeUtils.escapeJava(result).replace("\\/", "/"))
.replace("\\", "\\\\")
.replace("\"", "\\\""));
if(this.processMarkdown) {
/**
* Convert markdown strong **Bold text** and __Bold text__
* to bash bold control sequences (tput bold)
*/
result = result.replaceAll("(?m)(^|\\s)\\*{2}([\\w\\d ]+)\\*{2}($|\\s)",
"\\$\\(tput bold\\) $2 \\$\\(tput sgr0\\)");
result = result.replaceAll("(?m)(^|\\s)_{2}([\\w\\d ]+)_{2}($|\\s)",
"\\$\\(tput bold\\) $2 \\$\\(tput sgr0\\)");
/**
* Convert markdown *Italics text* and _Italics text_ to bash dim
* control sequences (tput dim)
*/
result = result.replaceAll("(?m)(^|\\s)\\*{1}([\\w\\d ]+)\\*{1}($|\\s)",
"\\$\\(tput dim\\) $2 \\$\\(tput sgr0\\)");
result = result.replaceAll("(?m)(^|\\s)_{1}([\\w\\d ]+)_{1}($|\\s)",
"\\$\\(tput dim\\) $2 \\$\\(tput sgr0\\)");
/**
* Convert all markdown section 1 level headers with bold
*/
result = result.replaceAll("(?m)^\\#\\s+(.+)$",
"\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)"
+"$1\\$\\(tput sgr0\\)");
/**
* Convert all markdown section 2 level headers with bold
*/
result = result.replaceAll("(?m)^\\#\\#\\s+(.+)$",
"\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)"
+"$1\\$\\(tput sgr0\\)");
/**
* Convert all markdown section 3 level headers with bold
*/
result = result.replaceAll("(?m)^\\#\\#\\#\\s+(.+)$",
"\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)"
+"$1\\$\\(tput sgr0\\)");
/**
* Convert all markdown code blocks into --- delimited sections
*/
result = result.replaceAll("(?m)\\s*```.*$",
"\n---");
result = result.replaceAll("(?m)\\s*\\'\\'\\'.*$",
"\n---");
/**
* Remove any trailing new line at the end of the string
*/
result = result.replaceAll("\\s+$", "");
}
return result;
}
@Override
public String escapeQuotationMark(String input) {
return input;
}
/**
* Override with any special text escaping logic to handle unsafe
* characters so as to avoid code injection.
*
* @param input String to be cleaned up
* @return string with unsafe characters removed or escaped
*/
public String escapeUnsafeCharacters(String input) {
/**
* Replace backticks with normal single quotes.
*/
String result = input.replaceAll("`", "'");
return result;
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod,
Operation operation,
Map<String, Model> definitions,
Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation,
definitions, swagger);
/**
* Check if the operation has a Bash codegen specific description
* for help
*/
if(op.vendorExtensions.containsKey("x-bash-codegen-description")) {
String bash_description
= (String)op.vendorExtensions.get("x-bash-codegen-description");
op.vendorExtensions.put("x-bash-codegen-description",
escapeText(bash_description));
}
/**
* Check if operation has an 'x-code-samples' vendor extension with
* Shell example
*/
if(op.vendorExtensions.containsKey("x-code-samples")) {
List codesamples = (List)op.vendorExtensions.get("x-code-samples");
for (Object codesample : codesamples) {
if(codesample instanceof ObjectNode) {
ObjectNode codesample_object = (ObjectNode) codesample;
if ((codesample_object.get("lang").asText()).equals("Shell")) {
op.vendorExtensions.put("x-bash-codegen-sample",
escapeUnsafeCharacters(
codesample_object.get("source").asText()));
}
}
}
}
for (CodegenParameter p : op.bodyParams) {
if(p.dataType != null && definitions.get(p.dataType) != null) {
/**
* If the operation produces Json and has nonempty example
* try to reformat it.
*/
if(operation.getConsumes() != null
&& operation.getConsumes().contains("application/json")
&& definitions.get(p.dataType).getExample() != null) {
ObjectMapper mapper = new ObjectMapper();
try {
p.vendorExtensions.put(
"x-codegen-body-example",
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(
definitions.get(p.dataType).getExample()));
}
catch(JsonProcessingException e) {
e.printStackTrace();
}
}
else {
/**
* Otherwise present whatever is provided as example
*/
p.vendorExtensions.put(
"x-codegen-body-example",
definitions.get(p.dataType).getExample());
}
}
}
return op;
}
/**
* Preprocess original properties from the Swagger definition where necessary.
*
* @param swagger [description]
*/
@Override
public void preprocessSwagger(Swagger swagger) {
super.preprocessSwagger(swagger);
if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath("");
}
if(swagger.getInfo() != null
&& swagger.getInfo().getVendorExtensions()!=null) {
String bash_codegen_app_description
= (String)swagger.getInfo().getVendorExtensions()
.get("x-bash-codegen-description");
if(bash_codegen_app_description != null) {
bash_codegen_app_description
= escapeText(bash_codegen_app_description);
additionalProperties.put("x-bash-codegen-app-description",
bash_codegen_app_description);
}
}
}
}

View File

@@ -1,6 +1,9 @@
package io.swagger.codegen.languages;
import com.google.common.collect.ImmutableMap;
import com.sun.org.apache.bcel.internal.classfile.Code;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.CodegenModel;
@@ -28,6 +31,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class);
private static final String NET45 = "v4.5";
private static final String NET35 = "v3.5";
private static final String NETSTANDARD = "v5.0";
private static final String UWP = "uwp";
private static final String DATA_TYPE_WITH_ENUM_EXTENSION = "plainDatatypeWithEnum";
@@ -41,10 +45,14 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
protected String targetFrameworkNuget = "net45";
protected boolean supportsAsync = Boolean.TRUE;
protected boolean supportsUWP = Boolean.FALSE;
protected boolean netStandard = Boolean.FALSE;
protected boolean generatePropertyChanged = Boolean.FALSE;
protected Map<Character, String> regexModifiers;
protected final Map<String, String> frameworks;
// By default, generated code is considered public
protected boolean nonPublicApi = Boolean.FALSE;
public CSharpClientCodegen() {
super();
modelTemplateFiles.put("model.mustache", ".cs");
@@ -72,6 +80,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
CodegenConstants.OPTIONAL_PROJECT_GUID_DESC,
null);
addOption(CodegenConstants.INTERFACE_PREFIX,
CodegenConstants.INTERFACE_PREFIX_DESC,
interfacePrefix);
CliOption framework = new CliOption(
CodegenConstants.DOTNET_FRAMEWORK,
CodegenConstants.DOTNET_FRAMEWORK_DESC
@@ -79,7 +91,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
frameworks = new ImmutableMap.Builder<String, String>()
.put(NET35, ".NET Framework 3.5 compatible")
.put(NET45, ".NET Framework 4.5+ compatible")
.put(UWP, "Universal Windows Platform - beta support")
.put(NETSTANDARD, ".NET Standard 1.3 compatible")
.put(UWP, "Universal Windows Platform (IMPORTANT: this will be decommissioned and replaced by v5.0)")
.build();
framework.defaultValue(this.targetFramework);
framework.setEnum(frameworks);
@@ -126,6 +139,18 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
CodegenConstants.PACKAGE_DESCRIPTION_DESC,
this.generatePropertyChanged);
// NOTE: This will reduce visibility of all public members in templates. Users can use InternalsVisibleTo
// https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx
// to expose to shared code if the generated code is not embedded into another project. Otherwise, users of codegen
// should rely on default public visibility.
addSwitch(CodegenConstants.NON_PUBLIC_API,
CodegenConstants.NON_PUBLIC_API_DESC,
this.nonPublicApi);
addSwitch(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS,
CodegenConstants.ALLOW_UNICODE_IDENTIFIERS_DESC,
this.allowUnicodeIdentifiers);
regexModifiers = new HashMap<Character, String>();
regexModifiers.put('i', "IgnoreCase");
regexModifiers.put('m', "Multiline");
@@ -180,6 +205,22 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
if(additionalProperties.containsKey("supportsAsync")){
additionalProperties.remove("supportsAsync");
}
} else if (NETSTANDARD.equals(this.targetFramework)){
setTargetFrameworkNuget("netstandard1.3");
setSupportsAsync(Boolean.TRUE);
setSupportsUWP(Boolean.FALSE);
setNetStandard(Boolean.TRUE);
additionalProperties.put("supportsAsync", this.supportsAsync);
additionalProperties.put("supportsUWP", this.supportsUWP);
additionalProperties.put("netStandard", this.netStandard);
//Tests not yet implemented for .NET Standard codegen
//Todo implement it
excludeTests = true;
if(additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)){
additionalProperties.remove(CodegenConstants.EXCLUDE_TESTS);
}
additionalProperties.put(CodegenConstants.EXCLUDE_TESTS, excludeTests);
} else if (UWP.equals(this.targetFramework)){
setTargetFrameworkNuget("uwp");
setSupportsAsync(Boolean.TRUE);
@@ -196,9 +237,15 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
if(additionalProperties.containsKey(CodegenConstants.GENERATE_PROPERTY_CHANGED)) {
if(NET35.equals(targetFramework)) {
LOGGER.warn(CodegenConstants.GENERATE_PROPERTY_CHANGED + " is only supported by generated code for .NET 4+.");
} else if(NETSTANDARD.equals(targetFramework)) {
LOGGER.warn(CodegenConstants.GENERATE_PROPERTY_CHANGED + " is not supported in .NET Standard generated code.");
} else {
setGeneratePropertyChanged(Boolean.valueOf(additionalProperties.get(CodegenConstants.GENERATE_PROPERTY_CHANGED).toString()));
}
if(Boolean.FALSE.equals(this.generatePropertyChanged)) {
additionalProperties.remove(CodegenConstants.GENERATE_PROPERTY_CHANGED);
}
}
additionalProperties.put("targetFrameworkNuget", this.targetFrameworkNuget);
@@ -224,6 +271,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
.get(CodegenConstants.OPTIONAL_ASSEMBLY_INFO).toString()));
}
if (additionalProperties.containsKey(CodegenConstants.NON_PUBLIC_API)) {
setNonPublicApi(Boolean.valueOf(additionalProperties.get(CodegenConstants.NON_PUBLIC_API).toString()));
}
final String testPackageName = testPackageName();
String packageFolder = sourceFolder + File.separator + packageName;
String clientPackageDir = packageFolder + File.separator + clientPackage;
@@ -252,14 +303,17 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
clientPackageDir, "ApiResponse.cs"));
supportingFiles.add(new SupportingFile("ExceptionFactory.mustache",
clientPackageDir, "ExceptionFactory.cs"));
if(Boolean.FALSE.equals(this.netStandard)) {
supportingFiles.add(new SupportingFile("compile.mustache", "", "build.bat"));
supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "build.sh"));
supportingFiles.add(new SupportingFile("compile.mustache", "", "build.bat"));
supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "build.sh"));
// copy package.config to nuget's standard location for project-level installs
supportingFiles.add(new SupportingFile("packages.config.mustache", packageFolder + File.separator, "packages.config"));
// .travis.yml for travis-ci.org CI
supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml"));
// copy package.config to nuget's standard location for project-level installs
supportingFiles.add(new SupportingFile("packages.config.mustache", packageFolder + File.separator, "packages.config"));
// .travis.yml for travis-ci.org CI
supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml"));
} else {
supportingFiles.add(new SupportingFile("project.json.mustache", packageFolder + File.separator, "project.json"));
}
// Only write out test related files if excludeTests is unset or explicitly set to false (see start of this method)
if(Boolean.FALSE.equals(excludeTests)) {
@@ -289,6 +343,9 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
if (optionalProjectFileFlag) {
supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln"));
supportingFiles.add(new SupportingFile("Project.mustache", packageFolder, packageName + ".csproj"));
if(Boolean.FALSE.equals(this.netStandard)) {
supportingFiles.add(new SupportingFile("nuspec.mustache", packageFolder, packageName + ".nuspec"));
}
if(Boolean.FALSE.equals(excludeTests)) {
// NOTE: This exists here rather than previous excludeTests block because the test project is considered an optional project file.
@@ -368,7 +425,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objMap) {
return super.postProcessModels(objMap);
return super.postProcessModels(objMap);
}
@Override
@@ -490,6 +547,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
@Override
public String toEnumVarName(String value, String datatype) {
if (value.length() == 0) {
return "Empty";
}
// for symbol, e.g. $, #
if (getSymbolName(value) != null) {
return camelize(getSymbolName(value));
@@ -539,10 +600,22 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
this.supportsUWP = supportsUWP;
}
public void setNetStandard(Boolean netStandard){
this.netStandard = netStandard;
}
public void setGeneratePropertyChanged(final Boolean generatePropertyChanged){
this.generatePropertyChanged = generatePropertyChanged;
}
public boolean isNonPublicApi() {
return nonPublicApi;
}
public void setNonPublicApi(final boolean nonPublicApi) {
this.nonPublicApi = nonPublicApi;
}
@Override
public String toModelDocFilename(String name) {
return toModelFilename(name);

View File

@@ -62,7 +62,7 @@ public class CppRestClientCodegen extends DefaultCodegen implements CodegenConfi
apiTemplateFiles.put("api-header.mustache", ".h");
apiTemplateFiles.put("api-source.mustache", ".cpp");
templateDir = "cpprest";
embeddedTemplateDir = templateDir = "cpprest";
cliOptions.clear();
@@ -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

@@ -10,6 +10,8 @@ import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.codegen.CliOption;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
@@ -21,6 +23,9 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
protected String packageVersion = "1.0.0";
protected String clientPackage = "IO.Swagger.Client";
protected String sourceFolder = "src" + File.separator + "main" + File.separator + "CsharpDotNet2";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
public CsharpDotNet2ClientCodegen() {
super();
@@ -35,6 +40,8 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
embeddedTemplateDir = templateDir = "CsharpDotNet2";
apiPackage = "IO.Swagger.Api";
modelPackage = "IO.Swagger.Model";
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
setReservedWordsLowerCase(
Arrays.asList(
@@ -65,6 +72,7 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
"Integer",
"Long",
"Float",
"Guid?",
"System.IO.Stream", // not really a primitive, we include it to avoid model import
"Object")
);
@@ -86,6 +94,7 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
typeMapping.put("list", "List");
typeMapping.put("map", "Dictionary");
typeMapping.put("object", "Object");
typeMapping.put("uuid", "Guid?");
cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name (convention: Camel.Case).")
@@ -120,6 +129,9 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
additionalProperties.put(CLIENT_PACKAGE, clientPackage);
}
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
supportingFiles.add(new SupportingFile("Configuration.mustache",
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs"));
supportingFiles.add(new SupportingFile("ApiClient.mustache",
@@ -128,7 +140,7 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiException.cs"));
supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor", "packages.config"));
supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh"));
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
}
@@ -160,7 +172,10 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
}
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@@ -220,11 +235,26 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
@Override
public String toModelName(String name) {
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
name = sanitizeName(name);
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("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 " + camelize("model_" + name));
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
}
// camelize the model name
@@ -271,12 +301,18 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
// throw exception if method name is empty (should not occur as an auto-generated method name will be used)
if (StringUtils.isEmpty(operationId)) {
throw new RuntimeException("Empty method name (operationId) not allowed");
}
return camelize(operationId);
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(operationId)) {
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId)));
operationId = "call_" + operationId;
}
return camelize(sanitizeName(operationId));
}
@Override
@@ -290,4 +326,14 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
return input.replace("*/", "*_/").replace("/*", "/_*");
}
@Override
public String apiDocFileFolder() {
return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar);
}
@Override
public String modelDocFileFolder() {
return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar);
}
}

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);
@@ -174,7 +181,10 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}

View File

@@ -0,0 +1,389 @@
package io.swagger.codegen.languages;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.codegen.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig {
// source folder where to write the files
protected String sourceFolder = "lib";
protected String apiVersion = "1.0.0";
String supportedElixirVersion = "1.4";
List<String> extraApplications = Arrays.asList(":logger");
List<String> deps = Arrays.asList(
"{:tesla, \"~> 0.5.0\"}",
"{:poison, \">= 1.0.0\"}"
);
public ElixirClientCodegen() {
super();
// set the output folder here
outputFolder = "generated-code/elixir";
/**
* Models. You can write model files using the modelTemplateFiles map.
* if you want to create one template for file, you can do so here.
* for multiple files for model, just put another entry in the `modelTemplateFiles` with
* a different extension
*/
modelTemplateFiles.put(
"model.mustache", // the template to use
".ex"); // the extension for each file to write
/**
* Api classes. You can write classes for each Api file with the apiTemplateFiles map.
* as with models, add multiple entries with different extensions for multiple files per
* class
*/
apiTemplateFiles.put(
"api.mustache", // the template to use
".ex"); // the extension for each file to write
/**
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
templateDir = "elixir";
/**
* Reserved words. Override this with reserved words specific to your language
*/
reservedWords = new HashSet<String>(
Arrays.asList(
"sample1", // replace with static values
"sample2")
);
/**
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
*/
additionalProperties.put("apiVersion", apiVersion);
/**
* Supporting Files. You can write single files for the generator with the
* entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied
*/
supportingFiles.add(new SupportingFile("README.md.mustache", // the input template or file
"", // the destination folder, relative `outputFolder`
"README.md") // the output file
);
supportingFiles.add(new SupportingFile("config.exs.mustache",
"config",
"config.exs")
);
supportingFiles.add(new SupportingFile("mix.exs.mustache",
"",
"mix.exs")
);
supportingFiles.add(new SupportingFile("test_helper.exs.mustache",
"test",
"test_helper.exs")
);
/**
* Language Specific Primitives. These types will not trigger imports by
* the client generator
*/
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"Type1", // replace these with your types
"Type2")
);
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see io.swagger.codegen.CodegenType
*/
public CodegenType getTag() {
return CodegenType.CLIENT;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -l flag.
*
* @return the friendly name for the generator
*/
public String getName() {
return "elixir";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
public String getHelp() {
return "Generates an elixir client library (alpha).";
}
@Override
public void processOpts() {
super.processOpts();
additionalProperties.put("supportedElixirVersion", supportedElixirVersion);
additionalProperties.put("extraApplications", join(",", extraApplications));
additionalProperties.put("deps", deps);
additionalProperties.put("underscored", new Mustache.Lambda() {
@Override
public void execute(Template.Fragment fragment, Writer writer) throws IOException {
writer.write(underscored(fragment.execute()));
}
});
additionalProperties.put("modulized", new Mustache.Lambda() {
@Override
public void execute(Template.Fragment fragment, Writer writer) throws IOException {
writer.write(modulized(fragment.execute()));
}
});
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) super.postProcessOperations(objs).get("operations");
List<CodegenOperation> os = (List<CodegenOperation>) operations.get("operation");
List<ExtendedCodegenOperation> newOs = new ArrayList<ExtendedCodegenOperation>();
Pattern pattern = Pattern.compile("(.*)\\{([^\\}]+)\\}(.*)");
for (CodegenOperation o : os) {
ArrayList<String> pathTemplateNames = new ArrayList<String>();
Matcher matcher = pattern.matcher(o.path);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
String pathTemplateName = matcher.group(2);
matcher.appendReplacement(buffer, "$1" + "#{" + underscore(pathTemplateName) + "}" + "$3");
pathTemplateNames.add(pathTemplateName);
}
ExtendedCodegenOperation eco = new ExtendedCodegenOperation(o);
if (buffer.toString().isEmpty()) {
eco.setReplacedPathName(o.path);
} else {
eco.setReplacedPathName(buffer.toString());
}
eco.setPathTemplateNames(pathTemplateNames);
newOs.add(eco);
}
operations.put("operation", newOs);
return objs;
}
// We should use String.join if we can use Java8
String join(CharSequence charSequence, Iterable<String> iterable) {
StringBuilder buf = new StringBuilder();
for (String str : iterable) {
if (0 < buf.length()) {
buf.append((charSequence));
}
buf.append(str);
}
return buf.toString();
}
String underscored(String words) {
ArrayList<String> underscoredWords = new ArrayList<String>();
for (String word : words.split(" ")) {
underscoredWords.add(underscore(word));
}
return join("_", underscoredWords);
}
String modulized(String words) {
ArrayList<String> modulizedWords = new ArrayList<String>();
for (String word : words.split(" ")) {
modulizedWords.add(camelize(word));
}
return join("", modulizedWords);
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reseved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
/**
* Location to write model files. You can use the modelPackage() as defined when the class is
* instantiated
*/
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + underscored((String) additionalProperties.get("appName")) + "/" + "model";
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
@Override
public String apiFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + underscored((String) additionalProperties.get("appName")) + "/" + "api";
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "Default";
}
return initialCaps(name);
}
@Override
public String toApiFilename(String name) {
return snakeCase(name);
}
@Override
public String toModelFilename(String name) {
return snakeCase(name);
}
/**
* Optional - type declaration. This is a String which is used by the templates to instantiate your
* types. There is typically special handling for different property types
*
* @return a string value used as the `dataType` field for model templates, `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
/**
* Optional - swagger type conversion. This is used to map swagger types in a `Property` into
* either language specific types via `typeMapping` or into complex models if there is not a mapping.
*
* @return a string value of the type or complex model for this property
* @see io.swagger.models.properties.Property
*/
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type))
return toModelName(type);
} else
type = swaggerType;
return toModelName(type);
}
class ExtendedCodegenOperation extends CodegenOperation {
private List<String> pathTemplateNames = new ArrayList<String>();
private String replacedPathName;
public ExtendedCodegenOperation(CodegenOperation o) {
super();
// Copy all fields of CodegenOperation
this.responseHeaders.addAll(o.responseHeaders);
this.hasAuthMethods = o.hasAuthMethods;
this.hasConsumes = o.hasConsumes;
this.hasProduces = o.hasProduces;
this.hasParams = o.hasParams;
this.hasOptionalParams = o.hasOptionalParams;
this.returnTypeIsPrimitive = o.returnTypeIsPrimitive;
this.returnSimpleType = o.returnSimpleType;
this.subresourceOperation = o.subresourceOperation;
this.isMapContainer = o.isMapContainer;
this.isListContainer = o.isListContainer;
this.isMultipart = o.isMultipart;
this.hasMore = o.hasMore;
this.isResponseBinary = o.isResponseBinary;
this.hasReference = o.hasReference;
this.isRestfulIndex = o.isRestfulIndex;
this.isRestfulShow = o.isRestfulShow;
this.isRestfulCreate = o.isRestfulCreate;
this.isRestfulUpdate = o.isRestfulUpdate;
this.isRestfulDestroy = o.isRestfulDestroy;
this.isRestful = o.isRestful;
this.path = o.path;
this.operationId = o.operationId;
this.returnType = o.returnType;
this.httpMethod = o.httpMethod;
this.returnBaseType = o.returnBaseType;
this.returnContainer = o.returnContainer;
this.summary = o.summary;
this.unescapedNotes = o.unescapedNotes;
this.notes = o.notes;
this.baseName = o.baseName;
this.defaultResponse = o.defaultResponse;
this.discriminator = o.discriminator;
this.consumes = o.consumes;
this.produces = o.produces;
this.bodyParam = o.bodyParam;
this.allParams = o.allParams;
this.bodyParams = o.bodyParams;
this.pathParams = o.pathParams;
this.queryParams = o.queryParams;
this.headerParams = o.headerParams;
this.formParams = o.formParams;
this.authMethods = o.authMethods;
this.tags = o.tags;
this.responses = o.responses;
this.imports = o.imports;
this.examples = o.examples;
this.externalDocs = o.externalDocs;
this.vendorExtensions = o.vendorExtensions;
this.nickname = o.nickname;
this.operationIdLowerCase = o.operationIdLowerCase;
this.operationIdCamelCase = o.operationIdCamelCase;
}
public List<String> getPathTemplateNames() {
return pathTemplateNames;
}
public void setPathTemplateNames(List<String> pathTemplateNames) {
this.pathTemplateNames = pathTemplateNames;
}
public String getReplacedPathName() {
return replacedPathName;
}
public void setReplacedPathName(String replacedPathName) {
this.replacedPathName = replacedPathName;
}
}
@Override
public String escapeQuotationMark(String input) {
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
// no need to escape as Elixir does not support multi-line comments
return input;
}
}

View File

@@ -182,8 +182,11 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return name + "_"; // add an underscore to the name
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
/**
@@ -233,7 +236,7 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig
Swagger swagger = (Swagger)objs.get("swagger");
if(swagger != null) {
try {
objs.put("swagger-json", Json.mapper().writeValueAsString(swagger));
objs.put("swagger-json", Json.pretty().writeValueAsString(swagger).replace("\r\n", "\n"));
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}

View File

@@ -0,0 +1,320 @@
package io.swagger.codegen.languages;
import com.google.common.base.Strings;
import io.swagger.codegen.*;
import io.swagger.models.Model;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class FinchServerCodegen extends DefaultCodegen implements CodegenConfig {
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";
public FinchServerCodegen() {
super();
outputFolder = "generated-code/finch";
modelTemplateFiles.put("model.mustache", ".scala");
apiTemplateFiles.put("api.mustache", ".scala");
embeddedTemplateDir = templateDir = "finch";
apiPackage = packageName + ".apis";
modelPackage = packageName + ".models";
setReservedWordsLowerCase(
Arrays.asList(
// Scala
"abstract", "case", "catch", "class", "def",
"do", "else", "extends", "false", "final",
"finally", "for", "forSome", "if", "implicit",
"import", "lazy", "match", "new", "null",
"object", "override", "package", "private", "protected",
"return", "sealed", "super", "this", "throw",
"trait", "try", "true", "type", "val",
"var", "while", "with", "yield",
// Scala-interop languages keywords
"abstract", "continue", "switch", "assert",
"default", "synchronized", "goto",
"break", "double", "implements", "byte",
"public", "throws", "enum", "instanceof", "transient",
"int", "short", "char", "interface", "static",
"void", "finally", "long", "strictfp", "volatile", "const", "float",
"native")
);
defaultIncludes = new HashSet<String>(
Arrays.asList("double",
"Int",
"Long",
"Float",
"Double",
"char",
"float",
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"List",
"Set",
"Map")
);
typeMapping = new HashMap<String, String>();
typeMapping.put("string", "String");
typeMapping.put("boolean", "Boolean");
typeMapping.put("integer", "Int");
typeMapping.put("float", "Float");
typeMapping.put("long", "Long");
typeMapping.put("double", "Double");
typeMapping.put("number", "BigDecimal");
typeMapping.put("date-time", "LocalDateTime");
typeMapping.put("date", "LocalDateTime");
typeMapping.put("file", "File");
typeMapping.put("array", "Seq");
typeMapping.put("list", "List");
typeMapping.put("map", "Map");
typeMapping.put("object", "Object");
typeMapping.put("binary", "Array[Byte]");
typeMapping.put("Date", "LocalDateTime");
typeMapping.put("DateTime", "LocalDateTime");
additionalProperties.put("modelPackage", modelPackage());
additionalProperties.put("apiPackage", apiPackage());
additionalProperties.put("appName", "Swagger Sample");
additionalProperties.put("appDescription", "A sample swagger server");
additionalProperties.put("infoUrl", "http://swagger.io");
additionalProperties.put("infoEmail", "apiteam@swagger.io");
additionalProperties.put("licenseInfo", "Apache 2.0");
additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html");
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
} else {
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
}
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt"));
supportingFiles.add(new SupportingFile("Server.mustache", sourceFolder, "Server.scala"));
supportingFiles.add(new SupportingFile("DataAccessor.mustache", sourceFolder, "DataAccessor.scala"));
supportingFiles.add(new SupportingFile("project/build.properties", "project", "build.properties"));
supportingFiles.add(new SupportingFile("project/plugins.sbt", "project", "plugins.sbt"));
supportingFiles.add(new SupportingFile("sbt", "", "sbt"));
supportingFiles.add(new SupportingFile("endpoint.mustache", sourceFolder, "endpoint.scala"));
supportingFiles.add(new SupportingFile("errors.mustache", sourceFolder, "errors.scala"));
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"String",
"Boolean",
"Double",
"Int",
"Integer",
"Long",
"Float",
"Any",
"AnyVal",
"AnyRef",
"Object")
);
instantiationTypes.put("array", "ArrayList");
instantiationTypes.put("map", "HashMap");
importMapping = new HashMap<String, String>();
importMapping.put("BigDecimal", "java.math.BigDecimal");
importMapping.put("UUID", "java.util.UUID");
importMapping.put("File", "java.io.File");
importMapping.put("Date", "java.util.Date");
importMapping.put("Timestamp", "java.sql.Timestamp");
importMapping.put("Map", "scala.collection.immutable.Map");
importMapping.put("HashMap", "scala.collection.immutable.HashMap");
importMapping.put("Seq", "scala.collection.immutable.Seq");
importMapping.put("ArrayBuffer", "scala.collection.mutable.ArrayBuffer");
importMapping.put("DateTime", "java.time.LocalDateTime");
importMapping.put("LocalDateTime", "java.time.LocalDateTime");
importMapping.put("LocalDate", "java.time.LocalDate");
importMapping.put("LocalTime", "java.time.LocalTime");
cliOptions.clear();
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));
}
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
@Override
public String getName() {
return "finch";
}
@Override
public String getHelp() {
return "Generates a Scala server application with Finch.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
@Override
public String modelFileFolder() {
return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar);
}
/**
* Convert Swagger Model object to Codegen Model object
*
* @param name the name of the model
* @param model Swagger Model object
* @param allDefinitions a map of all Swagger models from the spec
* @return Codegen Model object
*/
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
return codegenModel;
}
@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();
String path = new String(op.path);
// remove first /
if (path.startsWith("/")) {
path = path.substring(1);
}
// remove last /
if (path.endsWith("/")) {
path = path.substring(0, path.length()-1);
}
String[] items = path.split("/", -1);
String scalaPath = "";
int pathParamIndex = 0;
for (int i = 0; i < items.length; ++i) {
if (items[i].matches("^\\{(.*)\\}$")) { // wrap in {}
// find the datatype of the parameter
final CodegenParameter cp = op.pathParams.get(pathParamIndex);
// TODO: Handle non-primitives…
scalaPath = scalaPath + cp.dataType.toLowerCase();
pathParamIndex++;
} else {
scalaPath = scalaPath + "\"" + items[i] + "\"";
}
if (i != items.length -1) {
scalaPath = scalaPath + " :: ";
}
}
for (CodegenParameter p : op.allParams) {
// TODO: This hacky, should be converted to mappings if possible to keep it clean.
// This could also be done using template imports
if(Boolean.TRUE.equals(p.isPrimitiveType)) {
p.vendorExtensions.put("x-codegen-normalized-path-type", p.dataType.toLowerCase());
p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType);
} else if(Boolean.TRUE.equals(p.isBodyParam)) {
p.vendorExtensions.put("x-codegen-normalized-path-type", "jsonBody["+ p.dataType + "]");
p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType);
} else if(Boolean.TRUE.equals(p.isContainer) || Boolean.TRUE.equals(p.isListContainer)) {
p.vendorExtensions.put("x-codegen-normalized-path-type", "params(\""+ p.paramName + "\")");
p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType.replaceAll("^[^\\[]+", "Seq"));
} else if(Boolean.TRUE.equals(p.isFile)) {
p.vendorExtensions.put("x-codegen-normalized-path-type", "fileUpload(\""+ p.paramName + "\")");
p.vendorExtensions.put("x-codegen-normalized-input-type", "FileUpload");
} else {
p.vendorExtensions.put("x-codegen-normalized-path-type", p.dataType);
p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType);
}
}
op.vendorExtensions.put("x-codegen-path", scalaPath);
}
return objs;
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
} else {
type = swaggerType;
}
return toModelName(type);
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
}

View File

@@ -177,8 +177,11 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
}
@Override
public String escapeReservedWord(String name) {
return name + "_";
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@Override

View File

@@ -34,6 +34,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
protected String packageVersion;
protected String controllerPackage;
protected String defaultController;
protected Map<Character, String> regexModifiers;
public FlaskConnexionCodegen() {
super();
@@ -50,6 +51,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");
@@ -106,6 +108,16 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml"));
supportingFiles.add(new SupportingFile("Dockerfile.mustache", "", "Dockerfile"));
supportingFiles.add(new SupportingFile("dockerignore.mustache", "", ".dockerignore"));
regexModifiers = new HashMap<Character, String>();
regexModifiers.put('i', "IGNORECASE");
regexModifiers.put('l', "LOCALE");
regexModifiers.put('m', "MULTILINE");
regexModifiers.put('s', "DOTALL");
regexModifiers.put('u', "UNICODE");
regexModifiers.put('x', "VERBOSE");
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case).")
.defaultValue("swagger_server"));
@@ -236,10 +248,13 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name; // add an underscore to the name
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
@@ -345,7 +360,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
opsByPathEntry.put("path", entry.getKey());
opsByPathEntry.put("operation", entry.getValue());
List<CodegenOperation> operationsForThisPath = Lists.newArrayList(entry.getValue());
operationsForThisPath.get(operationsForThisPath.size() - 1).hasMore = null;
operationsForThisPath.get(operationsForThisPath.size() - 1).hasMore = false;
if (opsByPathList.size() < opsByPath.asMap().size()) {
opsByPathEntry.put("hasMore", "true");
}
@@ -410,33 +425,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
@@ -553,20 +544,20 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
example = "'" + escapeText(example) + "'";
} else if ("Integer".equals(type) || "int".equals(type)) {
if(p.minimum != null) {
example = "" + (p.minimum.intValue() + 1);
example = "" + (Integer.valueOf(p.minimum) + 1);
}
if(p.maximum != null) {
example = "" + p.maximum.intValue();
example = "" + p.maximum;
} else if (example == null) {
example = "56";
}
} else if ("Long".equalsIgnoreCase(type)) {
if(p.minimum != null) {
example = "" + (p.minimum.longValue() + 1);
example = "" + (Long.valueOf(p.minimum) + 1);
}
if(p.maximum != null) {
example = "" + p.maximum.longValue();
example = "" + p.maximum;
} else if (example == null) {
example = "789";
}
@@ -640,11 +631,60 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
@Override
public String toModelImport(String name) {
String modelImport = "from ";
if (!"".equals(modelPackage())) {
modelImport += modelPackage() + ".";
String modelImport;
if (StringUtils.startsWithAny(name,"import", "from")) {
modelImport = name;
} else {
modelImport = "from ";
if (!"".equals(modelPackage())) {
modelImport += modelPackage() + ".";
}
modelImport += toModelFilename(name)+ " import " + name;
}
modelImport += toModelFilename(name)+ " import " + name;
return modelImport;
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property){
if (StringUtils.isNotEmpty(property.pattern)) {
addImport(model, "import re");
}
postProcessPattern(property.pattern, property.vendorExtensions);
}
@Override
public void postProcessParameter(CodegenParameter parameter){
postProcessPattern(parameter.pattern, parameter.vendorExtensions);
}
/*
* The swagger pattern spec follows the Perl convention and style of modifiers. Python
* does not support this in as natural a way so it needs to convert it. See
* https://docs.python.org/2/howto/regex.html#compilation-flags for details.
*/
public void postProcessPattern(String pattern, Map<String, Object> vendorExtensions){
if(pattern != null) {
int i = pattern.lastIndexOf('/');
//Must follow Perl /pattern/modifiers convention
if(pattern.charAt(0) != '/' || i < 2) {
throw new IllegalArgumentException("Pattern must follow the Perl "
+ "/pattern/modifiers convention. "+pattern+" is not valid.");
}
String regex = pattern.substring(1, i).replace("'", "\\'");
List<String> modifiers = new ArrayList<String>();
for(char c : pattern.substring(i).toCharArray()) {
if(regexModifiers.containsKey(c)) {
String modifier = regexModifiers.get(c);
modifiers.add(modifier);
}
}
vendorExtensions.put("x-regex", regex);
vendorExtensions.put("x-modifiers", modifiers);
}
}
}

View File

@@ -43,7 +43,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
templateDir = "go";
embeddedTemplateDir = templateDir = "go";
setReservedWordsLowerCase(
Arrays.asList(
@@ -180,9 +180,10 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
// - XName
// - X_Name
// ... or maybe a suffix?
// - Name_ ... think this will work.
// FIXME: This should also really be a customizable option
// - Name_ ... think this will work.
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return camelize(name) + '_';
}

View File

@@ -126,6 +126,9 @@ public class GoServerCodegen extends DefaultCodegen implements CodegenConfig {
cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Go package name (convention: lowercase).")
.defaultValue("swagger"));
cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated")
.defaultValue(Boolean.TRUE.toString()));
/*
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
@@ -204,6 +207,9 @@ public class GoServerCodegen extends DefaultCodegen implements CodegenConfig {
*/
@Override
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name; // add an underscore to the name
}

View File

@@ -54,6 +54,12 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
specialCharReplacements.put(">", "GreaterThan");
specialCharReplacements.put("<", "LessThan");
// backslash and double quote need double the escapement for both Java and Haskell
specialCharReplacements.remove("\\");
specialCharReplacements.remove("\"");
specialCharReplacements.put("\\\\", "Back_Slash");
specialCharReplacements.put("\\\"", "Double_Quote");
// set the output folder here
outputFolder = "generated-code/haskell-servant";
@@ -154,8 +160,11 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return name + "_";
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
public String firstLetterToUpper(String word) {
@@ -386,7 +395,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);
@@ -417,7 +426,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

@@ -68,7 +68,7 @@ public class JMeterCodegen extends DefaultCodegen implements CodegenConfig {
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
templateDir = "JMeter";
embeddedTemplateDir = templateDir = "JMeter";
/*
* Api Package. Optional, if needed, this can be used in templates
@@ -119,10 +119,13 @@ public class JMeterCodegen extends DefaultCodegen implements CodegenConfig {
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
@Override
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
/**
* Location to write model files. You can use the modelPackage() as defined when the class is

View File

@@ -11,40 +11,45 @@ import org.slf4j.LoggerFactory;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.codegen.languages.features.GzipTestFeatures;
import io.swagger.codegen.languages.features.JaxbFeatures;
import io.swagger.codegen.languages.features.LoggingTestFeatures;
import io.swagger.codegen.languages.features.UseGenericResponseFeatures;
import io.swagger.models.Operation;
public class JavaCXFClientCodegen extends AbstractJavaCodegen
implements BeanValidationFeatures, JaxbFeatures, GzipTestFeatures, LoggingTestFeatures
{
private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFClientCodegen.class);
implements BeanValidationFeatures, UseGenericResponseFeatures, 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 useGenericResponse = 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 +57,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 +68,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 +76,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"));
cliOptions.add(CliOption.newBoolean(USE_GENERIC_RESPONSE, "Use generic response"));
}
@@ -84,7 +88,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);
@@ -95,14 +99,22 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen
this.setUseBeanValidation(useBeanValidationProp);
}
if (additionalProperties.containsKey(USE_GENERIC_RESPONSE)) {
this.setUseGenericResponse(convertPropertyToBoolean(USE_GENERIC_RESPONSE));
}
if (useGenericResponse) {
writePropertyBack(USE_GENERIC_RESPONSE, useGenericResponse);
}
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 +129,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 +144,39 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen
model.imports.remove("JsonSerialize");
model.imports.remove("ToStringSerializer");
}
@Override
@SuppressWarnings("unchecked")
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
objs = super.postProcessOperations(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.returnType == null) {
operation.returnType = "void";
// set vendorExtensions.x-java-is-response-void to true as
// returnType is set to "void"
operation.vendorExtensions.put("x-java-is-response-void", true);
}
}
}
return operations;
}
@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;
@@ -156,4 +190,8 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen
this.useLoggingFeatureForTests = useLoggingFeatureForTests;
}
public void setUseGenericResponse(boolean useGenericResponse) {
this.useGenericResponse = useGenericResponse;
}
}

View File

@@ -17,18 +17,17 @@ import io.swagger.codegen.languages.features.CXFServerFeatures;
import io.swagger.codegen.languages.features.GzipTestFeatures;
import io.swagger.codegen.languages.features.JaxbFeatures;
import io.swagger.codegen.languages.features.LoggingTestFeatures;
import io.swagger.codegen.languages.features.UseGenericResponseFeatures;
import io.swagger.models.Operation;
public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
implements CXFServerFeatures, GzipTestFeatures, LoggingTestFeatures, JaxbFeatures
implements CXFServerFeatures, GzipTestFeatures, LoggingTestFeatures, JaxbFeatures, UseGenericResponseFeatures
{
private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFServerCodegen.class);
protected boolean addConsumesProducesJson = true;
protected boolean useJaxbAnnotations = true;
protected boolean useBeanValidation = false;
protected boolean generateSpringApplication = false;
@@ -41,7 +40,7 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
protected boolean useWadlFeature = false;
protected boolean useMultipartFeature = false;
protected boolean useBeanValidationFeature = false;
protected boolean generateSpringBootApplication= false;
@@ -56,6 +55,12 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
protected boolean useLoggingFeatureForTests = false;
protected boolean useAnnotatedBasePath = false;
protected boolean generateNonSpringApplication = false;
protected boolean useGenericResponse = false;
public JavaCXFServerCodegen()
{
super();
@@ -76,7 +81,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");
@@ -84,7 +88,6 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
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(GENERATE_SPRING_APPLICATION, "Generate Spring application"));
cliOptions.add(CliOption.newBoolean(USE_SPRING_ANNOTATION_CONFIG, "Use Spring Annotation Config"));
@@ -108,6 +111,11 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
cliOptions
.add(CliOption.newBoolean(ADD_CONSUMES_PRODUCES_JSON, "Add @Consumes/@Produces Json to API interface"));
cliOptions.add(CliOption.newBoolean(USE_ANNOTATED_BASE_PATH, "Use @Path annotations for basePath"));
cliOptions.add(CliOption.newBoolean(GENERATE_NON_SPRING_APPLICATION, "Generate non-Spring application"));
cliOptions.add(CliOption.newBoolean(USE_GENERIC_RESPONSE, "Use generic response"));
}
@@ -121,14 +129,17 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
this.setUseJaxbAnnotations(useJaxbAnnotationsProp);
}
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
boolean useBeanValidationProp = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION);
this.setUseBeanValidation(useBeanValidationProp);
}
if (additionalProperties.containsKey(ADD_CONSUMES_PRODUCES_JSON)) {
this.setAddConsumesProducesJson(convertPropertyToBooleanAndWriteBack(ADD_CONSUMES_PRODUCES_JSON));
}
if (additionalProperties.containsKey(USE_GENERIC_RESPONSE)) {
this.setUseGenericResponse(convertPropertyToBoolean(USE_GENERIC_RESPONSE));
}
if (useGenericResponse) {
writePropertyBack(USE_GENERIC_RESPONSE, useGenericResponse);
}
if (additionalProperties.containsKey(GENERATE_SPRING_APPLICATION)) {
this.setGenerateSpringApplication(convertPropertyToBooleanAndWriteBack(GENERATE_SPRING_APPLICATION));
@@ -159,6 +170,16 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
this.setGenerateJbossDeploymentDescriptor(generateJbossDeploymentDescriptorProp);
}
if (additionalProperties.containsKey(USE_ANNOTATED_BASE_PATH)) {
boolean useAnnotatedBasePathProp = convertPropertyToBooleanAndWriteBack(USE_ANNOTATED_BASE_PATH);
this.setUseAnnotatedBasePath(useAnnotatedBasePathProp);
}
if (additionalProperties.containsKey(GENERATE_NON_SPRING_APPLICATION)) {
boolean generateNonSpringApplication = convertPropertyToBooleanAndWriteBack(GENERATE_NON_SPRING_APPLICATION);
this.setGenerateNonSpringApplication(generateNonSpringApplication);
}
supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen
writeOptional(outputFolder, new SupportingFile("server/pom.mustache", "", "pom.xml"));
@@ -191,10 +212,12 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
(testResourcesFolder + '/'), "application.properties"));
}
}
if (this.generateNonSpringApplication) {
writeOptional(outputFolder, new SupportingFile("server/nonspring-web.mustache",
("src/main/webapp/WEB-INF"), "web.xml"));
}
}
@Override
@@ -224,10 +247,6 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
return "Generates a Java JAXRS Server application based on Apache CXF framework.";
}
public void setUseBeanValidation(boolean useBeanValidation) {
this.useBeanValidation = useBeanValidation;
}
public void setGenerateSpringApplication(boolean generateSpringApplication) {
this.generateSpringApplication = generateSpringApplication;
}
@@ -293,4 +312,16 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
this.addConsumesProducesJson = addConsumesProducesJson;
}
public void setUseAnnotatedBasePath(boolean useAnnotatedBasePath) {
this.useAnnotatedBasePath = useAnnotatedBasePath;
}
public void setGenerateNonSpringApplication(boolean generateNonSpringApplication) {
this.generateNonSpringApplication = generateNonSpringApplication;
}
public void setUseGenericResponse(boolean useGenericResponse) {
this.useGenericResponse = useGenericResponse;
}
}

View File

@@ -2,7 +2,8 @@ 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;
import org.slf4j.Logger;
@@ -12,13 +13,19 @@ import java.io.File;
import java.util.*;
import java.util.regex.Pattern;
public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValidationFeatures {
public class JavaClientCodegen extends AbstractJavaCodegen
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";
public static final String RETROFIT_1 = "retrofit";
@@ -26,8 +33,13 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
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();
@@ -39,18 +51,23 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
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("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0");
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: OpenFeign 9.4.0. JSON processing: Jackson 2.8.7");
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("resteasy", "HTTP client: Resteasy client 3.0.19.Final. JSON processing: Jackson 2.7.0");
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);
// set okhttp-gson as the default
@@ -79,9 +96,22 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
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()));
}
additionalProperties.put(USE_PLAY24_WS, usePlay24WS);
if (additionalProperties.containsKey(PARCELABLE_MODEL)) {
this.setParcelableModel(Boolean.valueOf(additionalProperties.get(PARCELABLE_MODEL).toString()));
}
@@ -89,11 +119,15 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
additionalProperties.put(PARCELABLE_MODEL, parcelableModel);
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
boolean useBeanValidationProp = Boolean.valueOf(additionalProperties.get(USE_BEANVALIDATION).toString());
this.setUseBeanValidation(useBeanValidationProp);
this.setUseBeanValidation(convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION));
}
// write back as boolean
additionalProperties.put(USE_BEANVALIDATION, useBeanValidationProp);
if (additionalProperties.containsKey(PERFORM_BEANVALIDATION)) {
this.setPerformBeanValidation(convertPropertyToBooleanAndWriteBack(PERFORM_BEANVALIDATION));
}
if (additionalProperties.containsKey(USE_GZIP_FEATURE)) {
this.setUseGzipFeature(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE));
}
final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/");
@@ -123,6 +157,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
if (performBeanValidation) {
supportingFiles.add(new SupportingFile("BeanValidationException.mustache", invokerFolder,
"BeanValidationException.java"));
}
//TODO: add doc to retrofit1 and feign
if ( "feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) ){
modelDocTemplateFiles.remove("model_doc.mustache");
@@ -139,6 +178,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
if ("feign".equals(getLibrary())) {
additionalProperties.put("jackson", "true");
supportingFiles.add(new SupportingFile("ParamExpander.mustache", invokerFolder, "ParamExpander.java"));
supportingFiles.add(new SupportingFile("EncodingUtils.mustache", invokerFolder, "EncodingUtils.java"));
} else if ("okhttp-gson".equals(getLibrary()) || StringUtils.isEmpty(getLibrary())) {
// the "okhttp-gson" library template requires "ApiCallback.mustache" for async call
supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java"));
@@ -146,12 +186,13 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
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"));
supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java"));
additionalProperties.put("gson", "true");
} else if("jersey2".equals(getLibrary())) {
} else if ("jersey2".equals(getLibrary()) || "resteasy".equals(getLibrary())) {
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
additionalProperties.put("jackson", "true");
} else if("jersey1".equals(getLibrary())) {
@@ -160,6 +201,33 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
LOGGER.error("Unknown library option (-l/--library): " + getLibrary());
}
if (Boolean.TRUE.equals(additionalProperties.get(USE_PLAY24_WS))) {
// remove unsupported auth
Iterator<SupportingFile> iter = supportingFiles.iterator();
while (iter.hasNext()) {
SupportingFile sf = iter.next();
if (sf.templateFile.startsWith("auth/")) {
iter.remove();
}
}
// auth
supportingFiles.add(new SupportingFile("play24/auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java"));
supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java"));
supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java"));
// api client
supportingFiles.add(new SupportingFile("play24/ApiClient.mustache", invokerFolder, "ApiClient.java"));
// adapters
supportingFiles
.add(new SupportingFile("play24/Play24CallFactory.mustache", invokerFolder, "Play24CallFactory.java"));
supportingFiles.add(new SupportingFile("play24/Play24CallAdapterFactory.mustache", invokerFolder,
"Play24CallAdapterFactory.java"));
additionalProperties.put("jackson", "true");
additionalProperties.remove("gson");
}
if (additionalProperties.containsKey("jackson") ) {
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder, "RFC3339DateFormat.java"));
}
@@ -176,16 +244,16 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
super.postProcessOperations(objs);
if(usesAnyRetrofitLibrary()) {
if (usesAnyRetrofitLibrary()) {
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) {
if ( isMultipartType(operation.consumes) ) {
if (isMultipartType(operation.consumes)) {
operation.isMultipart = Boolean.TRUE;
}
}
else {
operation.prioritizedContentTypes = prioritizeContentTypes(operation.consumes);
}
@@ -198,6 +266,27 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
}
}
}
// camelize path variables for Feign client
if ("feign".equals(getLibrary())) {
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;
}
@@ -293,8 +382,23 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
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) {
this.usePlay24WS = usePlay24WS;
}
public void setParcelableModel(boolean parcelableModel) {
this.parcelableModel = parcelableModel;
}
@@ -303,6 +407,14 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
this.useBeanValidation = useBeanValidation;
}
public void setPerformBeanValidation(boolean performBeanValidation) {
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

@@ -1,8 +1,10 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import java.io.File;
@@ -13,7 +15,10 @@ import java.io.File;
* in /src/gen/java and a sample ServiceImpl in /src/main/java. The API uses CDI
* to get an instance of ServiceImpl that implements the Service interface.
*/
public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen {
public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen implements BeanValidationFeatures {
protected boolean useBeanValidation = true;
/**
* Default constructor
*/
@@ -32,6 +37,8 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen {
// Updated template directory
embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME
+ File.separator + "cxf-cdi";
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
}
@Override
@@ -43,6 +50,14 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen {
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
}
if (useBeanValidation) {
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
}
supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen
// writeOptional means these files are only written if they don't already exist
@@ -73,4 +88,7 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen {
+ "Apache CXF runtime and a Java EE runtime with CDI enabled.";
}
public void setUseBeanValidation(boolean useBeanValidation) {
this.useBeanValidation = useBeanValidation;
}
}

View File

@@ -2,27 +2,30 @@ package io.swagger.codegen.languages;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.properties.Property;
import io.swagger.util.Json;
import org.apache.commons.io.FileUtils;
public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen
{
public JavaJAXRSSpecServerCodegen()
{
{
public JavaJAXRSSpecServerCodegen()
{
super();
invokerPackage = "io.swagger.api";
artifactId = "swagger-jaxrs-server";
@@ -45,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");
@@ -57,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);
@@ -67,26 +69,27 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen
library.setEnum(supportedLibraries);
cliOptions.add(library);
}
@Override
public void processOpts()
{
super.processOpts();
}
supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen
@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()
{
return "jaxrs-spec";
}
}
@Override
public String getName()
{
return "jaxrs-spec";
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
@@ -115,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);
@@ -126,17 +129,17 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen
model.imports.remove("JsonValue");
model.imports.remove("JsonProperty");
}
@Override
@Override
public void preprocessSwagger(Swagger swagger) {
//copy input swagger to output folder
try {
String swaggerJson = Json.pretty(swagger);
//copy input swagger to output folder
try {
String swaggerJson = Json.pretty(swagger);
FileUtils.writeStringToFile(new File(outputFolder + File.separator + "swagger.json"), swaggerJson);
} catch (IOException e) {
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e.getCause());
}
super.preprocessSwagger(swagger);
}
super.preprocessSwagger(swagger);
}
@Override

View File

@@ -1,6 +1,7 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.models.Operation;
import java.util.*;
@@ -12,7 +13,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
protected static final String LIBRARY_JERSEY1 = "jersey1";
protected static final String LIBRARY_JERSEY2 = "jersey2";
/**
* Default library template to use. (Default:{@value #DEFAULT_LIBRARY})
*/
@@ -84,7 +85,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
if (StringUtils.isEmpty(library)) {
setLibrary(DEFAULT_LIBRARY);
}
if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) {
implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER);
}
@@ -160,5 +161,5 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
opList.add(co);
co.baseName = basePath;
}
}

View File

@@ -0,0 +1,320 @@
package io.swagger.codegen.languages;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.codegen.*;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.models.Model;
import io.swagger.models.Swagger;
import io.swagger.util.Json;
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 USE_INTERFACES = "useInterfaces";
public static final String HANDLE_EXCEPTIONS = "handleExceptions";
public static final String WRAP_CALLS = "wrapCalls";
public static final String USE_SWAGGER_UI = "useSwaggerUI";
protected String title = "swagger-petstore";
protected String configPackage = "io.swagger.configuration";
protected String basePackage = "io.swagger";
protected boolean controllerOnly = false;
protected boolean useInterfaces = true;
protected boolean useBeanValidation = true;
protected boolean handleExceptions = true;
protected boolean wrapCalls = true;
protected boolean useSwaggerUI = 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"));
//Custom options for this generator
cliOptions.add(createBooleanCliWithDefault(CONTROLLER_ONLY, "Whether to generate only API interface stubs without the server files.", controllerOnly));
cliOptions.add(createBooleanCliWithDefault(USE_BEANVALIDATION, "Use BeanValidation API annotations", useBeanValidation));
cliOptions.add(createBooleanCliWithDefault(USE_INTERFACES, "Makes the controllerImp implements an interface to facilitate automatic completion when updating from version x to y of your spec", useInterfaces));
cliOptions.add(createBooleanCliWithDefault(HANDLE_EXCEPTIONS, "Add a 'throw exception' to each controller function. Add also a custom error handler where you can put your custom logic", handleExceptions));
cliOptions.add(createBooleanCliWithDefault(WRAP_CALLS, "Add a wrapper to each controller function to handle things like metrics, response modification, etc..", wrapCalls));
cliOptions.add(createBooleanCliWithDefault(USE_SWAGGER_UI, "Add a route to /api which show your documentation in swagger-ui. Will also import needed dependencies", useSwaggerUI));
}
@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(convertPropertyToBoolean(CONTROLLER_ONLY));
} else {
writePropertyBack(CONTROLLER_ONLY, controllerOnly);
}
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
} else {
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
}
if (additionalProperties.containsKey(USE_INTERFACES)) {
this.setUseInterfaces(convertPropertyToBoolean(USE_INTERFACES));
} else {
writePropertyBack(USE_INTERFACES, useInterfaces);
}
if (additionalProperties.containsKey(HANDLE_EXCEPTIONS)) {
this.setHandleExceptions(convertPropertyToBoolean(HANDLE_EXCEPTIONS));
} else {
writePropertyBack(HANDLE_EXCEPTIONS, handleExceptions);
}
if (additionalProperties.containsKey(WRAP_CALLS)) {
this.setWrapCalls(convertPropertyToBoolean(WRAP_CALLS));
} else {
writePropertyBack(WRAP_CALLS, wrapCalls);
}
if (additionalProperties.containsKey(USE_SWAGGER_UI)) {
this.setUseSwaggerUI(convertPropertyToBoolean(USE_SWAGGER_UI));
} else {
writePropertyBack(USE_SWAGGER_UI, useSwaggerUI);
}
//We don't use annotation anymore
importMapping.remove("ApiModelProperty");
importMapping.remove("ApiModel");
//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"));
if (this.handleExceptions) {
supportingFiles.add(new SupportingFile("errorHandler.mustache", "app/swagger", "ErrorHandler.java"));
}
if(this.wrapCalls) {
supportingFiles.add(new SupportingFile("apiCall.mustache", "app/swagger", "ApiCall.java"));
}
if(this.useSwaggerUI) {
//App/Controllers
supportingFiles.add(new SupportingFile("swagger.mustache", "public", "swagger.json"));
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");
}
if (this.useInterfaces) {
apiTemplateFiles.put("newApiInterface.mustache", "ControllerImpInterface.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");
importMapping.put("InputStream", "java.io.InputStream");
typeMapping.put("file", "InputStream");
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
//We don't use annotation anymore
model.imports.remove("ApiModelProperty");
model.imports.remove("ApiModel");
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
if(codegenModel.description != null) {
codegenModel.imports.remove("ApiModel");
}
return codegenModel;
}
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 setUseInterfaces(boolean useInterfaces) {
this.useInterfaces = useInterfaces;
}
public void setUseBeanValidation(boolean useBeanValidation) {
this.useBeanValidation = useBeanValidation;
}
public void setHandleExceptions(boolean handleExceptions) {
this.handleExceptions = handleExceptions;
}
public void setWrapCalls(boolean wrapCalls) {
this.wrapCalls = wrapCalls;
}
public void setUseSwaggerUI(boolean useSwaggerUI) {
this.useSwaggerUI = useSwaggerUI;
}
@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) {
for (CodegenParameter param : operation.allParams) {
if (param.isFormParam && param.isFile) {
param.dataType = "Http.MultipartFormData.FilePart";
}
}
for (CodegenParameter param : operation.formParams) {
if (param.isFile) {
param.dataType = "Http.MultipartFormData.FilePart";
}
}
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;
}
private CliOption createBooleanCliWithDefault(String optionName, String description, boolean defaultValue) {
CliOption defaultOption = CliOption.newBoolean(optionName, description);
defaultOption.setDefault(Boolean.toString(defaultValue));
return defaultOption;
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
Swagger swagger = (Swagger)objs.get("swagger");
System.out.println("swagger" + swagger.toString());
if(swagger != null) {
try {
objs.put("swagger-json", Json.pretty().writeValueAsString(swagger));
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}
}
return super.postProcessSupportingFileData(objs);
}
}

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

@@ -1,6 +1,7 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.codegen.languages.features.JbossFeature;
import io.swagger.models.Operation;
import org.apache.commons.lang3.BooleanUtils;
@@ -12,7 +13,7 @@ import java.util.*;
public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen implements JbossFeature {
protected boolean generateJbossDeploymentDescriptor = true;
public JavaResteasyServerCodegen() {
super();
@@ -58,7 +59,7 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen im
GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR);
this.setGenerateJbossDeploymentDescriptor(generateJbossDeploymentDescriptorProp);
}
writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml"));
writeOptional(outputFolder, new SupportingFile("gradle.mustache", "", "build.gradle"));
writeOptional(outputFolder, new SupportingFile("settingsGradle.mustache", "", "settings.gradle"));
@@ -214,7 +215,7 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen im
return objs;
}
public void setGenerateJbossDeploymentDescriptor(boolean generateJbossDeploymentDescriptor) {
this.generateJbossDeploymentDescriptor = generateJbossDeploymentDescriptor;
}

View File

@@ -22,6 +22,7 @@ import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.ByteArrayProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DoubleProperty;
@@ -84,7 +85,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
modelTestTemplateFiles.put("model_test.mustache", ".js");
apiTemplateFiles.put("api.mustache", ".js");
apiTestTemplateFiles.put("api_test.mustache", ".js");
templateDir = "Javascript";
embeddedTemplateDir = templateDir = "Javascript";
apiPackage = "api";
modelPackage = "model";
modelDocTemplateFiles.put("model_doc.mustache", ".md");
@@ -113,7 +114,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
);
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList("String", "Boolean", "Number", "Array", "Object", "Date", "File")
Arrays.asList("String", "Boolean", "Number", "Array", "Object", "Date", "File", "Blob")
);
defaultIncludes = new HashSet<String>(languageSpecificPrimitives);
@@ -138,8 +139,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
typeMapping.put("object", "Object");
typeMapping.put("integer", "Number");
// binary not supported in JavaScript client right now, using String as a workaround
typeMapping.put("ByteArray", "String"); // I don't see ByteArray defined in the Swagger docs.
typeMapping.put("binary", "String");
typeMapping.put("ByteArray", "Blob"); // I don't see ByteArray defined in the Swagger docs.
typeMapping.put("binary", "Blob");
typeMapping.put("UUID", "String");
importMapping.clear();
@@ -202,7 +203,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 +228,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));
}
}
@@ -313,7 +313,10 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
}
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@@ -650,7 +653,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
* @return Normalized type
*/
public String normalizeType(String type) {
return type.replaceAll("\\b(Boolean|Integer|Number|String|Date)\\b", "'$1'");
return type.replaceAll("\\b(Boolean|Integer|Number|String|Date|Blob)\\b", "'$1'");
}
@Override
@@ -707,7 +710,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;
@@ -775,12 +778,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"))
@@ -802,12 +799,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))
@@ -825,13 +816,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) {
@@ -863,7 +847,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;
@@ -927,14 +911,14 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
// set vendor-extension: x-codegen-hasMoreRequired
CodegenProperty lastRequired = null;
for (CodegenProperty var : cm.vars) {
if (var.required != null && var.required) {
if (var.required) {
lastRequired = var;
}
}
for (CodegenProperty var : cm.vars) {
if (var == lastRequired) {
var.vendorExtensions.put("x-codegen-hasMoreRequired", false);
} else if (var.required != null && var.required) {
} else if (var.required) {
var.vendorExtensions.put("x-codegen-hasMoreRequired", true);
}
}
@@ -947,15 +931,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
@@ -996,7 +971,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
int count = 0, numVars = codegenProperties.size();
for(CodegenProperty codegenProperty : codegenProperties) {
count += 1;
codegenProperty.hasMore = (count < numVars) ? true : null;
codegenProperty.hasMore = (count < numVars) ? true : false;
}
codegenModel.vars = codegenProperties;
}
@@ -1021,6 +996,10 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override
public String toEnumVarName(String value, String datatype) {
if (value.length() == 0) {
return "empty";
}
// for symbol, e.g. $, #
if (getSymbolName(value) != null) {
return (getSymbolName(value)).toUpperCase();

View File

@@ -102,7 +102,10 @@ public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implem
}
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}

View File

@@ -1,24 +1,12 @@
package io.swagger.codegen.languages;
import static com.google.common.base.Strings.isNullOrEmpty;
import static io.swagger.codegen.CodegenConstants.OPTIONAL_PROJECT_FILE;
import static io.swagger.codegen.CodegenConstants.OPTIONAL_PROJECT_FILE_DESC;
import static io.swagger.codegen.CodegenConstants.PACKAGE_NAME;
import static io.swagger.codegen.CodegenConstants.PACKAGE_VERSION;
import static io.swagger.codegen.CodegenConstants.RETURN_ICOLLECTION;
import static io.swagger.codegen.CodegenConstants.RETURN_ICOLLECTION_DESC;
import static io.swagger.codegen.CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG;
import static io.swagger.codegen.CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC;
import static io.swagger.codegen.CodegenConstants.SOURCE_FOLDER;
import static io.swagger.codegen.CodegenConstants.SOURCE_FOLDER_DESC;
import static io.swagger.codegen.CodegenConstants.USE_COLLECTION;
import static io.swagger.codegen.CodegenConstants.USE_COLLECTION_DESC;
import static io.swagger.codegen.CodegenConstants.USE_DATETIME_OFFSET;
import static io.swagger.codegen.CodegenConstants.USE_DATETIME_OFFSET_DESC;
import static io.swagger.codegen.CodegenConstants.*;
import static io.swagger.codegen.CodegenType.SERVER;
import static java.util.Arrays.asList;
import static java.util.UUID.randomUUID;
import static org.apache.commons.lang3.StringUtils.capitalize;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
@@ -60,7 +48,7 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen {
private static final Map<String, Predicate<Property>> propertyToSwaggerTypeMapping =
createPropertyToSwaggerTypeMapping();
private final String packageGuid = "{" + randomUUID().toString().toUpperCase() + "}";
private String packageGuid = "{" + randomUUID().toString().toUpperCase() + "}";
private final Map<String, DependencyInfo> dependencies = new HashMap<>();
private final Set<String> parentModels = new HashSet<>();
@@ -71,6 +59,9 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen {
outputFolder = "generated-code" + File.separator + getName();
apiTemplateFiles.put("api.mustache", ".cs");
// Early versions use no prefix for interfaces. Defaulting to I- common practice would break existing users.
setInterfacePrefix("");
// contextually reserved words
setReservedWordsLowerCase(
asList("var", "async", "await", "dynamic", "yield")
@@ -82,6 +73,8 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen {
addOption(PACKAGE_NAME, "C# package name (convention: Title.Case).", packageName);
addOption(PACKAGE_VERSION, "C# package version.", packageVersion);
addOption(SOURCE_FOLDER, SOURCE_FOLDER_DESC, sourceFolder);
addOption(INTERFACE_PREFIX, INTERFACE_PREFIX_DESC, interfacePrefix);
addOption(OPTIONAL_PROJECT_GUID,OPTIONAL_PROJECT_GUID_DESC, null);
// CLI Switches
addSwitch(SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_BY_REQUIRED_FLAG_DESC, sortParamsByRequiredFlag);
@@ -127,6 +120,11 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen {
supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln"));
supportingFiles.add(new SupportingFile("Project.mustache", sourceFolder(), packageName + ".csproj"));
}
if (additionalProperties.containsKey(OPTIONAL_PROJECT_GUID)) {
setPackageGuid((String) additionalProperties.get(OPTIONAL_PROJECT_GUID));
}
additionalProperties.put("packageGuid", packageGuid);
setupModelTemplate();
@@ -195,6 +193,10 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen {
return sourceFolder() + File.separator + fileName;
}
public void setPackageGuid(String packageGuid) {
this.packageGuid = packageGuid;
}
@Override
public String apiFileFolder() {
return outputFolder + File.separator + sourceFolder() + File.separator + API_NAMESPACE;
@@ -292,6 +294,10 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen {
@Override
public String toEnumVarName(final String name, final String datatype) {
if (name.length() == 0) {
return "Empty";
}
final String enumName = camelize(
sanitizeName(name)
.replaceFirst("^_", "")

View File

@@ -24,10 +24,16 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
private static final Logger LOGGER = LoggerFactory.getLogger(NodeJSServerCodegen.class);
public static final String GOOGLE_CLOUD_FUNCTIONS = "googleCloudFunctions";
public static final String EXPORTED_NAME = "exportedName";
protected String apiVersion = "1.0.0";
protected int serverPort = 8080;
protected String projectName = "swagger-server";
protected boolean googleCloudFunctions;
protected String exportedName;
public NodeJSServerCodegen() {
super();
@@ -76,27 +82,15 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
additionalProperties.put("apiVersion", apiVersion);
additionalProperties.put("serverPort", serverPort);
/*
* Supporting Files. You can write single files for the generator with the
* entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied
*/
// supportingFiles.add(new SupportingFile("controller.mustache",
// "controllers",
// "controller.js")
// );
supportingFiles.add(new SupportingFile("swagger.mustache",
"api",
"swagger.yaml")
);
writeOptional(outputFolder, new SupportingFile("index.mustache", "", "index.js"));
writeOptional(outputFolder, new SupportingFile("package.mustache", "", "package.json"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));
if (System.getProperty("noservice") == null) {
apiTemplateFiles.put(
"service.mustache", // the template to use
"Service.js"); // the extension for each file to write
}
cliOptions.add(CliOption.newBoolean(GOOGLE_CLOUD_FUNCTIONS,
"When specified, it will generate the code which runs within Google Cloud Functions "
+ "instead of standalone Node.JS server. See "
+ "https://cloud.google.com/functions/docs/quickstart for the details of how to "
+ "deploy the generated code."));
cliOptions.add(new CliOption(EXPORTED_NAME,
"When the generated code will be deployed to Google Cloud Functions, this option can be "
+ "used to update the name of the exported function. By default, it refers to the "
+ "basePath. This does not affect normal standalone nodejs server code."));
}
@Override
@@ -153,13 +147,16 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reseved words
* those terms here. This logic is only called if a variable matches the reserved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
/**
@@ -171,6 +168,22 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
public boolean getGoogleCloudFunctions() {
return googleCloudFunctions;
}
public void setGoogleCloudFunctions(boolean value) {
googleCloudFunctions = value;
}
public String getExportedName() {
return exportedName;
}
public void setExportedName(String name) {
exportedName = name;
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
@SuppressWarnings("unchecked")
@@ -231,7 +244,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
opsByPathEntry.put("path", entry.getKey());
opsByPathEntry.put("operation", entry.getValue());
List<CodegenOperation> operationsForThisPath = Lists.newArrayList(entry.getValue());
operationsForThisPath.get(operationsForThisPath.size() - 1).hasMore = null;
operationsForThisPath.get(operationsForThisPath.size() - 1).hasMore = false;
if (opsByPathList.size() < opsByPath.asMap().size()) {
opsByPathEntry.put("hasMore", "true");
}
@@ -240,6 +253,46 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
return opsByPathList;
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(GOOGLE_CLOUD_FUNCTIONS)) {
setGoogleCloudFunctions(
Boolean.valueOf(additionalProperties.get(GOOGLE_CLOUD_FUNCTIONS).toString()));
}
if (additionalProperties.containsKey(EXPORTED_NAME)) {
setExportedName((String)additionalProperties.get(EXPORTED_NAME));
}
/*
* Supporting Files. You can write single files for the generator with the
* entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied
*/
// supportingFiles.add(new SupportingFile("controller.mustache",
// "controllers",
// "controller.js")
// );
supportingFiles.add(new SupportingFile("swagger.mustache",
"api",
"swagger.yaml")
);
if (getGoogleCloudFunctions()) {
writeOptional(outputFolder, new SupportingFile("index-gcf.mustache", "", "index.js"));
} else {
writeOptional(outputFolder, new SupportingFile("index.mustache", "", "index.js"));
}
writeOptional(outputFolder, new SupportingFile("package.mustache", "", "package.json"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));
if (System.getProperty("noservice") == null) {
apiTemplateFiles.put(
"service.mustache", // the template to use
"Service.js"); // the extension for each file to write
}
}
@Override
public void preprocessSwagger(Swagger swagger) {
String host = swagger.getHost();
@@ -257,11 +310,32 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
if (info.getTitle() != null) {
// when info.title is defined, use it for projectName
// used in package.json
projectName = dashize(info.getTitle());
projectName = info.getTitle()
.replaceAll("[^a-zA-Z0-9]", "-")
.replaceAll("^[-]*", "")
.replaceAll("[-]*$", "")
.replaceAll("[-]{2,}", "-")
.toLowerCase();
this.additionalProperties.put("projectName", projectName);
}
}
if (getGoogleCloudFunctions()) {
// Note that Cloud Functions don't allow customizing port name, simply checking host
// is good enough.
if (!host.endsWith(".cloudfunctions.net")) {
LOGGER.warn("Host " + host + " seems not matching with cloudfunctions.net URL.");
}
if (!additionalProperties.containsKey(EXPORTED_NAME)) {
String basePath = swagger.getBasePath();
if (basePath == null || basePath.equals("/")) {
LOGGER.warn("Cannot find the exported name properly. Using 'openapi' as the exported name");
basePath = "/openapi";
}
additionalProperties.put(EXPORTED_NAME, basePath.substring(1));
}
}
// need vendor extensions for x-swagger-router-controller
Map<String, Path> paths = swagger.getPaths();
if(paths != null) {

View File

@@ -255,10 +255,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m"));
supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h"));
supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m"));
supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h"));
supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h"));
supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m"));
supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h"));
supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m"));
supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m"));
supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h"));
supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m"));
@@ -269,8 +267,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h"));
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m"));
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h"));
supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m"));
supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h"));
supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", coreFileFolder(), classPrefix + "Configuration.h"));
supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.m"));
supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.h"));
supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.h"));
supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.m"));
supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h"));
supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
@@ -538,8 +539,17 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
return toVarName(name);
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reserved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}

View File

@@ -109,7 +109,8 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString()));
cliOptions.add(CliOption.newBoolean(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants
.ENSURE_UNIQUE_PARAMS_DESC).defaultValue(Boolean.TRUE.toString()));
cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC)
.defaultValue(Boolean.TRUE.toString()));
}
@@ -134,6 +135,14 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
// 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()));
}
supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiClient.pm"));
supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "Configuration.pm"));
supportingFiles.add(new SupportingFile("ApiFactory.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiFactory.pm"));
@@ -162,6 +171,9 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@@ -396,7 +408,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public void setParameterExampleValue(CodegenParameter p) {
if (Boolean.TRUE.equals(p.isString) || Boolean.TRUE.equals(p.isBinary) ||
if (Boolean.TRUE.equals(p.isString) || Boolean.TRUE.equals(p.isBinary) ||
Boolean.TRUE.equals(p.isByteArray) || Boolean.TRUE.equals(p.isFile)) {
p.example = "'" + p.example + "'";
} else if (Boolean.TRUE.equals(p.isBoolean)) {

View File

@@ -232,17 +232,25 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE));
// Update the invokerPackage for the default apiPackage and modelPackage
apiPackage = invokerPackage + "\\" + apiDirName;
modelPackage = invokerPackage + "\\" + modelDirName;
} else {
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
}
if (!additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) {
additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage);
if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) {
// Update model package to contain the specified model package name and the invoker package
modelPackage = invokerPackage + "\\" + (String) additionalProperties.get(CodegenConstants.MODEL_PACKAGE);
}
additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage);
if (!additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) {
additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) {
// Update model package to contain the specified model package name and the invoker package
apiPackage = invokerPackage + "\\" + (String) additionalProperties.get(CodegenConstants.API_PACKAGE);
}
additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
if (additionalProperties.containsKey(COMPOSER_PROJECT_NAME)) {
this.setComposerProjectName((String) additionalProperties.get(COMPOSER_PROJECT_NAME));
@@ -308,6 +316,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@@ -480,7 +491,13 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
// add prefix and/or suffic only if name does not start wth \ (e.g. \DateTime)
if (!name.matches("^\\\\.*")) {
name = modelNamePrefix + name + modelNameSuffix;
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
}
// camelize the model name
@@ -644,6 +661,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toEnumVarName(String name, String datatype) {
if (name.length() == 0) {
return "EMPTY";
}
// number
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
String varName = name;
@@ -658,8 +679,8 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
enumName = enumName.replaceFirst("^_", "");
enumName = enumName.replaceFirst("_$", "");
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
if (isReservedWord(enumName) || enumName.matches("\\d.*")) { // reserved word or starts with number
return escapeReservedWord(enumName);
} else {
return enumName;
}

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;
@@ -31,7 +32,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
protected Map<Character, String> regexModifiers;
private String testFolder;
private String testFolder;
public PythonClientCodegen() {
super();
@@ -251,7 +252,10 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
}
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@@ -288,12 +292,12 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String apiTestFileFolder() {
return outputFolder + File.separatorChar + testFolder;
return outputFolder + File.separatorChar + testFolder;
}
@Override
public String modelTestFileFolder() {
return outputFolder + File.separatorChar + testFolder;
return outputFolder + File.separatorChar + testFolder;
}
@Override
@@ -429,8 +433,8 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toModelTestFilename(String name) {
return "test_" + toModelFilename(name);
};
return "test_" + toModelFilename(name);
}
@Override
public String toApiFilename(String name) {
@@ -443,7 +447,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toApiTestFilename(String name) {
return "test_" + toApiFilename(name);
return "test_" + toApiFilename(name);
}
@Override
@@ -516,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

@@ -198,8 +198,11 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
/**

View File

@@ -186,7 +186,10 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig
}
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}

View File

@@ -250,6 +250,8 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("Rakefile.mustache", "", "Rakefile"));
supportingFiles.add(new SupportingFile("Gemfile.mustache", "", "Gemfile"));
// test files should not be overwritten
writeOptional(outputFolder, new SupportingFile("rspec.mustache", "", ".rspec"));
@@ -270,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;
@@ -328,7 +330,10 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@@ -566,6 +571,10 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toEnumVarName(String name, String datatype) {
if (name.length() == 0) {
return "EMPTY";
}
// number
if ("Integer".equals(datatype) || "Float".equals(datatype)) {
String varName = name;

View File

@@ -76,7 +76,7 @@ public class ScalaClientCodegen extends AbstractScalaCodegen implements CodegenC
importMapping.remove("Map");
importMapping.put("DateTime", "org.joda.time.DateTime");
importMapping.put("ListBuffer", "scala.collections.mutable.ListBuffer");
importMapping.put("ListBuffer", "scala.collection.mutable.ListBuffer");
typeMapping = new HashMap<String, String>();
typeMapping.put("enum", "NSString");

View File

@@ -65,7 +65,6 @@ public class ScalatraServerCodegen extends AbstractScalaCodegen implements Codeg
// mapped to String as a workaround
typeMapping.put("binary", "String");
additionalProperties.put("appName", "Swagger Sample");
additionalProperties.put("appName", "Swagger Sample");
additionalProperties.put("appDescription", "A sample swagger server");
additionalProperties.put("infoUrl", "http://swagger.io");

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;
@@ -107,10 +112,13 @@ public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig
}
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@Override
public String apiFileFolder() {
return (outputFolder + "/" + apiPackage()).replace('/', File.separatorChar);
@@ -210,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

@@ -104,7 +104,10 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi
}
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}

View File

@@ -118,7 +118,10 @@ public class SlimFrameworkServerCodegen extends DefaultCodegen implements Codege
}
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}

View File

@@ -1,448 +1,534 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import java.io.File;
import java.util.*;
public class SpringCodegen extends AbstractJavaCodegen {
public static final String DEFAULT_LIBRARY = "spring-boot";
public static final String TITLE = "title";
public static final String CONFIG_PACKAGE = "configPackage";
public static final String BASE_PACKAGE = "basePackage";
public static final String INTERFACE_ONLY = "interfaceOnly";
public static final String SINGLE_CONTENT_TYPES = "singleContentTypes";
public static final String JAVA_8 = "java8";
public static final String ASYNC = "async";
public static final String RESPONSE_WRAPPER = "responseWrapper";
public static final String SPRING_MVC_LIBRARY = "spring-mvc";
public static final String SPRING_CLOUD_LIBRARY = "spring-cloud";
protected String title = "swagger-petstore";
protected String configPackage = "io.swagger.configuration";
protected String basePackage = "io.swagger";
protected boolean interfaceOnly = false;
protected boolean singleContentTypes = false;
protected boolean java8 = false;
protected boolean async = false;
protected String responseWrapper = "";
public SpringCodegen() {
super();
outputFolder = "generated-code/javaSpring";
apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaSpring";
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
invokerPackage = "io.swagger.api";
artifactId = "swagger-spring";
additionalProperties.put(CONFIG_PACKAGE, configPackage);
additionalProperties.put(BASE_PACKAGE, basePackage);
// spring uses the jackson lib
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(INTERFACE_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(CliOption.newBoolean(JAVA_8, "use java8 default interface"));
cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers"));
cliOptions.add(new CliOption(RESPONSE_WRAPPER, "wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)"));
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.");
supportedLibraries.put(SPRING_CLOUD_LIBRARY, "Spring-Cloud-Feign client with Spring-Boot auto-configured settings.");
setLibrary(DEFAULT_LIBRARY);
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY);
library.setEnum(supportedLibraries);
library.setDefault(DEFAULT_LIBRARY);
cliOptions.add(library);
}
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
@Override
public String getName() {
return "spring";
}
@Override
public String getHelp() {
return "Generates a Java SpringBoot Server application using the SpringFox integration.";
}
@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(INTERFACE_ONLY)) {
this.setInterfaceOnly(Boolean.valueOf(additionalProperties.get(INTERFACE_ONLY).toString()));
}
if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) {
this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString()));
}
if (additionalProperties.containsKey(JAVA_8)) {
this.setJava8(Boolean.valueOf(additionalProperties.get(JAVA_8).toString()));
}
if (additionalProperties.containsKey(ASYNC)) {
this.setAsync(Boolean.valueOf(additionalProperties.get(ASYNC).toString()));
}
if (additionalProperties.containsKey(RESPONSE_WRAPPER)) {
this.setResponseWrapper((String) additionalProperties.get(RESPONSE_WRAPPER));
}
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
if (!this.interfaceOnly) {
if (library.equals(DEFAULT_LIBRARY)) {
supportingFiles.add(new SupportingFile("homeController.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java"));
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java"));
supportingFiles.add(new SupportingFile("application.mustache",
("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
}
if (library.equals(SPRING_MVC_LIBRARY)) {
supportingFiles.add(new SupportingFile("webApplication.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebApplication.java"));
supportingFiles.add(new SupportingFile("webMvcConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebMvcConfiguration.java"));
supportingFiles.add(new SupportingFile("swaggerUiConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerUiConfiguration.java"));
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java"));
supportingFiles.add(new SupportingFile("application.properties",
("src.main.resources").replace(".", java.io.File.separator), "swagger.properties"));
}
if (library.equals(SPRING_CLOUD_LIBRARY)) {
supportingFiles.add(new SupportingFile("apiKeyRequestInterceptor.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ApiKeyRequestInterceptor.java"));
supportingFiles.add(new SupportingFile("clientConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ClientConfiguration.java"));
apiTemplateFiles.put("apiClient.mustache", "Client.java");
if (!additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) {
additionalProperties.put(SINGLE_CONTENT_TYPES, "true");
this.setSingleContentTypes(true);
}
} else {
apiTemplateFiles.put("apiController.mustache", "Controller.java");
supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("apiResponseMessage.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("notFoundException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
}
}
if (this.java8) {
additionalProperties.put("javaVersion", "1.8");
additionalProperties.put("jdk8", "true");
if (this.async) {
additionalProperties.put(RESPONSE_WRAPPER, "CompletableFuture");
}
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "OffsetDateTime");
importMapping.put("LocalDate", "java.time.LocalDate");
importMapping.put("OffsetDateTime", "java.time.OffsetDateTime");
} else if (this.async) {
additionalProperties.put(RESPONSE_WRAPPER, "Callable");
}
// 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;
case "ListenableFuture":
additionalProperties.put(RESPONSE_WRAPPER, "org.springframework.util.concurrent.ListenableFuture");
break;
case "DeferredResult":
additionalProperties.put(RESPONSE_WRAPPER, "org.springframework.web.context.request.DeferredResult");
break;
case "HystrixCommand":
additionalProperties.put(RESPONSE_WRAPPER, "com.netflix.hystrix.HystrixCommand");
break;
case "RxObservable":
additionalProperties.put(RESPONSE_WRAPPER, "rx.Observable");
break;
case "RxSingle":
additionalProperties.put(RESPONSE_WRAPPER, "rx.Single");
break;
default:
break;
}
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
if(library.equals(DEFAULT_LIBRARY) || library.equals(SPRING_MVC_LIBRARY)) {
String basePath = resourcePath;
if (basePath.startsWith("/")) {
basePath = basePath.substring(1);
}
int pos = basePath.indexOf("/");
if (pos > 0) {
basePath = basePath.substring(0, pos);
}
if (basePath.equals("")) {
basePath = "default";
} else {
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;
} else {
super.addOperationToGroup(tag, resourcePath, operation, co, operations);
}
}
@Override
public void preprocessSwagger(Swagger swagger) {
super.preprocessSwagger(swagger);
if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath("");
}
if(!additionalProperties.containsKey(TITLE)) {
// From the title, compute a reasonable name for the package and the API
String title = swagger.getInfo().getTitle();
// Drop any API suffix
if (title != null) {
title = title.trim().replace(" ", "-");
if (title.toUpperCase().endsWith("API")) {
title = title.substring(0, title.length() - 3);
}
this.title = camelize(sanitizeName(title), true);
}
additionalProperties.put(TITLE, this.title);
}
String host = swagger.getHost();
String port = "8080";
if (host != null) {
String[] parts = host.split(":");
if (parts.length > 1) {
port = parts[1];
}
}
this.additionalProperties.put("serverPort", port);
if (swagger.getPaths() != null) {
for (String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if (path.getOperations() != null) {
for (Operation operation : path.getOperations()) {
if (operation.getTags() != null) {
List<Map<String, String>> tags = new ArrayList<Map<String, String>>();
for (String tag : operation.getTags()) {
Map<String, String> value = new HashMap<String, String>();
value.put("tag", tag);
value.put("hasMore", "true");
tags.add(value);
}
if (tags.size() > 0) {
tags.get(tags.size() - 1).remove("hasMore");
}
if (operation.getTags().size() > 0) {
String tag = operation.getTags().get(0);
operation.setTags(Arrays.asList(tag));
}
operation.setVendorExtension("x-tags", tags);
}
}
}
}
}
}
@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) {
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 Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
if(library.equals(SPRING_CLOUD_LIBRARY)) {
List<CodegenSecurity> authMethods = (List<CodegenSecurity>) objs.get("authMethods");
if (authMethods != null) {
for (CodegenSecurity authMethod : authMethods) {
authMethod.name = camelize(sanitizeName(authMethod.name), true);
}
}
}
return objs;
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultApi";
}
name = sanitizeName(name);
return camelize(name) + "Api";
}
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 setInterfaceOnly(boolean interfaceOnly) { this.interfaceOnly = interfaceOnly; }
public void setSingleContentTypes(boolean singleContentTypes) {
this.singleContentTypes = singleContentTypes;
}
public void setJava8(boolean java8) { this.java8 = java8; }
public void setAsync(boolean async) { this.async = async; }
public void setResponseWrapper(String responseWrapper) { this.responseWrapper = responseWrapper; }
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
if ("null".equals(property.example)) {
property.example = null;
}
//Add imports for Jackson
if (!Boolean.TRUE.equals(model.isEnum)) {
model.imports.add("JsonProperty");
if (Boolean.TRUE.equals(model.hasEnums)) {
model.imports.add("JsonValue");
}
} else { // enum class
//Needed imports for Jackson's JsonCreator
if (additionalProperties.containsKey("jackson")) {
model.imports.add("JsonCreator");
}
}
}
@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;
}
}
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import java.io.File;
import java.util.*;
public class SpringCodegen extends AbstractJavaCodegen implements BeanValidationFeatures {
public static final String DEFAULT_LIBRARY = "spring-boot";
public static final String TITLE = "title";
public static final String CONFIG_PACKAGE = "configPackage";
public static final String BASE_PACKAGE = "basePackage";
public static final String INTERFACE_ONLY = "interfaceOnly";
public static final String DELEGATE_PATTERN = "delegatePattern";
public static final String SINGLE_CONTENT_TYPES = "singleContentTypes";
public static final String JAVA_8 = "java8";
public static final String ASYNC = "async";
public static final String RESPONSE_WRAPPER = "responseWrapper";
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";
protected String basePackage = "io.swagger";
protected boolean interfaceOnly = false;
protected boolean delegatePattern = false;
protected boolean singleContentTypes = false;
protected boolean java8 = false;
protected boolean async = false;
protected String responseWrapper = "";
protected boolean useTags = false;
protected boolean useBeanValidation = true;
protected boolean implicitHeaders = false;
public SpringCodegen() {
super();
outputFolder = "generated-code/javaSpring";
apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaSpring";
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
invokerPackage = "io.swagger.api";
artifactId = "swagger-spring";
additionalProperties.put(CONFIG_PACKAGE, configPackage);
additionalProperties.put(BASE_PACKAGE, basePackage);
// spring uses the jackson lib
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(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files."));
cliOptions.add(CliOption.newBoolean(DELEGATE_PATTERN, "Whether to generate the server files using the delegate pattern"));
cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation."));
cliOptions.add(CliOption.newBoolean(JAVA_8, "use java8 default interface"));
cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers"));
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.");
supportedLibraries.put(SPRING_CLOUD_LIBRARY, "Spring-Cloud-Feign client with Spring-Boot auto-configured settings.");
setLibrary(DEFAULT_LIBRARY);
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY);
library.setEnum(supportedLibraries);
library.setDefault(DEFAULT_LIBRARY);
cliOptions.add(library);
}
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
@Override
public String getName() {
return "spring";
}
@Override
public String getHelp() {
return "Generates a Java SpringBoot Server application using the SpringFox integration.";
}
@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(INTERFACE_ONLY)) {
this.setInterfaceOnly(Boolean.valueOf(additionalProperties.get(INTERFACE_ONLY).toString()));
}
if (additionalProperties.containsKey(DELEGATE_PATTERN)) {
this.setDelegatePattern(Boolean.valueOf(additionalProperties.get(DELEGATE_PATTERN).toString()));
}
if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) {
this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString()));
}
if (additionalProperties.containsKey(JAVA_8)) {
this.setJava8(Boolean.valueOf(additionalProperties.get(JAVA_8).toString()));
}
if (additionalProperties.containsKey(ASYNC)) {
this.setAsync(Boolean.valueOf(additionalProperties.get(ASYNC).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);
}
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"));
if (this.interfaceOnly && this.delegatePattern) {
throw new IllegalArgumentException(
String.format("Can not generate code with `%s` and `%s` both true.", DELEGATE_PATTERN, INTERFACE_ONLY));
}
if (!this.interfaceOnly) {
if (library.equals(DEFAULT_LIBRARY)) {
supportingFiles.add(new SupportingFile("homeController.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java"));
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java"));
supportingFiles.add(new SupportingFile("application.mustache",
("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
}
if (library.equals(SPRING_MVC_LIBRARY)) {
supportingFiles.add(new SupportingFile("webApplication.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebApplication.java"));
supportingFiles.add(new SupportingFile("webMvcConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebMvcConfiguration.java"));
supportingFiles.add(new SupportingFile("swaggerUiConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerUiConfiguration.java"));
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java"));
supportingFiles.add(new SupportingFile("application.properties",
("src.main.resources").replace(".", java.io.File.separator), "swagger.properties"));
}
if (library.equals(SPRING_CLOUD_LIBRARY)) {
supportingFiles.add(new SupportingFile("apiKeyRequestInterceptor.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ApiKeyRequestInterceptor.java"));
supportingFiles.add(new SupportingFile("clientConfiguration.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ClientConfiguration.java"));
apiTemplateFiles.put("apiClient.mustache", "Client.java");
if (!additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) {
additionalProperties.put(SINGLE_CONTENT_TYPES, "true");
this.setSingleContentTypes(true);
}
} else {
apiTemplateFiles.put("apiController.mustache", "Controller.java");
supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("apiResponseMessage.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("notFoundException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
}
}
if (!this.delegatePattern && this.java8) {
additionalProperties.put("jdk8-no-delegate", true);
}
if (this.delegatePattern) {
additionalProperties.put("isDelegate", "true");
apiTemplateFiles.put("apiDelegate.mustache", "Delegate.java");
}
if (this.java8) {
additionalProperties.put("javaVersion", "1.8");
additionalProperties.put("jdk8", "true");
if (this.async) {
additionalProperties.put(RESPONSE_WRAPPER, "CompletableFuture");
}
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "OffsetDateTime");
importMapping.put("LocalDate", "java.time.LocalDate");
importMapping.put("OffsetDateTime", "java.time.OffsetDateTime");
} else if (this.async) {
additionalProperties.put(RESPONSE_WRAPPER, "Callable");
}
// 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;
case "ListenableFuture":
additionalProperties.put(RESPONSE_WRAPPER, "org.springframework.util.concurrent.ListenableFuture");
break;
case "DeferredResult":
additionalProperties.put(RESPONSE_WRAPPER, "org.springframework.web.context.request.DeferredResult");
break;
case "HystrixCommand":
additionalProperties.put(RESPONSE_WRAPPER, "com.netflix.hystrix.HystrixCommand");
break;
case "RxObservable":
additionalProperties.put(RESPONSE_WRAPPER, "rx.Observable");
break;
case "RxSingle":
additionalProperties.put(RESPONSE_WRAPPER, "rx.Single");
break;
default:
break;
}
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
if((library.equals(DEFAULT_LIBRARY) || library.equals(SPRING_MVC_LIBRARY)) && !useTags) {
String basePath = resourcePath;
if (basePath.startsWith("/")) {
basePath = basePath.substring(1);
}
int pos = basePath.indexOf("/");
if (pos > 0) {
basePath = basePath.substring(0, pos);
}
if (basePath.equals("")) {
basePath = "default";
} else {
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;
} else {
super.addOperationToGroup(tag, resourcePath, operation, co, operations);
}
}
@Override
public void preprocessSwagger(Swagger swagger) {
super.preprocessSwagger(swagger);
if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath("");
}
if(!additionalProperties.containsKey(TITLE)) {
// From the title, compute a reasonable name for the package and the API
String title = swagger.getInfo().getTitle();
// Drop any API suffix
if (title != null) {
title = title.trim().replace(" ", "-");
if (title.toUpperCase().endsWith("API")) {
title = title.substring(0, title.length() - 3);
}
this.title = camelize(sanitizeName(title), true);
}
additionalProperties.put(TITLE, this.title);
}
String host = swagger.getHost();
String port = "8080";
if (host != null) {
String[] parts = host.split(":");
if (parts.length > 1) {
port = parts[1];
}
}
this.additionalProperties.put("serverPort", port);
if (swagger.getPaths() != null) {
for (String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if (path.getOperations() != null) {
for (Operation operation : path.getOperations()) {
if (operation.getTags() != null) {
List<Map<String, String>> tags = new ArrayList<Map<String, String>>();
for (String tag : operation.getTags()) {
Map<String, String> value = new HashMap<String, String>();
value.put("tag", tag);
value.put("hasMore", "true");
tags.add(value);
}
if (tags.size() > 0) {
tags.get(tags.size() - 1).remove("hasMore");
}
if (operation.getTags().size() > 0) {
String tag = operation.getTags().get(0);
operation.setTags(Arrays.asList(tag));
}
operation.setVendorExtension("x-tags", tags);
}
}
}
}
}
}
@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) {
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";
}
}
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)) {
List<CodegenSecurity> authMethods = (List<CodegenSecurity>) objs.get("authMethods");
if (authMethods != null) {
for (CodegenSecurity authMethod : authMethods) {
authMethod.name = camelize(sanitizeName(authMethod.name), true);
}
}
}
return objs;
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultApi";
}
name = sanitizeName(name);
return camelize(name) + "Api";
}
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 setInterfaceOnly(boolean interfaceOnly) { this.interfaceOnly = interfaceOnly; }
public void setDelegatePattern(boolean delegatePattern) { this.delegatePattern = delegatePattern; }
public void setSingleContentTypes(boolean singleContentTypes) {
this.singleContentTypes = singleContentTypes;
}
public void setJava8(boolean java8) { this.java8 = java8; }
public void setAsync(boolean async) { this.async = async; }
public void setResponseWrapper(String responseWrapper) { this.responseWrapper = responseWrapper; }
public void setUseTags(boolean useTags) {
this.useTags = useTags;
}
public void setImplicitHeaders(boolean implicitHeaders) {
this.implicitHeaders = implicitHeaders;
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
if ("null".equals(property.example)) {
property.example = null;
}
//Add imports for Jackson
if (!Boolean.TRUE.equals(model.isEnum)) {
model.imports.add("JsonProperty");
if (Boolean.TRUE.equals(model.hasEnums)) {
model.imports.add("JsonValue");
}
} else { // enum class
//Needed imports for Jackson's JsonCreator
if (additionalProperties.containsKey("jackson")) {
model.imports.add("JsonCreator");
}
}
}
@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;
}
}

View File

@@ -77,7 +77,10 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}

View File

@@ -1,6 +1,15 @@
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;
@@ -8,16 +17,24 @@ import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client";
protected String invokerPackage = "io.swagger.client"; // default for Java and Android
protected String phpInvokerPackage = "Swagger\\Client"; // default for PHP
protected String packageName = "IO.Swagger"; // default for C#
protected String groupId = "io.swagger";
protected String artifactId = "swagger-client";
protected String artifactVersion = "1.0.0";
protected String jsProjectName;
protected String jsModuleName;
protected String perlModuleName = "WWW::SwaggerClient";
protected String pythonPackageName = "swagger_client";
public StaticHtml2Generator() {
super();
@@ -33,6 +50,10 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi
cliOptions.add(new CliOption("licenseInfo", "a short description of the license"));
cliOptions.add(new CliOption("licenseUrl", "a URL pointing to the full license"));
cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.PHP_INVOKER_PACKAGE, CodegenConstants.PHP_INVOKER_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.PERL_MODULE_NAME, CodegenConstants.PERL_MODULE_NAME_DESC));
cliOptions.add(new CliOption(CodegenConstants.PYTHON_PACKAGE_NAME, CodegenConstants.PYTHON_PACKAGE_NAME_DESC));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name"));
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));
@@ -44,6 +65,10 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi
additionalProperties.put("licenseInfo", "All rights reserved");
additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html");
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put(CodegenConstants.PHP_INVOKER_PACKAGE, phpInvokerPackage);
additionalProperties.put(CodegenConstants.PERL_MODULE_NAME, perlModuleName);
additionalProperties.put(CodegenConstants.PYTHON_PACKAGE_NAME, pythonPackageName);
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
@@ -97,10 +122,38 @@ 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;
}
@Override
public void preprocessSwagger(Swagger swagger) {
super.preprocessSwagger(swagger);
if (swagger.getInfo() != null) {
Info info = swagger.getInfo();
if (StringUtils.isBlank(jsProjectName) && info.getTitle() != null) {
// when jsProjectName is not specified, generate it from info.title
jsProjectName = sanitizeName(dashize(info.getTitle()));
}
}
// default values
if (StringUtils.isBlank(jsProjectName)) {
jsProjectName = "swagger-js-client";
}
if (StringUtils.isBlank(jsModuleName)) {
jsModuleName = camelize(underscore(jsProjectName));
}
additionalProperties.put("jsProjectName", jsProjectName);
additionalProperties.put("jsModuleName", jsModuleName);
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
@@ -119,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

@@ -3,21 +3,31 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Operation;
import io.swagger.models.Info;
import io.swagger.models.Model;
import io.swagger.models.Swagger;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.ArrayList;
import io.swagger.codegen.utils.Markdown;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import com.samskivert.mustache.Escapers;
import com.samskivert.mustache.Mustache.Compiler;
import io.swagger.codegen.utils.Markdown;
public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger";
@@ -41,7 +51,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");
@@ -60,13 +70,19 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
importMapping = new HashMap<String, String>();
}
@Override
/**
* Convert Markdown (CommonMark) to HTML. This class also disables normal HTML
* escaping in the Mustache engine (see {@link #processCompiler(Compiler)} above.)
*/
@Override
public String escapeText(String input) {
// newline escaping disabled for HTML documentation for markdown to work correctly
return input;
return toHtml(input);
}
@Override
@Override
public CodegenType getTag() {
return CodegenType.DOCUMENTATION;
}
@@ -96,12 +112,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;
}
@@ -118,4 +139,61 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
// just return the original string
return input;
}
/**
* Markdown conversion emits HTML and by default, the Mustache
* {@link Compiler} will escape HTML. For example a summary
* <code>"Text with **bold**"</code> is converted from Markdown to HTML as
* <code>"Text with &lt;strong&gt;bold&lt;/strong&gt; text"</code> and then
* the default compiler with HTML escaping on turns this into
* <code>"Text with &amp;lt;strong&amp;gt;bold&amp;lt;/strong&amp;gt; text"</code>.
* Here, we disable escaping by setting the compiler to {@link Escapers#NONE
* Escapers.NONE}
*/
@Override
public Compiler processCompiler(Compiler compiler) {
return compiler.withEscaper(Escapers.NONE);
}
private Markdown markdownConverter = new Markdown();
private static final boolean CONVERT_TO_MARKDOWN_VIA_ESCAPE_TEXT = false;
/**
* Convert Markdown text to HTML
* @param input text in Markdown; may be null.
* @return the text, converted to Markdown. For null input, "" is returned.
*/
public String toHtml(String input) {
if (input == null)
return "";
return markdownConverter.toHtml(input);
}
public void preprocessSwagger(Swagger swagger) {
Info info = swagger.getInfo();
info.setDescription(toHtml(info.getDescription()));
info.setTitle(toHtml(info.getTitle()));
Map<String, Model> models = swagger.getDefinitions();
for (Model model : models.values()) {
model.setDescription(toHtml(model.getDescription()));
model.setTitle(toHtml(model.getTitle()));
}
}
// override to post-process any parameters
public void postProcessParameter(CodegenParameter parameter) {
parameter.description = toHtml(parameter.description);
parameter.unescapedDescription = toHtml(
parameter.unescapedDescription);
}
// override to post-process any model properties
public void postProcessModelProperty(CodegenModel model,
CodegenProperty property) {
property.description = toHtml(property.description);
property.unescapedDescription = toHtml(
property.unescapedDescription);
}
}

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

@@ -46,7 +46,6 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
protected boolean swiftUseApiNamespace;
protected String[] responseAs = new String[0];
protected String sourceFolder = "Classes" + File.separator + "Swaggers";
private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}");
@Override
public CodegenType getTag() {
@@ -103,7 +102,7 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
reservedWords = new HashSet<>(
Arrays.asList(
// name used by swift client
"ErrorResponse",
"ErrorResponse", "Response",
// swift keywords
"Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", "Any", "Error", "URL",
@@ -185,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);
@@ -208,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);
@@ -235,10 +233,13 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name; // add an underscore to the name
}
@Override
public String modelFileFolder() {
return outputFolder + File.separator + sourceFolder + modelPackage().replace('.', File.separatorChar);
@@ -276,6 +277,11 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
return toModelName(type);
}
@Override
public boolean isDataTypeFile(String dataType) {
return dataType != null && dataType.equals("URL");
}
@Override
public boolean isDataTypeBinary(final String dataType) {
return dataType != null && dataType.equals("Data");
@@ -448,47 +454,6 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
return codegenModel;
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
List<Parameter> parameters = operation.getParameters();
parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate<Parameter>() {
@Override
public boolean apply(@Nullable Parameter parameter) {
return !(parameter instanceof HeaderParameter);
}
}));
operation.setParameters(parameters);
return super.fromOperation(path, httpMethod, operation, definitions, swagger);
}
private static String normalizePath(String path) {
StringBuilder builder = new StringBuilder();
int cursor = 0;
Matcher matcher = PATH_PARAM_PATTERN.matcher(path);
boolean found = matcher.find();
while (found) {
String stringBeforeMatch = path.substring(cursor, matcher.start());
builder.append(stringBeforeMatch);
String group = matcher.group().substring(1, matcher.group().length() - 1);
group = camelize(group, true);
builder
.append("{")
.append(group)
.append("}");
cursor = matcher.end();
found = matcher.find();
}
String stringAfterMatch = path.substring(cursor);
builder.append(stringAfterMatch);
return builder.toString();
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
@@ -501,6 +466,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);
@@ -513,24 +482,38 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toEnumVarName(String name, String datatype) {
if (name.length() == 0) {
return "empty";
}
Pattern startWithNumberPattern = Pattern.compile("^\\d+");
Matcher startWithNumberMatcher = startWithNumberPattern.matcher(name);
if (startWithNumberMatcher.find()) {
String startingNumbers = startWithNumberMatcher.group(0);
String nameWithoutStartingNumbers = name.substring(startingNumbers.length());
return "_" + startingNumbers + camelize(nameWithoutStartingNumbers, true);
}
// for symbol, e.g. $, #
if (getSymbolName(name) != null) {
return camelize(WordUtils.capitalizeFully(getSymbolName(name).toUpperCase()), true);
}
// Camelize only when we have a structure defined below
Boolean camelized = false;
if (name.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) {
name = camelize(name, true);
camelized = true;
}
// Reserved Name
if (isReservedWord(name)) {
return escapeReservedWord(name);
// Camelize only when we have a structure defined below
Boolean camelized = false;
if (name.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) {
name = camelize(name, true);
camelized = true;
}
// Check for numerical conversions
// Reserved Name
String nameLowercase = StringUtils.lowerCase(name);
if (isReservedWord(nameLowercase)) {
return escapeReservedWord(nameLowercase);
}
// Check for numerical conversions
if ("Int".equals(datatype) || "Int32".equals(datatype) || "Int64".equals(datatype) ||
"Float".equals(datatype) || "Double".equals(datatype)) {
String varName = "number" + camelize(name);
@@ -540,11 +523,11 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
return varName;
}
// If we have already camelized the word, don't progress
// any further
if (camelized) {
return name;
}
// If we have already camelized the word, don't progress
// any further
if (camelized) {
return name;
}
char[] separators = {'-', '_', ' ', ':', '(', ')'};
return camelize(WordUtils.capitalizeFully(StringUtils.lowerCase(name), separators).replaceAll("[-_ :\\(\\)]", ""), true);
@@ -621,7 +604,7 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
int count = 0, numVars = codegenProperties.size();
for(CodegenProperty codegenProperty : codegenProperties) {
count += 1;
codegenProperty.hasMore = (count < numVars) ? true : null;
codegenProperty.hasMore = (count < numVars) ? true : false;
}
codegenModel.vars = codegenProperties;
}

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);
@@ -232,11 +230,14 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
protected boolean isReservedWord(String word) {
return word != null && reservedWords.contains(word); //don't lowercase as super does
}
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name; // add an underscore to the name
}
@Override
public String modelFileFolder() {
@@ -275,9 +276,14 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
return toModelName(type);
}
@Override
public boolean isDataTypeFile(String dataType) {
return dataType != null && dataType.equals("NSURL");
}
@Override
public boolean isDataTypeBinary(final String dataType) {
return dataType != null && dataType.equals("NSData");
return dataType != null && dataType.equals("NSData");
}
/**
@@ -388,6 +394,10 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
@SuppressWarnings("static-method")
public String toSwiftyEnumName(String value) {
if (value.length() == 0) {
return "Empty";
}
if (value.matches("^-?\\d*\\.{0,1}\\d+.*")) { // starts with number
value = "Number" + value;
value = value.replaceAll("-", "Minus");
@@ -481,14 +491,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
List<Parameter> parameters = operation.getParameters();
parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate<Parameter>() {
@Override
public boolean apply(@Nullable Parameter parameter) {
return !(parameter instanceof HeaderParameter);
}
}));
operation.setParameters(parameters);
// issue 3914 - removed logic designed to remove any parameter of type HeaderParameter
return super.fromOperation(path, httpMethod, operation, definitions, swagger);
}
@@ -531,6 +534,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

@@ -261,7 +261,10 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
}
@Override
public String escapeReservedWord(String name) {
public String escapeReservedWord(String name) {
if(this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}

View File

@@ -132,7 +132,7 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
if(languageSpecificPrimitives.contains(swaggerType)) {
if(isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) {
return swaggerType;
}
return addModelPrefix(swaggerType);
@@ -146,15 +146,19 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
type = swaggerType;
}
if (!startsWithLanguageSpecificPrimitiv(type)) {
if (!isLanguagePrimitive(type) && !isLanguageGenericType(type)) {
type = "models." + swaggerType;
}
return type;
}
private boolean startsWithLanguageSpecificPrimitiv(String type) {
for (String langPrimitive:languageSpecificPrimitives) {
if (type.startsWith(langPrimitive)) {
private boolean isLanguagePrimitive(String type) {
return languageSpecificPrimitives.contains(type);
}
private boolean isLanguageGenericType(String type) {
for (String genericType: languageGenericTypes) {
if (type.startsWith(genericType + "<")) {
return true;
}
}

View File

@@ -3,35 +3,87 @@ package io.swagger.codegen.languages;
import java.io.File;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.CodegenParameter;
import io.swagger.models.properties.Property;
public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCodegen {
@Override
public String getName() {
return "typescript-angular";
}
@Override
public String getName() {
return "typescript-angular";
}
@Override
public String getHelp() {
return "Generates a TypeScript AngularJS client library.";
}
@Override
public String getHelp() {
return "Generates a TypeScript AngularJS client library.";
}
@Override
public void processOpts() {
super.processOpts();
supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage().replace('.', File.separatorChar), "api.d.ts"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
@Override
public void processOpts() {
super.processOpts();
supportingFiles.add(new SupportingFile("models.mustache", modelPackage().replace('.', File.separatorChar), "models.ts"));
supportingFiles.add(new SupportingFile("apis.mustache", apiPackage().replace('.', File.separatorChar), "api.ts"));
supportingFiles.add(new SupportingFile("index.mustache", getIndexDirectory(), "index.ts"));
supportingFiles.add(new SupportingFile("api.module.mustache", getIndexDirectory(), "api.module.ts"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
}
public TypeScriptAngularClientCodegen() {
super();
outputFolder = "generated-code/typescript-angular";
modelTemplateFiles.put("model.mustache", ".ts");
apiTemplateFiles.put("api.mustache", ".ts");
embeddedTemplateDir = templateDir = "typescript-angular";
apiPackage = "API.Client";
modelPackage = "API.Client";
}
}
public TypeScriptAngularClientCodegen() {
super();
outputFolder = "generated-code/typescript-angular";
modelTemplateFiles.put("model.mustache", ".ts");
apiTemplateFiles.put("api.mustache", ".ts");
embeddedTemplateDir = templateDir = "typescript-angular";
apiPackage = "api";
modelPackage = "model";
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
if(isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) {
return swaggerType;
}
return addModelPrefix(swaggerType);
}
@Override
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
parameter.dataType = addModelPrefix(parameter.dataType);
}
private String getIndexDirectory() {
String indexPackage = modelPackage.substring(0, Math.max(0, modelPackage.lastIndexOf('.')));
return indexPackage.replace('.', File.separatorChar);
}
private String addModelPrefix(String swaggerType) {
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
} else {
type = swaggerType;
}
if (!isLanguagePrimitive(type) && !isLanguageGenericType(type)) {
type = "models." + swaggerType;
}
return type;
}
private boolean isLanguagePrimitive(String type) {
return languageSpecificPrimitives.contains(type);
}
private boolean isLanguageGenericType(String type) {
for (String genericType: languageGenericTypes) {
if (type.startsWith(genericType + "<")) {
return true;
}
}
return false;
}
}

View File

@@ -40,6 +40,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
supportingFiles.add(new SupportingFile("package.json.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("typings.json.mustache", "", "typings.json"));
supportingFiles.add(new SupportingFile("tsconfig.json.mustache", "", "tsconfig.json"));
supportingFiles.add(new SupportingFile("tslint.json.mustache", "", "tslint.json"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
if(additionalProperties.containsKey(NPM_NAME)) {

View File

@@ -0,0 +1,110 @@
package io.swagger.codegen.languages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.BooleanProperty;
public class TypeScriptJqueryClientCodegen extends AbstractTypeScriptClientCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptNodeClientCodegen.class);
private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm");
public static final String NPM_NAME = "npmName";
public static final String NPM_VERSION = "npmVersion";
public static final String NPM_REPOSITORY = "npmRepository";
public static final String SNAPSHOT = "snapshot";
protected String npmName = null;
protected String npmVersion = "1.0.0";
protected String npmRepository = null;
public TypeScriptJqueryClientCodegen() {
super();
outputFolder = "generated-code/typescript-jquery";
embeddedTemplateDir = templateDir = "typescript-jquery";
this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package"));
this.cliOptions.add(new CliOption(NPM_VERSION, "The version of your npm package"));
this.cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json"));
this.cliOptions.add(new CliOption(SNAPSHOT, "When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm", BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString()));
}
@Override
public void processOpts() {
super.processOpts();
supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
LOGGER.warn("check additionals: " + additionalProperties.get(NPM_NAME));
if(additionalProperties.containsKey(NPM_NAME)) {
addNpmPackageGeneration();
}
}
private void addNpmPackageGeneration() {
if(additionalProperties.containsKey(NPM_NAME)) {
this.setNpmName(additionalProperties.get(NPM_NAME).toString());
}
if (additionalProperties.containsKey(NPM_VERSION)) {
this.setNpmVersion(additionalProperties.get(NPM_VERSION).toString());
}
if (additionalProperties.containsKey(SNAPSHOT) && Boolean.valueOf(additionalProperties.get(SNAPSHOT).toString())) {
this.setNpmVersion(npmVersion + "-SNAPSHOT." + SNAPSHOT_SUFFIX_FORMAT.format(new Date()));
}
additionalProperties.put(NPM_VERSION, npmVersion);
if (additionalProperties.containsKey(NPM_REPOSITORY)) {
this.setNpmRepository(additionalProperties.get(NPM_REPOSITORY).toString());
}
//Files for building our lib
supportingFiles.add(new SupportingFile("package.mustache", getPackageRootDirectory(), "package.json"));
supportingFiles.add(new SupportingFile("typings.mustache", getPackageRootDirectory(), "typings.json"));
supportingFiles.add(new SupportingFile("tsconfig.mustache", getPackageRootDirectory(), "tsconfig.json"));
}
private String getPackageRootDirectory() {
String indexPackage = modelPackage.substring(0, Math.max(0, modelPackage.lastIndexOf('.')));
return indexPackage.replace('.', File.separatorChar);
}
@Override
public String getName() {
return "typescript-jquery";
}
@Override
public String getHelp() {
return "Generates a TypeScript jquery client library.";
}
public void setNpmName(String npmName) {
this.npmName = npmName;
}
public void setNpmVersion(String npmVersion) {
this.npmVersion = npmVersion;
}
public String getNpmVersion() {
return npmVersion;
}
public String getNpmRepository() {
return npmRepository;
}
public void setNpmRepository(String npmRepository) {
this.npmRepository = npmRepository;
}
}

View File

@@ -1,5 +1,7 @@
package io.swagger.codegen.languages;
import io.swagger.models.properties.FileProperty;
import io.swagger.models.properties.Property;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -27,6 +29,8 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen
public TypeScriptNodeClientCodegen() {
super();
typeMapping.put("file", "Buffer");
// clear import mapping (from default generator) as TS does not use it
// at the moment
importMapping.clear();
@@ -92,6 +96,19 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen
return "Generates a TypeScript nodejs client library.";
}
@Override
public boolean isDataTypeFile(final String dataType) {
return dataType != null && dataType.equals("Buffer");
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof FileProperty) {
return "Buffer";
}
return super.getTypeDeclaration(p);
}
public void setNpmName(String npmName) {
this.npmName = npmName;

View File

@@ -0,0 +1,216 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Operation;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ZendExpressivePathHandlerServerCodegen extends AbstractPhpCodegen {
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
@Override
public String getName() {
return "ze-ph";
}
@Override
public String getHelp() {
return "Generates PHP server stub using Zend Expressive ( https://zendframework.github.io/zend-expressive ) and Path Handler ( https://github.com/Articus/PathHandler ).";
}
public ZendExpressivePathHandlerServerCodegen() {
super();
embeddedTemplateDir = templateDir = "ze-ph";
invokerPackage = "App";
packagePath = "";
srcBasePath = "src" + File.separator + "App";
apiDirName = "Handler";
modelDirName = "DTO";
apiPackage = invokerPackage + "\\" + apiDirName;
modelPackage = invokerPackage + "\\" + modelDirName;
apiTestTemplateFiles.clear();
modelTestTemplateFiles.clear();
apiDocTemplateFiles.clear();
modelDocTemplateFiles.clear();
supportingFiles.add(new SupportingFile("README.md.mustache", packagePath, "README.md"));
supportingFiles.add(new SupportingFile("composer.json.mustache", packagePath, "composer.json"));
supportingFiles.add(new SupportingFile("index.php", packagePath + File.separator + "public", "index.php"));
supportingFiles.add(new SupportingFile("container.php", packagePath + File.separator + "application", "container.php"));
supportingFiles.add(new SupportingFile("config.yml", packagePath + File.separator + "application", "config.yml"));
supportingFiles.add(new SupportingFile("app.yml.mustache", packagePath + File.separator + "application" + File.separator + "config", "app.yml"));
supportingFiles.add(new SupportingFile("path_handler.yml.mustache", packagePath + File.separator + "application" + File.separator + "config", "path_handler.yml"));
supportingFiles.add(new SupportingFile("data_transfer.yml.mustache", packagePath + File.separator + "application" + File.separator + "config", "data_transfer.yml"));
supportingFiles.add(new SupportingFile("Date.php.mustache", packagePath + File.separator + srcBasePath + File.separator + "Strategy", "Date.php"));
supportingFiles.add(new SupportingFile("DateTime.php.mustache", packagePath + File.separator + srcBasePath + File.separator + "Strategy", "DateTime.php"));
supportingFiles.add(new SupportingFile("Type.php.mustache", packagePath + File.separator + srcBasePath + File.separator + "Validator", "Type.php"));
supportingFiles.add(new SupportingFile("ErrorMiddleware.php.mustache", packagePath + File.separator + srcBasePath, "ErrorMiddleware.php"));
additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, "1.0.0");
}
/**
* Add operation to group
* Override of default grouping - group by resource path, not tag
*
* @param tag name of the tag
* @param resourcePath path of the resource
* @param operation Swagger Operation object
* @param co Codegen Operation object
* @param operations map of Codegen operations
*/
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
List<CodegenOperation> opList = operations.get(resourcePath);
if (opList == null) {
opList = new ArrayList<CodegenOperation>();
operations.put(resourcePath, opList);
}
//ignore duplicate operation ids - that means that operation has several tags
int counter = 0;
for (CodegenOperation op : opList) {
if (co.operationId.equals(op.operationId)) {
counter++;
}
}
if (counter == 0) {
co.operationIdLowerCase = co.operationId.toLowerCase();
opList.add(co);
co.baseName = tag;
}
}
/**
* Return the file name of the Api Test
*
* @param name the file name of the Api
* @return the file name of the Api
*/
@Override
public String toApiFilename(String name) {
return toApiName(name);
}
/**
* Output the API (class) name (capitalized) ending with "Api"
* Return DefaultApi if name is empty
*
* @param name the name of the Api
* @return capitalized Api name ending with "Api"
*/
@Override
public String toApiName(String name) {
//Remove }
name = name.replaceAll("[\\}]", "");
return super.toModelName(name);
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
objs = super.postProcessOperations(objs);
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
String interfaceToImplement;
StringBuilder interfacesToImplement = new StringBuilder();
String classMethod;
for (CodegenOperation op : operationList) {
switch (op.httpMethod) {
case "GET":
interfaceToImplement = "Operation\\GetInterface";
classMethod = "handleGet";
break;
case "POST":
interfaceToImplement = "Operation\\PostInterface";
classMethod = "handlePost";
break;
case "PATCH":
interfaceToImplement = "Operation\\PatchInterface";
classMethod = "handlePatch";
break;
case "PUT":
interfaceToImplement = "Operation\\PutInterface";
classMethod = "handlePut";
break;
case "DELETE":
interfaceToImplement = "Operation\\DeleteInterface";
classMethod = "handleDelete";
break;
default:
throw new RuntimeException("Unknown HTTP Method " + op.httpMethod + " not allowed");
}
if (interfacesToImplement.length() > 0) {
interfacesToImplement.append(", ");
}
interfacesToImplement.append(interfaceToImplement);
op.httpMethod = classMethod;
}
operations.put("interfacesToImplement", interfacesToImplement.toString());
return objs;
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
objs = super.postProcessSupportingFileData(objs);
Map<String, Object> apiInfo = (Map<String, Object>) objs.get("apiInfo");
List<Map<String, Object>> apis = (List<Map<String, Object>>) apiInfo.get("apis");
List<Map<String, Object>> routes = new ArrayList<Map<String, Object>>();
for (Map<String, Object> api : apis) {
String handler = (String) api.get("classname");
String url = (String) api.get("baseName");
if (url.charAt(0) == '/') {
url = url.substring(1);
}
insertRoute(routes, url.split("/"), 0, handler);
}
objs.put("routes", routes);
return objs;
}
private void insertRoute(List<Map<String, Object>> routes, String[] urlParts, int currentUrlPartIndex, String handler) {
if (urlParts.length > currentUrlPartIndex) {
String urlPart = urlParts[currentUrlPartIndex];
//List<Map<String, Object>> subRoutes = null;
Map<String, Object> currentRoute = null;
for (Map<String, Object> route : routes) {
if (urlPart.equals(route.get("name"))) {
currentRoute = route;
break;
}
}
if (currentRoute == null) {
currentRoute = new HashMap<String, Object>();
String routePart = urlPart.replaceAll("^\\{(\\w+)\\}$", ":$1");
boolean isLastUrlPart = currentUrlPartIndex == urlParts.length - 1;
currentRoute.put("name", urlPart);
currentRoute.put("route", "/" + routePart);
currentRoute.put("type", (urlPart == routePart) ? "Literal" : "Segment");
currentRoute.put("handler", isLastUrlPart ? handler : null);
currentRoute.put("hasChildren", false);
currentRoute.put("children", new ArrayList<Map<String, Object>>());
currentRoute.put("padding", StringUtils.repeat(' ', 4 * currentUrlPartIndex));
routes.add(currentRoute);
}
List<Map<String, Object>> subRoutes = (List<Map<String, Object>>) currentRoute.get("children");
insertRoute(subRoutes, urlParts, currentUrlPartIndex + 1, handler);
currentRoute.put("hasChildren", !subRoutes.isEmpty());
}
}
}

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";
@@ -15,10 +14,18 @@ public interface CXFServerFeatures
public static final String ADD_CONSUMES_PRODUCES_JSON = "addConsumesProducesJson";
public static final String USE_ANNOTATED_BASE_PATH = "useAnnotatedBasePath";
public static final String GENERATE_NON_SPRING_APPLICATION = "generateNonSpringApplication";
public void setUseWadlFeature(boolean useWadlFeature);
public void setUseMultipartFeature(boolean useMultipartFeature);
public void setAddConsumesProducesJson(boolean addConsumesProducesJson);
public void setUseAnnotatedBasePath(boolean useAnnotatedBasePath);
public void setGenerateNonSpringApplication(boolean generateNonSpringApplication);
}

View File

@@ -0,0 +1,10 @@
package io.swagger.codegen.languages.features;
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";

View File

@@ -0,0 +1,9 @@
package io.swagger.codegen.languages.features;
public interface UseGenericResponseFeatures {
// Language supports generating generic Jaxrs or native return types
public static final String USE_GENERIC_RESPONSE = "useGenericResponse";
public void setUseGenericResponse(boolean useGenericResponse);
}

View File

@@ -0,0 +1,47 @@
package io.swagger.codegen.utils;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
/**
* Utility class to convert Markdown (CommonMark) to HTML.
* <a href='https://github.com/atlassian/commonmark-java/issues/83'>This class is threadsafe.</a>
*/
public class Markdown {
// see https://github.com/atlassian/commonmark-java
private final Parser parser = Parser.builder().build();
private final HtmlRenderer renderer = HtmlRenderer.builder().build();
/**
* Convert input markdown text to HTML.
* Simple text is not wrapped in <p>...</p>.
* @param markdown text with Markdown styles. If <code>null<code>, </code>""</code> is returned.
* @return HTML rendering from the Markdown
*/
public String toHtml(String markdown) {
if (markdown == null)
return "";
Node document = parser.parse(markdown);
String html = renderer.render(document);
html = unwrapped(html);
return html;
}
// The CommonMark library wraps the HTML with
// <p> ... html ... </p>\n
// This method removes that markup wrapper if there are no other <p> elements,
// do that Markdown can be used in non-block contexts such as operation summary etc.
private static final String P_END = "</p>\n";
private static final String P_START = "<p>";
private String unwrapped(String html) {
if (html.startsWith(P_START) && html.endsWith(P_END)
&& html.lastIndexOf(P_START) == 0)
return html.substring(P_START.length(),
html.length() - P_END.length());
else
return html;
}
}

View File

@@ -1,9 +1,10 @@
package io.swagger.codegen.utils;
import org.apache.commons.lang3.tuple.Pair;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import joptsimple.internal.Strings;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
@@ -22,10 +23,10 @@ public class OptionUtils {
results.add(pair);
}
}
//Strings.isNullOrEmpty(input)
return results;
}
public static List<String> splitCommaSeparatedList(String input) {
List<String> results = new ArrayList<String>();
@@ -39,5 +40,4 @@ public class OptionUtils {
return results;
}
}