diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java deleted file mode 100644 index ced84fef21a..00000000000 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ /dev/null @@ -1,1304 +0,0 @@ -package io.swagger.codegen.languages; - -import java.io.File; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.regex.Pattern; - -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.lang3.StringUtils; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Strings; - -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.DefaultCodegen; -import io.swagger.models.Model; -import io.swagger.models.Operation; -import io.swagger.models.Path; -import io.swagger.models.Swagger; -import io.swagger.models.parameters.BodyParameter; -import io.swagger.models.parameters.FormParameter; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DoubleProperty; -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.Property; -import io.swagger.models.properties.StringProperty; - - -public abstract class AbstractJavaCodegen extends DefaultCodegen implements CodegenConfig { - - static Logger LOGGER = LoggerFactory.getLogger(AbstractJavaCodegen.class); - public static final String FULL_JAVA_UTIL = "fullJavaUtil"; - public static final String DEFAULT_LIBRARY = ""; - public static final String DATE_LIBRARY = "dateLibrary"; - public static final String JAVA8_MODE = "java8"; - public static final String SUPPORT_ASYNC = "supportAsync"; - public static final String WITH_XML = "withXml"; - public static final String SUPPORT_JAVA6 = "supportJava6"; - - protected String dateLibrary = "threetenbp"; - protected boolean supportAsync = false; - protected boolean java8Mode = false; - protected boolean withXml = false; - protected String invokerPackage = "io.swagger"; - 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"; - protected String testFolder = projectTestFolder + File.separator + "java"; - protected String localVariablePrefix = ""; - protected boolean fullJavaUtil; - protected String javaUtilPrefix = ""; - protected Boolean serializableModel = false; - protected boolean serializeBigDecimalAsString = false; - protected boolean hideGenerationTimestamp = false; - protected String apiDocPath = "docs/"; - protected String modelDocPath = "docs/"; - protected boolean supportJava6= false; - - public AbstractJavaCodegen() { - super(); - supportsInheritance = true; - modelTemplateFiles.put("model.mustache", ".java"); - apiTemplateFiles.put("api.mustache", ".java"); - apiTestTemplateFiles.put("api_test.mustache", ".java"); - modelDocTemplateFiles.put("model_doc.mustache", ".md"); - apiDocTemplateFiles.put("api_doc.mustache", ".md"); - - setReservedWordsLowerCase( - Arrays.asList( - // used as internal variables, can collide with parameter names - "localVarPath", "localVarQueryParams", "localVarCollectionQueryParams", - "localVarHeaderParams", "localVarFormParams", "localVarPostBody", - "localVarAccepts", "localVarAccept", "localVarContentTypes", - "localVarContentType", "localVarAuthNames", "localReturnType", - "ApiClient", "ApiException", "ApiResponse", "Configuration", "StringUtil", - - // language reserved words - "abstract", "continue", "for", "new", "switch", "assert", - "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", - "this", "break", "double", "implements", "protected", "throw", "byte", "else", - "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", - "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", - "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", - "native", "super", "while", "null") - ); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Object", - "byte[]") - ); - instantiationTypes.put("array", "ArrayList"); - instantiationTypes.put("map", "HashMap"); - typeMapping.put("date", "Date"); - typeMapping.put("file", "File"); - - cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); - 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)); - cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, CodegenConstants - .SERIALIZE_BIG_DECIMAL_AS_STRING_DESC)); - cliOptions.add(CliOption.newBoolean(FULL_JAVA_UTIL, "whether to use fully qualified name for classes under java.util. This option only works for Java API client")); - cliOptions.add(new CliOption("hideGenerationTimestamp", "hides the timestamp when files were generated")); - cliOptions.add(CliOption.newBoolean(WITH_XML, "whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)")); - - CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use"); - Map dateOptions = new HashMap(); - dateOptions.put("java8", "Java 8 native JSR310 (preferred for jdk 1.8+) - note: this also sets \"" + JAVA8_MODE + "\" to true"); - dateOptions.put("threetenbp", "Backport of JSR310 (preferred for jdk < 1.8)"); - dateOptions.put("java8-localdatetime", "Java 8 using LocalDateTime (for legacy app only)"); - dateOptions.put("joda", "Joda (for legacy app only)"); - dateOptions.put("legacy", "Legacy java.util.Date (if you really have a good reason not to use threetenbp"); - dateLibrary.setEnum(dateOptions); - cliOptions.add(dateLibrary); - - CliOption java8Mode = new CliOption(JAVA8_MODE, "Option. Use Java8 classes instead of third party equivalents"); - Map java8ModeOptions = new HashMap(); - java8ModeOptions.put("true", "Use Java 8 classes such as Base64"); - java8ModeOptions.put("false", "Various third party libraries as needed"); - java8Mode.setEnum(java8ModeOptions); - cliOptions.add(java8Mode); - } - - @Override - public void processOpts() { - super.processOpts(); - - if (additionalProperties.containsKey(SUPPORT_JAVA6)) { - this.setSupportJava6(Boolean.valueOf(additionalProperties.get(SUPPORT_JAVA6).toString())); - } - additionalProperties.put(SUPPORT_JAVA6, supportJava6); - - - if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { - this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); - } else if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { - // guess from api package - String derviedInvokerPackage = deriveInvokerPackageName((String)additionalProperties.get(CodegenConstants.API_PACKAGE)); - this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, derviedInvokerPackage); - this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); - LOGGER.info("Invoker Package Name, originally not set, is now dervied from api package name: " + derviedInvokerPackage); - } else if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { - // guess from model package - String derviedInvokerPackage = deriveInvokerPackageName((String)additionalProperties.get(CodegenConstants.MODEL_PACKAGE)); - this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, derviedInvokerPackage); - this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); - LOGGER.info("Invoker Package Name, originally not set, is now dervied from model package name: " + derviedInvokerPackage); - } else { - //not set, use default to be passed to template - additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); - } - - if (additionalProperties.containsKey(CodegenConstants.GROUP_ID)) { - this.setGroupId((String) additionalProperties.get(CodegenConstants.GROUP_ID)); - } else { - //not set, use to be passed to template - additionalProperties.put(CodegenConstants.GROUP_ID, groupId); - } - - if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_ID)) { - this.setArtifactId((String) additionalProperties.get(CodegenConstants.ARTIFACT_ID)); - } else { - //not set, use to be passed to template - additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); - } - - if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) { - this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION)); - } else { - //not set, use to be passed to template - 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)); - } - - if (additionalProperties.containsKey(CodegenConstants.LOCAL_VARIABLE_PREFIX)) { - this.setLocalVariablePrefix((String) additionalProperties.get(CodegenConstants.LOCAL_VARIABLE_PREFIX)); - } - - if (additionalProperties.containsKey(CodegenConstants.SERIALIZABLE_MODEL)) { - this.setSerializableModel(Boolean.valueOf(additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL).toString())); - } - - if (additionalProperties.containsKey(CodegenConstants.LIBRARY)) { - this.setLibrary((String) additionalProperties.get(CodegenConstants.LIBRARY)); - } - - if(additionalProperties.containsKey(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING)) { - this.setSerializeBigDecimalAsString(Boolean.valueOf(additionalProperties.get(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING).toString())); - } - - // need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string - additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel); - - if (additionalProperties.containsKey(FULL_JAVA_UTIL)) { - this.setFullJavaUtil(Boolean.valueOf(additionalProperties.get(FULL_JAVA_UTIL).toString())); - } - - if (fullJavaUtil) { - javaUtilPrefix = "java.util."; - } - additionalProperties.put(FULL_JAVA_UTIL, fullJavaUtil); - additionalProperties.put("javaUtilPrefix", javaUtilPrefix); - - if (additionalProperties.containsKey(WITH_XML)) { - this.setWithXml(Boolean.valueOf(additionalProperties.get(WITH_XML).toString())); - } - additionalProperties.put(WITH_XML, withXml); - - // make api and model doc path available in mustache template - additionalProperties.put("apiDocPath", apiDocPath); - additionalProperties.put("modelDocPath", modelDocPath); - - importMapping.put("List", "java.util.List"); - - if (fullJavaUtil) { - 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"); - importMapping.remove("HashMap"); - importMapping.remove("Array"); - importMapping.remove("ArrayList"); - importMapping.remove("List"); - importMapping.remove("Set"); - importMapping.remove("DateTime"); - importMapping.remove("UUID"); - instantiationTypes.put("array", "java.util.ArrayList"); - instantiationTypes.put("map", "java.util.HashMap"); - } - - this.sanitizeConfig(); - - // optional jackson mappings for BigDecimal support - importMapping.put("ToStringSerializer", "com.fasterxml.jackson.databind.ser.std.ToStringSerializer"); - importMapping.put("JsonSerialize", "com.fasterxml.jackson.databind.annotation.JsonSerialize"); - - // imports for pojos - importMapping.put("ApiModelProperty", "io.swagger.annotations.ApiModelProperty"); - importMapping.put("ApiModel", "io.swagger.annotations.ApiModel"); - importMapping.put("JsonProperty", "com.fasterxml.jackson.annotation.JsonProperty"); - importMapping.put("JsonSubTypes", "com.fasterxml.jackson.annotation.JsonSubTypes"); - importMapping.put("JsonTypeInfo", "com.fasterxml.jackson.annotation.JsonTypeInfo"); - importMapping.put("JsonCreator", "com.fasterxml.jackson.annotation.JsonCreator"); - importMapping.put("JsonValue", "com.fasterxml.jackson.annotation.JsonValue"); - importMapping.put("SerializedName", "com.google.gson.annotations.SerializedName"); - importMapping.put("TypeAdapter", "com.google.gson.TypeAdapter"); - importMapping.put("JsonAdapter", "com.google.gson.annotations.JsonAdapter"); - importMapping.put("JsonReader", "com.google.gson.stream.JsonReader"); - importMapping.put("JsonWriter", "com.google.gson.stream.JsonWriter"); - importMapping.put("IOException", "java.io.IOException"); - importMapping.put("Objects", "java.util.Objects"); - importMapping.put("StringUtil", invokerPackage + ".StringUtil"); - // import JsonCreator if JsonProperty is imported - // used later in recursive import in postProcessingModels - importMapping.put("com.fasterxml.jackson.annotation.JsonProperty", "com.fasterxml.jackson.annotation.JsonCreator"); - - if (additionalProperties.containsKey(JAVA8_MODE)) { - setJava8Mode(Boolean.parseBoolean(additionalProperties.get(JAVA8_MODE).toString())); - if ( java8Mode ) { - additionalProperties.put("java8", "true"); - } - } - - if (additionalProperties.containsKey(SUPPORT_ASYNC)) { - setSupportAsync(Boolean.parseBoolean(additionalProperties.get(SUPPORT_ASYNC).toString())); - if (supportAsync) { - additionalProperties.put(SUPPORT_ASYNC, "true"); - } - } - - if (additionalProperties.containsKey(WITH_XML)) { - setWithXml(Boolean.parseBoolean(additionalProperties.get(WITH_XML).toString())); - if ( withXml ) { - additionalProperties.put(WITH_XML, "true"); - } - } - - if (additionalProperties.containsKey(DATE_LIBRARY)) { - setDateLibrary(additionalProperties.get("dateLibrary").toString()); - } - - if ("threetenbp".equals(dateLibrary)) { - additionalProperties.put("threetenbp", "true"); - additionalProperties.put("jsr310", "true"); - typeMapping.put("date", "LocalDate"); - typeMapping.put("DateTime", "OffsetDateTime"); - importMapping.put("LocalDate", "org.threeten.bp.LocalDate"); - importMapping.put("OffsetDateTime", "org.threeten.bp.OffsetDateTime"); - } else if ("joda".equals(dateLibrary)) { - additionalProperties.put("joda", "true"); - typeMapping.put("date", "LocalDate"); - typeMapping.put("DateTime", "DateTime"); - importMapping.put("LocalDate", "org.joda.time.LocalDate"); - importMapping.put("DateTime", "org.joda.time.DateTime"); - } else if (dateLibrary.startsWith("java8")) { - additionalProperties.put("java8", "true"); - additionalProperties.put("jsr310", "true"); - typeMapping.put("date", "LocalDate"); - importMapping.put("LocalDate", "java.time.LocalDate"); - if ("java8-localdatetime".equals(dateLibrary)) { - typeMapping.put("DateTime", "LocalDateTime"); - importMapping.put("LocalDateTime", "java.time.LocalDateTime"); - } else { - typeMapping.put("DateTime", "OffsetDateTime"); - importMapping.put("OffsetDateTime", "java.time.OffsetDateTime"); - } - } else if (dateLibrary.equals("legacy")) { - additionalProperties.put("legacyDates", "true"); - } - } - - private void sanitizeConfig() { - // Sanitize any config options here. We also have to update the additionalProperties because - // the whole additionalProperties object is injected into the main object passed to the mustache layer - - this.setApiPackage(sanitizePackageName(apiPackage)); - if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { - this.additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); - } - - this.setModelPackage(sanitizePackageName(modelPackage)); - if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { - this.additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); - } - - this.setInvokerPackage(sanitizePackageName(invokerPackage)); - if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { - this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); - } - } - - @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { - return this.reservedWordsMappings().get(name); - } - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', '/'); - } - - @Override - public String apiTestFileFolder() { - return outputFolder + "/" + testFolder + "/" + apiPackage().replace('.', '/'); - } - - @Override - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', '/'); - } - - @Override - public String apiDocFileFolder() { - return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); - } - - @Override - public String modelDocFileFolder() { - return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); - } - - @Override - public String toApiDocFilename(String name) { - return toApiName(name); - } - - @Override - public String toModelDocFilename(String name) { - return toModelName(name); - } - - @Override - public String toApiTestFilename(String name) { - return toApiName(name) + "Test"; - } - - @Override - public String toApiName(String name) { - if (name.length() == 0) { - return "DefaultApi"; - } - return camelize(name) + "Api"; - } - - @Override - public String toApiFilename(String name) { - return toApiName(name); - } - - @Override - public String toVarName(String name) { - // sanitize name - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - if (name.toLowerCase().matches("^_*class$")) { - return "propertyClass"; - } - - if("_".equals(name)) { - name = "_u"; - } - - // if it's all uppper case, do nothing - if (name.matches("^[A-Z_]*$")) { - return name; - } - - if(startsWithTwoUppercaseLetters(name)){ - name = name.substring(0, 2).toLowerCase() + name.substring(2); - } - - // camelize (lower first character) 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; - } - - private boolean startsWithTwoUppercaseLetters(String name) { - boolean startsWithTwoUppercaseLetters = false; - if(name.length() > 1) { - startsWithTwoUppercaseLetters = name.substring(0, 2).equals(name.substring(0, 2).toUpperCase()); - } - return startsWithTwoUppercaseLetters; - } - - @Override - public String toParamName(String name) { - // to avoid conflicts with 'callback' parameter for async call - if ("callback".equals(name)) { - return "paramCallback"; - } - - // should be the same as variable name - return toVarName(name); - } - - @Override - public String toModelName(final String name) { - // We need to check if import-mapping has a different model for this class, so we use it - // instead of the auto-generated one. - if (importMapping.containsKey(name)) { - return importMapping.get(name); - } - - 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(nameWithPrefixSuffix); - - // model name cannot use reserved keyword, e.g. return - if (isReservedWord(camelizedName)) { - final String modelName = "Model" + camelizedName; - LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); - return modelName; - } - - // model name starts with number - 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; - } - - return camelizedName; - } - - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } - - @Override - public String getTypeDeclaration(Property p) { - 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) + ""; - } - return super.getTypeDeclaration(p); - } - - @Override - public String getAlias(String name) { - if (typeAliases != null && typeAliases.containsKey(name)) { - return typeAliases.get(name); - } - return name; - } - - @Override - public String toDefaultValue(Property p) { - if (p instanceof ArrayProperty) { - final ArrayProperty ap = (ArrayProperty) p; - final String pattern; - if (fullJavaUtil) { - pattern = "new java.util.ArrayList<%s>()"; - } else { - pattern = "new ArrayList<%s>()"; - } - if (ap.getItems() == null) { - return null; - } - - String typeDeclaration = getTypeDeclaration(ap.getItems()); - Object java8obj = additionalProperties.get("java8"); - if (java8obj != null) { - Boolean java8 = Boolean.valueOf(java8obj.toString()); - if (java8 != null && java8) { - typeDeclaration = ""; - } - } - - return String.format(pattern, typeDeclaration); - } else if (p instanceof MapProperty) { - final MapProperty ap = (MapProperty) p; - final String pattern; - if (fullJavaUtil) { - pattern = "new java.util.HashMap<%s>()"; - } else { - pattern = "new HashMap<%s>()"; - } - if (ap.getAdditionalProperties() == null) { - return null; - } - - String typeDeclaration = String.format("String, %s", getTypeDeclaration(ap.getAdditionalProperties())); - Object java8obj = additionalProperties.get("java8"); - if (java8obj != null) { - Boolean java8 = Boolean.valueOf(java8obj.toString()); - if (java8 != null && java8) { - typeDeclaration = ""; - } - } - - return String.format(pattern, typeDeclaration); - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return "null"; - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString()+"l"; - } - return "null"; - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString() + "d"; - } - return "null"; - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString() + "f"; - } - return "null"; - } else if (p instanceof BooleanProperty) { - BooleanProperty bp = (BooleanProperty) p; - if (bp.getDefault() != null) { - return bp.getDefault().toString(); - } - return "null"; - } else if (p instanceof StringProperty) { - StringProperty sp = (StringProperty) p; - if (sp.getDefault() != null) { - String _default = sp.getDefault(); - if (sp.getEnum() == null) { - return "\"" + escapeText(_default) + "\""; - } else { - // convert to enum var name later in postProcessModels - return _default; - } - } - return "null"; - } - return super.toDefaultValue(p); - } - - @Override - public void setParameterExampleValue(CodegenParameter p) { - String example; - - if (p.defaultValue == null) { - example = p.example; - } else { - example = p.defaultValue; - } - - String type = p.baseType; - if (type == null) { - type = p.dataType; - } - - if ("String".equals(type)) { - if (example == null) { - example = p.paramName + "_example"; - } - example = "\"" + escapeText(example) + "\""; - } else if ("Integer".equals(type) || "Short".equals(type)) { - if (example == null) { - example = "56"; - } - } else if ("Long".equals(type)) { - if (example == null) { - example = "56"; - } - example = example + "L"; - } else if ("Float".equals(type)) { - if (example == null) { - example = "3.4"; - } - example = example + "F"; - } else if ("Double".equals(type)) { - example = "3.4"; - example = example + "D"; - } else if ("Boolean".equals(type)) { - if (example == null) { - example = "true"; - } - } else if ("File".equals(type)) { - if (example == null) { - example = "/path/to/file"; - } - example = "new File(\"" + escapeText(example) + "\")"; - } else if ("Date".equals(type)) { - example = "new Date()"; - } else if (!languageSpecificPrimitives.contains(type)) { - // type is a model class, e.g. User - example = "new " + type + "()"; - } - - if (example == null) { - example = "null"; - } else if (Boolean.TRUE.equals(p.isListContainer)) { - example = "Arrays.asList(" + example + ")"; - } else if (Boolean.TRUE.equals(p.isMapContainer)) { - example = "new HashMap()"; - } - - p.example = example; - } - - @Override - public String toExampleValue(Property p) { - if(p.getExample() != null) { - return escapeText(p.getExample().toString()); - } else { - return super.toExampleValue(p); - } - } - - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - - swaggerType = getAlias(swaggerType); - - // don't apply renaming on types from the typeMapping - if (typeMapping.containsKey(swaggerType)) { - return typeMapping.get(swaggerType); - } - - if (null == swaggerType) { - LOGGER.error("No Type defined for Property " + p); - } - return toModelName(swaggerType); - } - - @Override - public String toOperationId(String operationId) { - // throw exception if method name is empty - if (StringUtils.isEmpty(operationId)) { - throw new RuntimeException("Empty method/operation name (operationId) not allowed"); - } - - operationId = camelize(sanitizeName(operationId), true); - - // method name cannot use reserved keyword, e.g. return - if (isReservedWord(operationId)) { - String newOperationId = camelize("call_" + operationId, true); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); - return newOperationId; - } - - return operationId; - } - - @Override - public CodegenModel fromModel(String name, Model model, Map allDefinitions) { - CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); - if(codegenModel.description != null) { - codegenModel.imports.add("ApiModel"); - } - if (codegenModel.discriminator != null && additionalProperties.containsKey("jackson")) { - codegenModel.imports.add("JsonSubTypes"); - codegenModel.imports.add("JsonTypeInfo"); - } - if (allDefinitions != null && codegenModel.parentSchema != null && codegenModel.hasEnums) { - final Model parentModel = allDefinitions.get(codegenModel.parentSchema); - final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); - codegenModel = AbstractJavaCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); - } - return codegenModel; - } - - @Override - public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { - if(serializeBigDecimalAsString) { - if (property.baseType.equals("BigDecimal")) { - // we serialize BigDecimal as `string` to avoid precision loss - property.vendorExtensions.put("extraAnnotation", "@JsonSerialize(using = ToStringSerializer.class)"); - - // this requires some more imports to be added for this model... - model.imports.add("ToStringSerializer"); - model.imports.add("JsonSerialize"); - } - } - - if (!fullJavaUtil) { - if ("array".equals(property.containerType)) { - model.imports.add("ArrayList"); - } else if ("map".equals(property.containerType)) { - model.imports.add("HashMap"); - } - } - - if(!BooleanUtils.toBoolean(model.isEnum)) { - // needed by all pojos, but not enums - model.imports.add("ApiModelProperty"); - model.imports.add("ApiModel"); - } - } - - @Override - public void postProcessParameter(CodegenParameter parameter) { } - - @Override - public Map postProcessModels(Map objs) { - // recursively add import for mapping one type to multiple imports - List> recursiveImports = (List>) objs.get("imports"); - if (recursiveImports == null) - return objs; - - ListIterator> listIterator = recursiveImports.listIterator(); - while (listIterator.hasNext()) { - String _import = listIterator.next().get("import"); - // if the import package happens to be found in the importMapping (key) - // add the corresponding import package to the list - if (importMapping.containsKey(_import)) { - Map newImportMap= new HashMap(); - newImportMap.put("import", importMapping.get(_import)); - listIterator.add(newImportMap); - } - } - - return postProcessModelsEnum(objs); - } - - @Override - public Map postProcessOperations(Map objs) { - // Remove imports of List, ArrayList, Map and HashMap as they are - // imported in the template already. - List> imports = (List>) objs.get("imports"); - Pattern pattern = Pattern.compile("java\\.util\\.(List|ArrayList|Map|HashMap)"); - for (Iterator> itr = imports.iterator(); itr.hasNext();) { - String _import = itr.next().get("import"); - if (pattern.matcher(_import).matches()) { - itr.remove(); - } - } - return objs; - } - - @Override - public void preprocessSwagger(Swagger swagger) { - if (swagger == null || swagger.getPaths() == null){ - return; - } - for (String pathname : swagger.getPaths().keySet()) { - Path path = swagger.getPath(pathname); - if (path.getOperations() == null){ - continue; - } - for (Operation operation : path.getOperations()) { - boolean hasFormParameters = false; - boolean hasBodyParameters = false; - for (Parameter parameter : operation.getParameters()) { - if (parameter instanceof FormParameter) { - hasFormParameters = true; - } - if (parameter instanceof BodyParameter) { - hasBodyParameters = true; - } - } - if (hasBodyParameters || hasFormParameters){ - String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json"; - String contentType = operation.getConsumes() == null || operation.getConsumes().isEmpty() ? defaultContentType : operation.getConsumes().get(0); - operation.setVendorExtension("x-contentType", contentType); - } - String accepts = getAccept(operation); - operation.setVendorExtension("x-accepts", accepts); - } - } - } - - private static String getAccept(Operation operation) { - String accepts = null; - String defaultContentType = "application/json"; - if (operation.getProduces() != null && !operation.getProduces().isEmpty()) { - StringBuilder sb = new StringBuilder(); - for (String produces : operation.getProduces()) { - if (defaultContentType.equalsIgnoreCase(produces)) { - accepts = defaultContentType; - break; - } else { - if (sb.length() > 0) { - sb.append(","); - } - sb.append(produces); - } - } - if (accepts == null) { - accepts = sb.toString(); - } - } else { - accepts = defaultContentType; - } - - return accepts; - } - - @Override - protected boolean needToImport(String type) { - return super.needToImport(type) && type.indexOf(".") < 0; - } -/* - @Override - public String findCommonPrefixOfVars(List 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", ""); - } -*/ - - @Override - public String toEnumName(CodegenProperty property) { - return sanitizeName(camelize(property.name)) + "Enum"; - } - - @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(); - } - - // number - if ("Integer".equals(datatype) || "Long".equals(datatype) || - "Float".equals(datatype) || "Double".equals(datatype)) { - String varName = "NUMBER_" + value; - varName = varName.replaceAll("-", "MINUS_"); - varName = varName.replaceAll("\\+", "PLUS_"); - varName = varName.replaceAll("\\.", "_DOT_"); - return varName; - } - - // string - String var = value.replaceAll("\\W+", "_").toUpperCase(); - if (var.matches("\\d.*")) { - return "_" + var; - } else { - return var; - } - } - - @Override - public String toEnumValue(String value, String datatype) { - if ("Integer".equals(datatype) || "Double".equals(datatype)) { - return value; - } else if ("Long".equals(datatype)) { - // add l to number, e.g. 2048 => 2048l - return value + "l"; - } else if ("Float".equals(datatype)) { - // add f to number, e.g. 3.14 => 3.14f - return value + "f"; - } else { - return "\"" + escapeText(value) + "\""; - } - } - - @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); - 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 - // the parent and child models, look for enums that match, and remove - // them from the child models and leave them in the parent. - // Because the child models extend the parents, the enums will be available via the parent. - - // Only bother with reconciliation if the parent model has enums. - if (!parentCodegenModel.hasEnums) { - return codegenModel; - } - - // Get the properties for the parent and child models - final List parentModelCodegenProperties = parentCodegenModel.vars; - List codegenProperties = codegenModel.vars; - - // Iterate over all of the parent model properties - boolean removedChildEnum = false; - for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) { - // Look for enums - if (parentModelCodegenPropery.isEnum) { - // Now that we have found an enum in the parent class, - // and search the child class for the same enum. - Iterator iterator = codegenProperties.iterator(); - while (iterator.hasNext()) { - CodegenProperty codegenProperty = iterator.next(); - if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) { - // We found an enum in the child class that is - // a duplicate of the one in the parent, so remove it. - iterator.remove(); - removedChildEnum = true; - } - } - } - } - - if(removedChildEnum) { - // If we removed an entry from this model's vars, we need to ensure hasMore is updated - int count = 0, numVars = codegenProperties.size(); - for(CodegenProperty codegenProperty : codegenProperties) { - count += 1; - codegenProperty.hasMore = (count < numVars) ? true : false; - } - codegenModel.vars = codegenProperties; - } - return codegenModel; - } - - private static String sanitizePackageName(String packageName) { - packageName = packageName.trim(); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_"); - if(Strings.isNullOrEmpty(packageName)) { - return "invalidPackageName"; - } - return packageName; - } - - public void setInvokerPackage(String invokerPackage) { - this.invokerPackage = invokerPackage; - } - - public void setGroupId(String groupId) { - this.groupId = groupId; - } - - public void setArtifactId(String artifactId) { - this.artifactId = artifactId; - } - - public void setArtifactVersion(String artifactVersion) { - 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; - } - - public void setTestFolder(String testFolder) { - this.testFolder = testFolder; - } - - public void setLocalVariablePrefix(String localVariablePrefix) { - this.localVariablePrefix = localVariablePrefix; - } - - public void setSerializeBigDecimalAsString(boolean s) { - this.serializeBigDecimalAsString = s; - } - - public void setSerializableModel(Boolean serializableModel) { - this.serializableModel = serializableModel; - } - - private String sanitizePath(String p) { - //prefer replace a ", instead of a fuLL URL encode for readability - return p.replaceAll("\"", "%22"); - } - - public void setFullJavaUtil(boolean fullJavaUtil) { - this.fullJavaUtil = fullJavaUtil; - } - - public void setWithXml(boolean withXml) { - this.withXml = withXml; - } - - public void setDateLibrary(String library) { - this.dateLibrary = library; - } - - public void setJava8Mode(boolean enabled) { - this.java8Mode = enabled; - } - - public void setSupportAsync(boolean enabled) { - this.supportAsync = enabled; - } - - @Override - public String escapeQuotationMark(String input) { - // remove " to avoid code injection - return input.replace("\"", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } - - /* - * Derive invoker package name based on the input - * e.g. foo.bar.model => foo.bar - * - * @param input API package/model name - * @return Derived invoker package name based on API package/model name - */ - private String deriveInvokerPackageName(String input) { - String[] parts = input.split(Pattern.quote(".")); // Split on period. - - StringBuilder sb = new StringBuilder(); - String delim = ""; - for (String p : Arrays.copyOf(parts, parts.length-1)) { - sb.append(delim).append(p); - delim = "."; - } - return sb.toString(); - } - - public void setSupportJava6(boolean value) { - this.supportJava6 = value; - } - - public String toRegularExpression(String pattern) { - 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); - } - - /** - * Output the partial Getter name for boolean property, e.g. Active - * - * @param name the name of the property - * @return partial getter name based on naming convention - */ - public String toBooleanGetter(String name) { - return getterAndSetterCapitalize(name); - } - - @Override - public String sanitizeTag(String tag) { - tag = camelize(underscore(sanitizeName(tag))); - - // tag starts with numbers - if (tag.matches("^\\d.*")) { - tag = "Class" + tag; - } - return tag; - } - -} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptInversifyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptInversifyClientCodegen.java deleted file mode 100644 index 56c224c0649..00000000000 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptInversifyClientCodegen.java +++ /dev/null @@ -1,373 +0,0 @@ -package io.swagger.codegen.languages; - -import java.io.File; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import io.swagger.codegen.CliOption; -import io.swagger.codegen.CodegenModel; -import io.swagger.codegen.CodegenParameter; -import io.swagger.codegen.CodegenOperation; -import io.swagger.codegen.SupportingFile; -import io.swagger.codegen.utils.SemVer; -import io.swagger.models.ModelImpl; -import io.swagger.models.properties.*; - -public class TypeScriptInversifyClientCodegen extends AbstractTypeScriptClientCodegen { - private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm"); - private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value"; - - 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"; - public static final String WITH_INTERFACES = "withInterfaces"; - public static final String USE_PROMISE = "usePromise"; - public static final String TAGGED_UNIONS ="taggedUnions"; - - protected String npmVersion = null; - protected String npmName = null; - protected String npmRepository = null; - private boolean taggedUnions = false; - - public TypeScriptInversifyClientCodegen() { - super(); - this.outputFolder = "generated-code/typescript-inversify"; - - embeddedTemplateDir = templateDir = "typescript-inversify"; - modelTemplateFiles.put("model.mustache", ".ts"); - apiTemplateFiles.put("api.service.mustache", ".ts"); - languageSpecificPrimitives.add("Blob"); - typeMapping.put("file", "Blob"); - apiPackage = "api"; - modelPackage = "model"; - - 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())); - this.cliOptions.add(new CliOption(WITH_INTERFACES, - "Setting this property to true will generate interfaces next to the default class implementations.", - BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString())); - this.cliOptions.add(new CliOption(USE_PROMISE, - "Setting this property to use promise instead of observable inside every service.", - BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString())); - this.cliOptions.add(new CliOption(TAGGED_UNIONS, - "Use discriminators to create tagged unions instead of extending interfaces.", - BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString())); - } - - @Override - protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) { - codegenModel.additionalPropertiesType = getTypeDeclaration(swaggerModel.getAdditionalProperties()); - addImport(codegenModel, codegenModel.additionalPropertiesType); - } - - @Override - public String getName() { - return "typescript-inversify"; - } - - @Override - public String getHelp() { - return "Generates Typescript services using Inversify IOC"; - } - - @Override - public void processOpts() { - super.processOpts(); - // HttpClient - supportingFiles.add(new SupportingFile("IHttpClient.mustache", getIndexDirectory(), "IHttpClient.ts")); - supportingFiles.add(new SupportingFile("IAPIConfiguration.mustache", getIndexDirectory(), "IAPIConfiguration.ts")); - supportingFiles.add(new SupportingFile("HttpClient.mustache", getIndexDirectory(), "HttpClient.ts")); - supportingFiles.add(new SupportingFile("HttpResponse.mustache", getIndexDirectory(), "HttpResponse.ts")); - supportingFiles.add(new SupportingFile("Headers.mustache", getIndexDirectory(), "Headers.ts")); - - supportingFiles.add(new SupportingFile("ApiServiceBinder.mustache", getIndexDirectory(), "ApiServiceBinder.ts")); - supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), "variables.ts")); - - if (additionalProperties.containsKey(NPM_NAME)) { - addNpmPackageGeneration(); - } - - if (additionalProperties.containsKey(WITH_INTERFACES)) { - boolean withInterfaces = Boolean.parseBoolean(additionalProperties.get(WITH_INTERFACES).toString()); - if (withInterfaces) { - apiTemplateFiles.put("apiInterface.mustache", "Interface.ts"); - } - } - - if (additionalProperties.containsKey(TAGGED_UNIONS)) { - taggedUnions = Boolean.parseBoolean(additionalProperties.get(TAGGED_UNIONS).toString()); - } - } - - 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("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("gitignore", "", ".gitignore")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("README.mustache", getIndexDirectory(), "README.md")); - supportingFiles.add(new SupportingFile("package.mustache", getIndexDirectory(), "package.json")); - supportingFiles.add(new SupportingFile("tsconfig.mustache", getIndexDirectory(), "tsconfig.json")); - } - - private String getIndexDirectory() { - String indexPackage = modelPackage.substring(0, Math.max(0, modelPackage.lastIndexOf('.'))); - return indexPackage.replace('.', File.separatorChar); - } - - @Override - public boolean isDataTypeFile(final String dataType) { - return dataType != null && dataType.equals("Blob"); - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof FileProperty) { - return "Blob"; - } else if (p instanceof ObjectProperty) { - return "any"; - } else { - return super.getTypeDeclaration(p); - } - } - - - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - if (isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) { - return swaggerType; - } - applyLocalTypeMapping(swaggerType); - return swaggerType; - } - - private String applyLocalTypeMapping(String type) { - if (typeMapping.containsKey(type)) { - type = typeMapping.get(type); - } - 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; - } - - @Override - public void postProcessParameter(CodegenParameter parameter) { - super.postProcessParameter(parameter); - parameter.dataType = applyLocalTypeMapping(parameter.dataType); - } - - @Override - public Map postProcessOperations(Map operations) { - Map objs = (Map) operations.get("operations"); - - // Add filename information for api imports - objs.put("apiFilename", getApiFilenameFromClassname(objs.get("classname").toString())); - - List ops = (List) objs.get("operation"); - for (CodegenOperation op : ops) { - // Prep a string buffer where we're going to set up our new version of the string. - StringBuilder pathBuffer = new StringBuilder(); - StringBuilder parameterName = new StringBuilder(); - int insideCurly = 0; - - op.httpMethod = op.httpMethod.toLowerCase(); - - // Iterate through existing string, one character at a time. - for (int i = 0; i < op.path.length(); i++) { - switch (op.path.charAt(i)) { - case '{': - // We entered curly braces, so track that. - insideCurly++; - - // Add the more complicated component instead of just the brace. - pathBuffer.append("${encodeURIComponent(String("); - break; - case '}': - // We exited curly braces, so track that. - insideCurly--; - - // Add the more complicated component instead of just the brace. - pathBuffer.append(toVarName(parameterName.toString())); - pathBuffer.append("))}"); - parameterName.setLength(0); - break; - default: - if (insideCurly > 0) { - parameterName.append(op.path.charAt(i)); - } else { - pathBuffer.append(op.path.charAt(i)); - } - break; - } - } - - // Overwrite path to TypeScript template string, after applying everything we just did. - op.path = pathBuffer.toString(); - } - - // Add additional filename information for model imports in the services - List> imports = (List>) operations.get("imports"); - for (Map im : imports) { - im.put("filename", im.get("import")); - im.put("classname", getModelnameFromModelFilename(im.get("filename").toString())); - } - - return operations; - } - - @Override - public Map postProcessModels(Map objs) { - Map result = super.postProcessModels(objs); - - return postProcessModelsEnum(result); - } - - @Override - public Map postProcessAllModels(Map objs) { - Map result = super.postProcessAllModels(objs); - - for (Map.Entry entry : result.entrySet()) { - Map inner = (Map) entry.getValue(); - List> models = (List>) inner.get("models"); - for (Map mo : models) { - CodegenModel cm = (CodegenModel) mo.get("model"); - if (taggedUnions) { - mo.put(TAGGED_UNIONS, true); - if (cm.discriminator != null && cm.children != null) { - for (CodegenModel child : cm.children) { - cm.imports.add(child.classname); - } - } - if (cm.parent != null) { - cm.imports.remove(cm.parent); - } - } - // Add additional filename information for imports - mo.put("tsImports", toTsImports(cm, cm.imports)); - } - } - return result; - } - - private List> toTsImports(CodegenModel cm, Set imports) { - List> tsImports = new ArrayList<>(); - for (String im : imports) { - if (!im.equals(cm.classname)) { - HashMap tsImport = new HashMap<>(); - tsImport.put("classname", im); - tsImport.put("filename", toModelFilename(im)); - tsImports.add(tsImport); - } - } - return tsImports; - } - - @Override - public String toApiName(String name) { - if (name.length() == 0) { - return "DefaultService"; - } - return initialCaps(name) + "Service"; - } - - @Override - public String toApiFilename(String name) { - if (name.length() == 0) { - return "default.service"; - } - return camelize(name, true) + ".service"; - } - - @Override - public String toApiImport(String name) { - return apiPackage() + "/" + toApiFilename(name); - } - - @Override - public String toModelFilename(String name) { - return camelize(toModelName(name), true); - } - - @Override - public String toModelImport(String name) { - return modelPackage() + "/" + toModelFilename(name); - } - - public String getNpmName() { - return npmName; - } - - public void setNpmName(String npmName) { - this.npmName = npmName; - } - - public String getNpmVersion() { - return npmVersion; - } - - public void setNpmVersion(String npmVersion) { - this.npmVersion = npmVersion; - } - - public String getNpmRepository() { - return npmRepository; - } - - public void setNpmRepository(String npmRepository) { - this.npmRepository = npmRepository; - } - - private String getApiFilenameFromClassname(String classname) { - String name = classname.substring(0, classname.length() - "Service".length()); - return toApiFilename(name); - } - - private String getModelnameFromModelFilename(String filename) { - String name = filename.substring((modelPackage() + "/").length()); - return camelize(name); - } - -} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/ApiServiceBinder.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/ApiServiceBinder.mustache deleted file mode 100644 index 0026933c69c..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/ApiServiceBinder.mustache +++ /dev/null @@ -1,20 +0,0 @@ -import {interfaces} from "inversify"; - -{{#apiInfo}} -{{#apis}} -import { {{classname}} } from './{{importPath}}'; -{{#withInterfaces}} -import { {{classname}}Interface } from './{{importPath}}Interface'; -{{/withInterfaces}} -{{/apis}} -{{/apiInfo}} - -export class ApiServiceBinder { - public static with(container: interfaces.Container) { - {{#apiInfo}} - {{#apis}} - container.bind<{{classname}}{{#withInterfaces}}Interface{{/withInterfaces}}>("{{classname}}").to({{classname}}).inSingletonScope(); - {{/apis}} - {{/apiInfo}} - } -} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/Headers.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/Headers.mustache deleted file mode 100644 index 0fa7760e01e..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/Headers.mustache +++ /dev/null @@ -1,3 +0,0 @@ -export interface Headers { - [index:string]: string -} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpClient.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpClient.mustache deleted file mode 100644 index 64fe12a3045..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpClient.mustache +++ /dev/null @@ -1,63 +0,0 @@ -import IHttpClient from "./IHttpClient"; -import { Observable } from "rxjs/Observable"; -import "whatwg-fetch"; -import HttpResponse from "./HttpResponse"; -import {injectable} from "inversify"; -import "rxjs/add/observable/fromPromise"; -import { Headers } from "./Headers"; - -@injectable() -class HttpClient implements IHttpClient { - - get(url:string, headers?: Headers):Observable { - return this.performNetworkCall(url, "get", undefined, headers); - } - - post(url: string, body: {}|FormData, headers?: Headers): Observable { - return this.performNetworkCall(url, "post", this.getJsonBody(body), this.addJsonHeaders(headers)); - } - - put(url: string, body: {}, headers?: Headers): Observable { - return this.performNetworkCall(url, "put", this.getJsonBody(body), this.addJsonHeaders(headers)); - } - - delete(url: string, headers?: Headers): Observable { - return this.performNetworkCall(url, "delete", undefined, headers); - } - - private getJsonBody(body: {}|FormData) { - return !(body instanceof FormData) ? JSON.stringify(body) : body; - } - - private addJsonHeaders(headers: Headers) { - return Object.assign({}, { - "Accept": "application/json", - "Content-Type": "application/json" - }, headers); - }; - - private performNetworkCall(url: string, method: string, body?: any, headers?: Headers): Observable { - let promise = window.fetch(url, { - method: method, - body: body, - headers: headers - }).then(response => { - let headers: Headers = {}; - response.headers.forEach((value, name) => { - headers[name.toString().toLowerCase()] = value; - }); - return response.text().then(text => { - let contentType = headers["content-type"] || ""; - let payload = contentType.match("application/json") ? JSON.parse(text) : text; - let httpResponse = new HttpResponse(payload, response.status, headers); - - if (response.status >= 400) - throw httpResponse; - return httpResponse; - }); - }); - return Observable.fromPromise(promise); - } -} - -export default HttpClient \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpResponse.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpResponse.mustache deleted file mode 100644 index 411240cde2b..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpResponse.mustache +++ /dev/null @@ -1,8 +0,0 @@ -import { Headers } from "./Headers" - -class HttpResponse { - constructor(public response: T, public status:number, public headers?: Headers) { - } -} - -export default HttpResponse \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/IAPIConfiguration.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/IAPIConfiguration.mustache deleted file mode 100644 index 2364e83e6cb..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/IAPIConfiguration.mustache +++ /dev/null @@ -1,8 +0,0 @@ -export interface IAPIConfiguration { - apiKeys?: {[ key: string ]: string}; - username?: string; - password?: string; - accessToken?: string | (() => string); - basePath?: string; - withCredentials?: boolean; -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/IHttpClient.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/IHttpClient.mustache deleted file mode 100644 index 22d9e07c903..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/IHttpClient.mustache +++ /dev/null @@ -1,12 +0,0 @@ -import { Observable } from "rxjs/Observable"; -import HttpResponse from "./HttpResponse"; -import { Headers } from "./Headers"; - -interface IHttpClient { - get(url:string, headers?: Headers):Observable - post(url:string, body:{}|FormData, headers?: Headers):Observable - put(url:string, body:{}, headers?: Headers):Observable - delete(url:string, headers?: Headers):Observable -} - -export default IHttpClient \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/README.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/README.mustache deleted file mode 100644 index 4da4e854d96..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/README.mustache +++ /dev/null @@ -1,74 +0,0 @@ -## {{npmName}}@{{npmVersion}} - -### Building - -To build an compile the typescript sources to javascript use: -``` -npm install -npm run build -``` - -### publishing - -First build the package than run ```npm publish``` - -### consuming - -navigate to the folder of your consuming project and run one of next commando's. - -_published:_ - -``` -npm install {{npmName}}@{{npmVersion}} --save -``` - -_unPublished (not recommended):_ - -``` -npm install PATH_TO_GENERATED_PACKAGE --save -``` - -_using `npm link`:_ - -In PATH_TO_GENERATED_PACKAGE: -``` -npm link -``` - -In your project: -``` -npm link {{npmName}}@{{npmVersion}} -``` - -## Requirements -Services require a `IHttpClient` and a `IApiConfiguration`. The `IHttpClient` is necessary to manage http's call and with the `IApiConfiguration` you can provide settings for the Authentication. -For the sake of simplicity an implementation of `IHttpClient` is already provided, but if you want you can override it. -For these reasons you have to manually bind these two services: - -```typescript -let container = new Container(); -container.bind("IApiHttpClient").to(HttpClient).inSingletonScope(); -container.bind("IApiConfiguration").to(ApiConfiguration).inSingletonScope(); -``` - - -## Services Binding -To bind all the generated services you can use `ApiServiceBinder`. - -```typescript -ApiServiceBinder.with(container); -``` - -## Final result - -```typescript -let container = new Container(); -container.bind("IApiHttpClient").to(HttpClient).inSingletonScope(); -container.bind("IApiConfiguration").to(ApiConfiguration).inSingletonScope(); -ApiServiceBinder.with(container); -``` - - - - - diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/api.service.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/api.service.mustache deleted file mode 100644 index 25958375576..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/api.service.mustache +++ /dev/null @@ -1,180 +0,0 @@ -{{>licenseInfo}} -/* tslint:disable:no-unused-variable member-ordering */ - -import { Observable } from "rxjs/Observable"; -import 'rxjs/add/operator/map'; -import 'rxjs/add/operator/toPromise'; -import IHttpClient from "../IHttpClient"; -import { inject, injectable } from "inversify"; -import { IAPIConfiguration } from "../IAPIConfiguration"; -import { Headers } from "../Headers"; -import HttpResponse from "../HttpResponse"; - -{{#imports}} -import { {{classname}} } from '../{{filename}}'; -{{/imports}} - -import { COLLECTION_FORMATS } from '../variables'; -{{#withInterfaces}} -import { {{classname}}Interface } from './{{classname}}Interface'; -{{/withInterfaces}} - -{{#operations}} - -{{#description}} -/** - * {{&description}} - */ -{{/description}} - -@injectable() -{{#withInterfaces}} -export class {{classname}} implements {{classname}}Interface { -{{/withInterfaces}} -{{^withInterfaces}} -export class {{classname}} { -{{/withInterfaces}} - private basePath: string = '{{{basePath}}}'; - - constructor(@inject("IApiHttpClient") private httpClient: IHttpClient, - @inject("IAPIConfiguration") private APIConfiguration: IAPIConfiguration ) { - if(this.APIConfiguration.basePath) - this.basePath = this.APIConfiguration.basePath; - } -{{#operation}} - - /** - * {{summary}} - * {{notes}} - {{#allParams}}* @param {{paramName}} {{description}} - {{/allParams}}{{#useHttpClient}}* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. - * @param reportProgress flag to report request and response progress.{{/useHttpClient}} - */ - public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe?: 'body', headers?: Headers): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>; - public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe?: 'response', headers?: Headers): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}>; - public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe: any = 'body', headers: Headers = {}): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}} { -{{#allParams}} -{{#required}} - if (!{{paramName}}){ - throw new Error('Required parameter {{paramName}} was null or undefined when calling {{nickname}}.'); - } - -{{/required}} -{{/allParams}} -{{#hasQueryParams}} - let queryParameters: string[] = []; -{{#queryParams}} - {{#isListContainer}} - if ({{paramName}}) { - {{#isCollectionFormatMulti}} - {{paramName}}.forEach((element) => { - queryParameters.push("{{paramName}}="+encodeURIComponent(String({{paramName}}))); - }) - {{/isCollectionFormatMulti}} - {{^isCollectionFormatMulti}} - queryParameters.push("{{paramName}}="+encodeURIComponent({{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}']))); - {{/isCollectionFormatMulti}} - } - {{/isListContainer}} - {{^isListContainer}} - if ({{paramName}} !== undefined) { - {{#isDateTime}} - queryParameters.push("{{paramName}}="+encodeURIComponent({{paramName}}.toISOString())); - {{/isDateTime}} - {{^isDateTime}} - queryParameters.push("{{paramName}}="+encodeURIComponent(String({{paramName}}))); - {{/isDateTime}} - } - {{/isListContainer}} -{{/queryParams}} - -{{/hasQueryParams}} -{{#headerParams}} - {{#isListContainer}} - if ({{paramName}}) { - headers['{{baseName}}'] = {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}']); - } - {{/isListContainer}} - {{^isListContainer}} - if ({{paramName}}) { - headers['{{baseName}}'] = String({{paramName}}); - } - {{/isListContainer}} - -{{/headerParams}} -{{#authMethods}} - // authentication ({{name}}) required -{{#isApiKey}} -{{#isKeyInHeader}} - if (this.APIConfiguration.apiKeys["{{keyParamName}}"]) { - headers['{{keyParamName}}'] = this.APIConfiguration.apiKeys["{{keyParamName}}"]; - } -{{/isKeyInHeader}} -{{#isKeyInQuery}} - if (this.APIConfiguration.apiKeys["{{keyParamName}}"]) { - queryParameters.push("{{paramName}}="+encodeURIComponent(String(this.APIConfiguration.apiKeys["{{keyParamName}}"]))); - } -{{/isKeyInQuery}} -{{/isApiKey}} -{{#isBasic}} - if (this.APIConfiguration.username || this.APIConfiguration.password) { - headers['Authorization'] = btoa(this.APIConfiguration.username + ':' + this.APIConfiguration.password); - } -{{/isBasic}} -{{#isOAuth}} - if (this.APIConfiguration.accessToken) { - let accessToken = typeof this.APIConfiguration.accessToken === 'function' - ? this.APIConfiguration.accessToken() - : this.APIConfiguration.accessToken; - headers['Authorization'] = 'Bearer ' + accessToken; - } -{{/isOAuth}} -{{/authMethods}} - {{^produces}} - headers['Accept'] = 'application/json'; - {{/produces}} - {{#produces.0}} - headers['Accept'] = '{{{mediaType}}}'; - {{/produces.0}} -{{#bodyParam}} - {{^consumes}} - headers['Content-Type'] = 'application/json'; - {{/consumes}} - {{#consumes.0}} - headers['Content-Type'] = '{{{mediaType}}}'; - {{/consumes.0}} -{{/bodyParam}} - -{{#hasFormParams}} - let formData: FormData = new FormData(); - headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; -{{#formParams}} - {{#isListContainer}} - if ({{paramName}}) { - {{#isCollectionFormatMulti}} - {{paramName}}.forEach((element) => { - formData.append('{{baseName}}', element); - }) - {{/isCollectionFormatMulti}} - {{^isCollectionFormatMulti}} - formData.append('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}'])); - {{/isCollectionFormatMulti}} - } - {{/isListContainer}} - {{^isListContainer}} - if ({{paramName}} !== undefined) { - formData.append('{{baseName}}', {{paramName}}); - } - {{/isListContainer}} -{{/formParams}} - -{{/hasFormParams}} - const response: Observable> = this.httpClient.{{httpMethod}}(`${this.basePath}{{{path}}}{{#hasQueryParams}}?${queryParameters.join('&')}{{/hasQueryParams}}`{{#bodyParam}}, {{paramName}} {{/bodyParam}}{{#hasFormParams}}, body{{/hasFormParams}}, headers); - if (observe == 'body') { - return response.map(httpResponse => <{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>(httpResponse.response)){{#usePromise}}.toPromise(){{/usePromise}}; - } - return response{{#usePromise}}.toPromise(){{/usePromise}}; - } - -{{/operation}}} -{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/apiInterface.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/apiInterface.mustache deleted file mode 100644 index cb31c6396b9..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/apiInterface.mustache +++ /dev/null @@ -1,26 +0,0 @@ -{{>licenseInfo}} -import { Headers } from "../Headers"; -import { Observable } from "rxjs/Observable"; -import * as models from "../model/models"; -import HttpResponse from "../HttpResponse"; - -{{#operations}} - -{{#description}} - /** - * {{&description}} - */ -{{/description}} -export interface {{classname}}Interface { -{{#operation}} - /** - * {{summary}} - * {{notes}} - {{#allParams}}* @param {{paramName}} {{description}} - {{/allParams}}*/ - - {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe?: 'body', headers?: Headers): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>; - {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe?: 'response', headers?: Headers): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}>; -{{/operation}} -} -{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/apis.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/apis.mustache deleted file mode 100644 index 3d49b9488b4..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/apis.mustache +++ /dev/null @@ -1,5 +0,0 @@ -{{#apiInfo}} -{{#apis}} -export * from './{{ classFilename }}'; -{{/apis}} -{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/git_push.sh.mustache deleted file mode 100755 index a2d75234837..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/git_push.sh.mustache +++ /dev/null @@ -1,52 +0,0 @@ -#!/bin/sh -# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ -# -# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 - -if [ "$git_user_id" = "" ]; then - git_user_id="{{{gitUserId}}}" - echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" -fi - -if [ "$git_repo_id" = "" ]; then - git_repo_id="{{{gitRepoId}}}" - echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" -fi - -if [ "$release_note" = "" ]; then - release_note="{{{releaseNote}}}" - echo "[INFO] No command line input provided. Set \$release_note to $release_note" -fi - -# Initialize the local directory as a Git repository -git init - -# Adds the files in the local repository and stages them for commit. -git add . - -# Commits the tracked changes and prepares them to be pushed to a remote repository. -git commit -m "$release_note" - -# Sets the new remote -git_remote=`git remote` -if [ "$git_remote" = "" ]; then # git remote not defined - - if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git - fi - -fi - -git pull origin master - -# Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' - diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/gitignore b/modules/swagger-codegen/src/main/resources/typescript-inversify/gitignore deleted file mode 100644 index 23c3bdf9c9b..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/gitignore +++ /dev/null @@ -1,6 +0,0 @@ -wwwroot/*.js -node_modules -typings -dist -.vscode -.idea \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/index.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/index.mustache deleted file mode 100644 index 54e1715c1e1..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/index.mustache +++ /dev/null @@ -1,7 +0,0 @@ -export * from './api/api'; -export * from './model/models'; -export * from './variables'; -export * from './IAPIConfiguration'; -export * from './ApiServiceBinder'; -export * from './IHttpClient'; -export * from './HttpClient'; \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/licenseInfo.mustache deleted file mode 100644 index 7d61c4ee055..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/licenseInfo.mustache +++ /dev/null @@ -1,11 +0,0 @@ -/** - * {{{appName}}} - * {{{appDescription}}} - * - * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} - * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/model.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/model.mustache deleted file mode 100644 index 0b93ad2998f..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/model.mustache +++ /dev/null @@ -1,16 +0,0 @@ -{{>licenseInfo}} -{{#models}} -{{#model}} -{{#tsImports}} -import { {{classname}} } from './{{filename}}'; -{{/tsImports}} - - -{{#description}} -/** - * {{{description}}} - */ -{{/description}} -{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#isAlias}}{{>modelAlias}}{{/isAlias}}{{^isAlias}}{{#taggedUnions}}{{>modelTaggedUnion}}{{/taggedUnions}}{{^taggedUnions}}{{>modelGeneric}}{{/taggedUnions}}{{/isAlias}}{{/isEnum}} -{{/model}} -{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelAlias.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelAlias.mustache deleted file mode 100644 index c1c6bf7a5da..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelAlias.mustache +++ /dev/null @@ -1 +0,0 @@ -export type {{classname}} = {{dataType}}; \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelEnum.mustache deleted file mode 100644 index 932d3c0fb47..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelEnum.mustache +++ /dev/null @@ -1,9 +0,0 @@ -export type {{classname}} = {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}} | {{/-last}}{{/enumVars}}{{/allowableValues}}; - -export const {{classname}} = { -{{#allowableValues}} -{{#enumVars}} - {{name}}: {{{value}}} as {{classname}}{{^-last}},{{/-last}} -{{/enumVars}} -{{/allowableValues}} -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGeneric.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGeneric.mustache deleted file mode 100644 index a4248ea3da0..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGeneric.mustache +++ /dev/null @@ -1,10 +0,0 @@ -export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ {{>modelGenericAdditionalProperties}} -{{#vars}} - {{#description}} - /** - * {{{description}}} - */ - {{/description}} - {{#isReadOnly}}readonly {{/isReadOnly}}{{name}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; -{{/vars}} -}{{>modelGenericEnums}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericAdditionalProperties.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericAdditionalProperties.mustache deleted file mode 100644 index e6499ce9d63..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericAdditionalProperties.mustache +++ /dev/null @@ -1,5 +0,0 @@ -{{#additionalPropertiesType}} - - [key: string]: {{{additionalPropertiesType}}}{{#hasVars}} | any{{/hasVars}}; - -{{/additionalPropertiesType}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericEnums.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericEnums.mustache deleted file mode 100644 index 432020b726f..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericEnums.mustache +++ /dev/null @@ -1,16 +0,0 @@ -{{#hasEnums}} - -export namespace {{classname}} { -{{#vars}} - {{#isEnum}} - export type {{enumName}} = {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}} | {{/-last}}{{/enumVars}}{{/allowableValues}}; - export const {{enumName}} = { - {{#allowableValues}} - {{#enumVars}} - {{name}}: {{{value}}} as {{enumName}}{{^-last}},{{/-last}} - {{/enumVars}} - {{/allowableValues}} - } - {{/isEnum}} -{{/vars}} -}{{/hasEnums}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelTaggedUnion.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelTaggedUnion.mustache deleted file mode 100644 index cd7d1c8b936..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelTaggedUnion.mustache +++ /dev/null @@ -1,21 +0,0 @@ -{{#discriminator}} -export type {{classname}} = {{#children}}{{^-first}} | {{/-first}}{{classname}}{{/children}}; -{{/discriminator}} -{{^discriminator}} -{{#parent}} -export interface {{classname}} { {{>modelGenericAdditionalProperties}} -{{#allVars}} - {{#description}} - /** - * {{{description}}} - */ - {{/description}} - {{name}}{{^required}}?{{/required}}: {{#discriminatorValue}}'{{discriminatorValue}}'{{/discriminatorValue}}{{^discriminatorValue}}{{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}{{/discriminatorValue}}; -{{/allVars}} -} -{{>modelGenericEnums}} -{{/parent}} -{{^parent}} -{{>modelGeneric}} -{{/parent}} -{{/discriminator}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/models.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/models.mustache deleted file mode 100644 index 02a39c248c4..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/models.mustache +++ /dev/null @@ -1,5 +0,0 @@ -{{#models}} -{{#model}} -export * from './{{{ classFilename }}}'; -{{/model}} -{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/package.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/package.mustache deleted file mode 100644 index 9733f2058a5..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/package.mustache +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "{{{npmName}}}", - "version": "{{{npmVersion}}}", - "description": "swagger client for {{{npmName}}}", - "author": "Swagger Codegen Contributors", - "keywords": [ - "swagger-client" - ], - "license": "Unlicense", - "main": "dist/index.js", - "typings": "dist/index.d.ts", - "scripts": { - "build": "tsc --outDir dist/", - "postinstall": "npm run build" - }, - "dependencies": { - "inversify": "^4.3.0", - "rxjs": "~5.5.7", - "whatwg-fetch": "~2.0.1", - "reflect-metadata": "0.1.8" - }, - "devDependencies": { - }{{#npmRepository}},{{/npmRepository}} -{{#npmRepository}} - "publishConfig": { - "registry": "{{{npmRepository}}}" - } -{{/npmRepository}} -} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/tsconfig.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/tsconfig.mustache deleted file mode 100644 index 3ed5f2c0b10..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/tsconfig.mustache +++ /dev/null @@ -1,25 +0,0 @@ -{ - "compilerOptions": { - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "noImplicitAny": false, - "suppressImplicitAnyIndexErrors": true, - "target": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}es5{{/supportsES6}}", - "module": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}commonjs{{/supportsES6}}", - "moduleResolution": "node", - "removeComments": true, - "sourceMap": true, - "outDir": "./dist", - "noLib": false, - "declaration": true, - "lib": [ "es6", "dom" ] - }, - "exclude": [ - "node_modules", - "dist" - ], - "filesGlob": [ - "./model/*.ts", - "./api/*.ts" - ] -} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/variables.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/variables.mustache deleted file mode 100644 index 5d3805255c2..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-inversify/variables.mustache +++ /dev/null @@ -1,6 +0,0 @@ -export const COLLECTION_FORMATS = { - 'csv': ',', - 'tsv': ' ', - 'ssv': ' ', - 'pipes': '|' -} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptInversifyClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptInversifyClientOptionsProvider.java deleted file mode 100644 index 191cd6788c3..00000000000 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptInversifyClientOptionsProvider.java +++ /dev/null @@ -1,50 +0,0 @@ -package io.swagger.codegen.options; - -import com.google.common.collect.ImmutableMap; -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.languages.TypeScriptAngularClientCodegen; -import io.swagger.codegen.languages.TypeScriptInversifyClientCodegen; - -import java.util.Map; - -public class TypeScriptInversifyClientOptionsProvider implements OptionsProvider { - public static final String SUPPORTS_ES6_VALUE = "false"; - public static final String SORT_PARAMS_VALUE = "false"; - public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; - private static final String NMP_NAME = "npmName"; - private static final String NMP_VERSION = "1.1.2"; - private static final String NPM_REPOSITORY = "https://registry.npmjs.org"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; - public static final String USE_PROMISE = "false"; - - - - @Override - public String getLanguage() { - return "typescript-inversify"; - } - - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) - .put(CodegenConstants.SUPPORTS_ES6, SUPPORTS_ES6_VALUE) - .put(TypeScriptInversifyClientCodegen.NPM_NAME, NMP_NAME) - .put(TypeScriptInversifyClientCodegen.NPM_VERSION, NMP_VERSION) - .put(TypeScriptInversifyClientCodegen.SNAPSHOT, Boolean.FALSE.toString()) - .put(TypeScriptInversifyClientCodegen.WITH_INTERFACES, Boolean.FALSE.toString()) - .put(TypeScriptInversifyClientCodegen.TAGGED_UNIONS, Boolean.FALSE.toString()) - .put(TypeScriptInversifyClientCodegen.USE_PROMISE, Boolean.FALSE.toString()) - .put(TypeScriptInversifyClientCodegen.NPM_REPOSITORY, NPM_REPOSITORY) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); - } - - @Override - public boolean isServer() { - return false; - } -} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyClientOptionsTest.java deleted file mode 100644 index 2aee4c61b5c..00000000000 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyClientOptionsTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package io.swagger.codegen.typescript.typescriptinversify; - -import io.swagger.codegen.AbstractOptionsTest; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.languages.TypeScriptInversifyClientCodegen; -import io.swagger.codegen.options.TypeScriptInversifyClientOptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class TypeScriptInversifyClientOptionsTest extends AbstractOptionsTest { - - @Tested - private TypeScriptInversifyClientCodegen clientCodegen; - - public TypeScriptInversifyClientOptionsTest() { - super(new TypeScriptInversifyClientOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptInversifyClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setModelPropertyNaming(TypeScriptInversifyClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); - times = 1; - clientCodegen.setSupportsES6(Boolean.valueOf(TypeScriptInversifyClientOptionsProvider.SUPPORTS_ES6_VALUE)); - times = 1; - }}; - } -} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyModelTest.java deleted file mode 100644 index 986f4b6956a..00000000000 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyModelTest.java +++ /dev/null @@ -1,198 +0,0 @@ -package io.swagger.codegen.typescript.typescriptinversify; - -import io.swagger.codegen.languages.TypeScriptInversifyClientCodegen; -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.google.common.collect.Sets; - -import io.swagger.codegen.CodegenModel; -import io.swagger.codegen.CodegenProperty; -import io.swagger.codegen.DefaultCodegen; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; - -@SuppressWarnings("static-method") -public class TypeScriptInversifyModelTest { - - @Test(description = "convert a simple TypeScript Angular model") - public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .property("birthDate", new DateProperty()) - .required("id") - .required("name"); - final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 4); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.datatype, "number"); - Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "undefined"); - Assert.assertEquals(property1.baseType, "number"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "name"); - Assert.assertEquals(property2.datatype, "string"); - Assert.assertEquals(property2.name, "name"); - Assert.assertEquals(property2.defaultValue, "undefined"); - Assert.assertEquals(property2.baseType, "string"); - Assert.assertTrue(property2.hasMore); - Assert.assertTrue(property2.required); - Assert.assertTrue(property2.isNotContainer); - - final CodegenProperty property3 = cm.vars.get(2); - Assert.assertEquals(property3.baseName, "createdAt"); - Assert.assertEquals(property3.complexType, null); - Assert.assertEquals(property3.datatype, "Date"); - Assert.assertEquals(property3.name, "createdAt"); - Assert.assertEquals(property3.baseType, "Date"); - Assert.assertEquals(property3.defaultValue, "undefined"); - Assert.assertTrue(property3.hasMore); - Assert.assertFalse(property3.required); - Assert.assertTrue(property3.isNotContainer); - - final CodegenProperty property4 = cm.vars.get(3); - Assert.assertEquals(property4.baseName, "birthDate"); - Assert.assertEquals(property4.complexType, null); - Assert.assertEquals(property4.datatype, "string"); - Assert.assertEquals(property4.name, "birthDate"); - Assert.assertEquals(property4.baseType, "string"); - Assert.assertEquals(property4.defaultValue, "undefined"); - Assert.assertFalse(property4.hasMore); - Assert.assertFalse(property4.required); - Assert.assertTrue(property4.isNotContainer); - } - - @Test(description = "convert a model with list property") - public void listPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty().items(new StringProperty())) - .required("id"); - final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 2); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.datatype, "number"); - Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "undefined"); - Assert.assertEquals(property1.baseType, "number"); - Assert.assertTrue(property1.hasMore); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isNotContainer); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "urls"); - Assert.assertEquals(property2.datatype, "Array"); - Assert.assertEquals(property2.name, "urls"); - Assert.assertEquals(property2.baseType, "Array"); - Assert.assertFalse(property2.hasMore); - Assert.assertFalse(property2.required); - Assert.assertTrue(property2.isContainer); - } - - @Test(description = "convert a model with complex property") - public void complexPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.datatype, "Children"); - Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.defaultValue, "undefined"); - Assert.assertEquals(property1.baseType, "Children"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isNotContainer); - } - - @Test(description = "convert a model with complex list property") - public void complexListPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))); - final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.complexType, "Children"); - Assert.assertEquals(property1.datatype, "Array"); - Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.baseType, "Array"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - } - - @Test(description = "convert an array model") - public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "an array model"); - Assert.assertEquals(cm.vars.size(), 0); - } - - @Test(description = "convert a map model") - public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); - final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a map model"); - Assert.assertEquals(cm.vars.size(), 0); - Assert.assertEquals(cm.imports.size(), 1); - Assert.assertEquals(cm.additionalPropertiesType, "Children"); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); - } -} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyArrayAndObjectIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyArrayAndObjectIntegrationTest.java deleted file mode 100644 index 6dbc175923b..00000000000 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyArrayAndObjectIntegrationTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.swagger.codegen.typescript.typescriptinversify; - -import java.util.HashMap; -import java.util.Map; - -import io.swagger.codegen.AbstractIntegrationTest; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.languages.TypeScriptInversifyClientCodegen; -import io.swagger.codegen.testutils.IntegrationTestPathsConfig; - -public class TypescriptInversifyArrayAndObjectIntegrationTest extends AbstractIntegrationTest { - - @Override - protected CodegenConfig getCodegenConfig() { - return new TypeScriptInversifyClientCodegen(); - } - - @Override - protected Map configProperties() { - Map properties = new HashMap<>(); - properties.put("npmName", "arrayAndAnyTest"); - properties.put("npmVersion", "1.0.2"); - properties.put("snapshot", "false"); - - return properties; - } - - @Override - protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { - return new IntegrationTestPathsConfig("typescript/array-and-object"); - } -} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyPestoreIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyPestoreIntegrationTest.java deleted file mode 100644 index de6cc5b5c51..00000000000 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyPestoreIntegrationTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.swagger.codegen.typescript.typescriptinversify; - -import java.util.HashMap; -import java.util.Map; - -import io.swagger.codegen.AbstractIntegrationTest; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.languages.TypeScriptInversifyClientCodegen; -import io.swagger.codegen.testutils.IntegrationTestPathsConfig; - -public class TypescriptInversifyPestoreIntegrationTest extends AbstractIntegrationTest { - - @Override - protected CodegenConfig getCodegenConfig() { - return new TypeScriptInversifyClientCodegen(); - } - - @Override - protected Map configProperties() { - Map properties = new HashMap<>(); - properties.put("npmName", "petstore-integration-test"); - properties.put("npmVersion", "1.0.3"); - properties.put("snapshot", "false"); - properties.put("usePromise", "false"); - - return properties; - } - - @Override - protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { - return new IntegrationTestPathsConfig("typescript/petstore"); - } -}