diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java index 94b64be8d02..cfdbd91851d 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java @@ -9,12 +9,9 @@ import io.swagger.codegen.cmd.Version; /** - * User: lanwen - * Date: 24.03.15 - * Time: 17:56 + * User: lanwen Date: 24.03.15 Time: 17:56 *

- * Command line interface for swagger codegen - * use `swagger-codegen-cli.jar help` for more info + * Command line interface for swagger codegen use `swagger-codegen-cli.jar help` for more info * * @since 2.1.3-M1 */ @@ -24,19 +21,15 @@ public class SwaggerCodegen { public static void main(String[] args) { String version = Version.readVersionFromResources(); @SuppressWarnings("unchecked") - Cli.CliBuilder builder = Cli.builder("swagger-codegen-cli") - .withDescription(String.format( - "Swagger code generator CLI (version %s). More info on swagger.io", - version)) - .withDefaultCommand(Langs.class) - .withCommands( - Generate.class, - Meta.class, - Langs.class, - Help.class, - ConfigHelp.class, - Version.class - ); + Cli.CliBuilder builder = + Cli.builder("swagger-codegen-cli") + .withDescription( + String.format( + "Swagger code generator CLI (version %s). More info on swagger.io", + version)) + .withDefaultCommand(Langs.class) + .withCommands(Generate.class, Meta.class, Langs.class, Help.class, + ConfigHelp.class, Version.class); builder.build().parse(args).run(); } diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java index eb2f8afea92..1ff3dfbb84f 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java @@ -20,7 +20,8 @@ public void run() { System.out.println("CONFIG OPTIONS"); for (CliOption langCliOption : config.cliOptions()) { System.out.println("\t" + langCliOption.getOpt()); - System.out.println("\t " + langCliOption.getOptionHelp().replaceAll("\n", "\n\t ")); + System.out.println("\t " + + langCliOption.getOptionHelp().replaceAll("\n", "\n\t ")); System.out.println(); } } diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java index 01303e64559..b5bccaa9811 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java @@ -13,9 +13,7 @@ import static org.apache.commons.lang3.StringUtils.isNotEmpty; /** - * User: lanwen - * Date: 24.03.15 - * Time: 20:22 + * User: lanwen Date: 24.03.15 Time: 20:22 */ @Command(name = "generate", description = "Generate code with chosen lang") @@ -42,163 +40,197 @@ public class Generate implements Runnable { description = "folder containing the template files") private String templateDir; - @Option(name = {"-a", "--auth"}, title = "authorization", - description = "adds authorization headers when fetching the swagger definitions remotely. " + - "Pass in a URL-encoded string of name:header with a comma separating multiple values") + @Option( + name = {"-a", "--auth"}, + title = "authorization", + description = "adds authorization headers when fetching the swagger definitions remotely. " + + "Pass in a URL-encoded string of name:header with a comma separating multiple values") private String auth; - @Option(name = {"-D"}, title = "system properties", description = "sets specified system properties in " + - "the format of name=value,name=value") + @Option(name = {"-D"}, title = "system properties", + description = "sets specified system properties in " + + "the format of name=value,name=value") private String systemProperties; - @Option(name = {"-c", "--config"}, title = "configuration file", description = "Path to json configuration file. " + - "File content should be in a json format {\"optionKey\":\"optionValue\", \"optionKey1\":\"optionValue1\"...} " + - "Supported options can be different for each language. Run config-help -l {lang} command for language specific config options.") + @Option( + name = {"-c", "--config"}, + title = "configuration file", + description = "Path to json configuration file. " + + "File content should be in a json format {\"optionKey\":\"optionValue\", \"optionKey1\":\"optionValue1\"...} " + + "Supported options can be different for each language. Run config-help -l {lang} command for language specific config options.") private String configFile; - @Option(name = {"-s", "--skip-overwrite"}, title = "skip overwrite", description = "specifies if the existing files should be " + - "overwritten during the generation.") + @Option(name = {"-s", "--skip-overwrite"}, title = "skip overwrite", + description = "specifies if the existing files should be " + + "overwritten during the generation.") private Boolean skipOverwrite; - @Option(name = {"--api-package"}, title = "api package", description = CodegenConstants.API_PACKAGE_DESC) + @Option(name = {"--api-package"}, title = "api package", + description = CodegenConstants.API_PACKAGE_DESC) private String apiPackage; - @Option(name = {"--model-package"}, title = "model package", description = CodegenConstants.MODEL_PACKAGE_DESC) + @Option(name = {"--model-package"}, title = "model package", + description = CodegenConstants.MODEL_PACKAGE_DESC) private String modelPackage; - @Option(name = {"--model-name-prefix"}, title = "model name prefix", description = CodegenConstants.MODEL_NAME_PREFIX_DESC) + @Option(name = {"--model-name-prefix"}, title = "model name prefix", + description = CodegenConstants.MODEL_NAME_PREFIX_DESC) private String modelNamePrefix; - @Option(name = {"--model-name-suffix"}, title = "model name suffix", description = CodegenConstants.MODEL_NAME_SUFFIX_DESC) + @Option(name = {"--model-name-suffix"}, title = "model name suffix", + description = CodegenConstants.MODEL_NAME_SUFFIX_DESC) private String modelNameSuffix; - @Option(name = {"--instantiation-types"}, title = "instantiation types", description = "sets instantiation type mappings in the format of type=instantiatedType,type=instantiatedType." + - "For example (in Java): array=ArrayList,map=HashMap. In other words array types will get instantiated as ArrayList in generated code.") + @Option( + name = {"--instantiation-types"}, + title = "instantiation types", + description = "sets instantiation type mappings in the format of type=instantiatedType,type=instantiatedType." + + "For example (in Java): array=ArrayList,map=HashMap. In other words array types will get instantiated as ArrayList in generated code.") private String instantiationTypes; - @Option(name = {"--type-mappings"}, title = "type mappings", description = "sets mappings between swagger spec types and generated code types " + - "in the format of swaggerType=generatedType,swaggerType=generatedType. For example: array=List,map=Map,string=String") + @Option( + name = {"--type-mappings"}, + title = "type mappings", + description = "sets mappings between swagger spec types and generated code types " + + "in the format of swaggerType=generatedType,swaggerType=generatedType. For example: array=List,map=Map,string=String") private String typeMappings; - @Option(name = {"--additional-properties"}, title = "additional properties", description = "sets additional properties that can be referenced by the mustache templates in the format of name=value,name=value") + @Option( + name = {"--additional-properties"}, + title = "additional properties", + description = "sets additional properties that can be referenced by the mustache templates in the format of name=value,name=value") private String additionalProperties; - @Option(name = {"--language-specific-primitives"}, title = "language specific primitives", + @Option( + name = {"--language-specific-primitives"}, + title = "language specific primitives", description = "specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: String,boolean,Boolean,Double") private String languageSpecificPrimitives; - @Option(name = {"--import-mappings"}, title = "import mappings", + @Option( + name = {"--import-mappings"}, + title = "import mappings", description = "specifies mappings between a given class and the import that should be used for that class in the format of type=import,type=import") private String importMappings; - @Option(name = {"--invoker-package"}, title = "invoker package", description = CodegenConstants.INVOKER_PACKAGE_DESC) + @Option(name = {"--invoker-package"}, title = "invoker package", + description = CodegenConstants.INVOKER_PACKAGE_DESC) private String invokerPackage; @Option(name = {"--group-id"}, title = "group id", description = CodegenConstants.GROUP_ID_DESC) private String groupId; - @Option(name = {"--artifact-id"}, title = "artifact id", description = CodegenConstants.ARTIFACT_ID_DESC) + @Option(name = {"--artifact-id"}, title = "artifact id", + description = CodegenConstants.ARTIFACT_ID_DESC) private String artifactId; - @Option(name = {"--artifact-version"}, title = "artifact version", description = CodegenConstants.ARTIFACT_VERSION_DESC) + @Option(name = {"--artifact-version"}, title = "artifact version", + description = CodegenConstants.ARTIFACT_VERSION_DESC) private String artifactVersion; @Option(name = {"--library"}, title = "library", description = CodegenConstants.LIBRARY_DESC) private String library; - - @Option(name = {"--git-user-id"}, title = "git user id", description = CodegenConstants.GIT_USER_ID_DESC) + + @Option(name = {"--git-user-id"}, title = "git user id", + description = CodegenConstants.GIT_USER_ID_DESC) private String gitUserId; - @Option(name = {"--git-repo-id"}, title = "git repo id", description = CodegenConstants.GIT_REPO_ID_DESC) + @Option(name = {"--git-repo-id"}, title = "git repo id", + description = CodegenConstants.GIT_REPO_ID_DESC) private String gitRepoId; - @Option(name = {"--release-note"}, title = "release note", description = CodegenConstants.RELEASE_NOTE_DESC) + @Option(name = {"--release-note"}, title = "release note", + description = CodegenConstants.RELEASE_NOTE_DESC) private String releaseNote; - @Option(name = {"--http-user-agent"}, title = "http user agent", description = CodegenConstants.HTTP_USER_AGENT_DESC) + @Option(name = {"--http-user-agent"}, title = "http user agent", + description = CodegenConstants.HTTP_USER_AGENT_DESC) private String httpUserAgent; - - @Option(name = {"--reserved-words-mappings"}, title = "import mappings", + + @Option( + name = {"--reserved-words-mappings"}, + title = "import mappings", description = "specifies how a reserved name should be escaped to. Otherwise, the default _ is used. For example id=identifier") private String reservedWordsMappings; - @Option(name = {"--ignore-file-override"}, title = "ignore file override location", description = CodegenConstants.IGNORE_FILE_OVERRIDE_DESC) + @Option(name = {"--ignore-file-override"}, title = "ignore file override location", + description = CodegenConstants.IGNORE_FILE_OVERRIDE_DESC) private String ignoreFileOverride; - + @Override public void run() { - //attempt to read from config file + // attempt to read from config file CodegenConfigurator configurator = CodegenConfigurator.fromFile(configFile); - //if a config file wasn't specified or we were unable to read it - if(configurator == null) { - //createa a fresh configurator + // if a config file wasn't specified or we were unable to read it + if (configurator == null) { + // createa a fresh configurator configurator = new CodegenConfigurator(); } - //now override with any specified parameters + // now override with any specified parameters if (verbose != null) { configurator.setVerbose(verbose); } - if(skipOverwrite != null) { + if (skipOverwrite != null) { configurator.setSkipOverwrite(skipOverwrite); } - if(isNotEmpty(spec)) { + if (isNotEmpty(spec)) { configurator.setInputSpec(spec); } - if(isNotEmpty(lang)) { + if (isNotEmpty(lang)) { configurator.setLang(lang); } - if(isNotEmpty(output)) { + if (isNotEmpty(output)) { configurator.setOutputDir(output); } - if(isNotEmpty(auth)) { + if (isNotEmpty(auth)) { configurator.setAuth(auth); } - if(isNotEmpty(templateDir)) { + if (isNotEmpty(templateDir)) { configurator.setTemplateDir(templateDir); } - if(isNotEmpty(apiPackage)) { + if (isNotEmpty(apiPackage)) { configurator.setApiPackage(apiPackage); } - if(isNotEmpty(modelPackage)) { + if (isNotEmpty(modelPackage)) { configurator.setModelPackage(modelPackage); } - if(isNotEmpty(modelNamePrefix)){ + if (isNotEmpty(modelNamePrefix)) { configurator.setModelNamePrefix(modelNamePrefix); } - if(isNotEmpty(modelNameSuffix)){ + if (isNotEmpty(modelNameSuffix)) { configurator.setModelNameSuffix(modelNameSuffix); } - if(isNotEmpty(invokerPackage)) { + if (isNotEmpty(invokerPackage)) { configurator.setInvokerPackage(invokerPackage); } - if(isNotEmpty(groupId)) { + if (isNotEmpty(groupId)) { configurator.setGroupId(groupId); } - if(isNotEmpty(artifactId)) { + if (isNotEmpty(artifactId)) { configurator.setArtifactId(artifactId); } - if(isNotEmpty(artifactVersion)) { + if (isNotEmpty(artifactVersion)) { configurator.setArtifactVersion(artifactVersion); } - if(isNotEmpty(library)) { + if (isNotEmpty(library)) { configurator.setLibrary(library); } diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Langs.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Langs.java index c3d7391579e..007da38d2f6 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Langs.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Langs.java @@ -9,15 +9,14 @@ import static java.util.ServiceLoader.load; /** - * User: lanwen - * Date: 24.03.15 - * Time: 20:25 + * User: lanwen Date: 24.03.15 Time: 20:25 */ @Command(name = "langs", description = "Shows available langs") public class Langs implements Runnable { @Override public void run() { - LambdaIterable langs = with(load(CodegenConfig.class)).extract(on(CodegenConfig.class).getName()); + LambdaIterable langs = + with(load(CodegenConfig.class)).extract(on(CodegenConfig.class).getName()); System.out.printf("Available languages: %s%n", langs); } } diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java index 3b5d71eec9f..e52e121e801 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java @@ -23,14 +23,12 @@ import static com.google.common.base.Joiner.on; /** - * User: lanwen - * Date: 24.03.15 - * Time: 20:22 + * User: lanwen Date: 24.03.15 Time: 20:22 */ -@Command(name = "meta", description = "MetaGenerator. Generator for creating a new template set " + - "and configuration for Codegen. The output will be based on the language you " + - "specify, and includes default templates to include.") +@Command(name = "meta", description = "MetaGenerator. Generator for creating a new template set " + + "and configuration for Codegen. The output will be based on the language you " + + "specify, and includes default templates to include.") public class Meta implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(Meta.class); @@ -57,58 +55,62 @@ public void run() { String mainClass = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name) + "Generator"; - List supportingFiles = ImmutableList.of( - new SupportingFile("pom.mustache", "", "pom.xml"), - new SupportingFile("generatorClass.mustache", - on(File.separator).join("src/main/java", asPath(targetPackage)), mainClass.concat(".java")), - new SupportingFile("README.mustache", "", "README.md"), - new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache"), - new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache"), - new SupportingFile("services.mustache", - "src/main/resources/META-INF/services", "io.swagger.codegen.CodegenConfig") - ); + List supportingFiles = + ImmutableList + .of(new SupportingFile("pom.mustache", "", "pom.xml"), + new SupportingFile("generatorClass.mustache", on(File.separator) + .join("src/main/java", asPath(targetPackage)), mainClass + .concat(".java")), new SupportingFile("README.mustache", + "", "README.md"), new SupportingFile("api.template", + "src/main/resources" + File.separator + name, + "api.mustache"), new SupportingFile("model.template", + "src/main/resources" + File.separator + name, + "model.mustache"), new SupportingFile("services.mustache", + "src/main/resources/META-INF/services", + "io.swagger.codegen.CodegenConfig")); String swaggerVersion = Version.readVersionFromResources(); - Map data = new ImmutableMap.Builder() - .put("generatorPackage", targetPackage) - .put("generatorClass", mainClass) - .put("name", name) - .put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass) - .put("swaggerCodegenVersion", swaggerVersion).build(); + Map data = + new ImmutableMap.Builder().put("generatorPackage", targetPackage) + .put("generatorClass", mainClass).put("name", name) + .put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass) + .put("swaggerCodegenVersion", swaggerVersion).build(); with(supportingFiles).convert(processFiles(targetDir, data)); } /** - * Converter method to process supporting files: execute with mustache, - * or simply copy to destination directory + * Converter method to process supporting files: execute with mustache, or simply copy to + * destination directory * * @param targetDir - destination directory - * @param data - map with additional params needed to process templates + * @param data - map with additional params needed to process templates * @return converter object to pass to lambdaj */ - private static Converter processFiles(final File targetDir, final Map data) { + private static Converter processFiles(final File targetDir, + final Map data) { return new Converter() { private DefaultGenerator generator = new DefaultGenerator(); @Override public File convert(SupportingFile support) { try { - File destinationFolder = new File(new File(targetDir.getAbsolutePath()), support.folder); + File destinationFolder = + new File(new File(targetDir.getAbsolutePath()), support.folder); File outputFile = new File(destinationFolder, support.destinationFilename); - String template = generator - .readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.templateFile).getPath()); + String template = + generator.readTemplate(new File(TEMPLATE_DIR_CLASSPATH, + support.templateFile).getPath()); String formatted = template; if (support.templateFile.endsWith(MUSTACHE_EXTENSION)) { LOGGER.info("writing file to {}", outputFile.getAbsolutePath()); - formatted = Mustache.compiler().withLoader(loader(generator)) - .defaultValue("") - .compile(template) - .execute(data); + formatted = + Mustache.compiler().withLoader(loader(generator)).defaultValue("") + .compile(template).execute(data); } else { LOGGER.info("copying file to {}", outputFile.getAbsolutePath()); } @@ -133,8 +135,8 @@ private static Mustache.TemplateLoader loader(final DefaultGenerator generator) return new Mustache.TemplateLoader() { @Override public Reader getTemplate(String name) { - return generator.getTemplateReader(TEMPLATE_DIR_CLASSPATH - + File.separator + name.concat(MUSTACHE_EXTENSION)); + return generator.getTemplateReader(TEMPLATE_DIR_CLASSPATH + File.separator + + name.concat(MUSTACHE_EXTENSION)); } }; } diff --git a/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/GenerateTest.java b/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/GenerateTest.java index 36a560b776d..397495927d4 100644 --- a/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/GenerateTest.java +++ b/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/GenerateTest.java @@ -28,31 +28,40 @@ public class GenerateTest { public void testVerbose() throws Exception { setupAndRunGenericTest("-v"); - new FullVerifications() {{ - configurator.setVerbose(true); - times = 1; - }}; + new FullVerifications() { + { + configurator.setVerbose(true); + times = 1; + } + }; setupAndRunGenericTest("--verbose"); - new FullVerifications() {{ - configurator.setVerbose(true); - times = 1; - }}; + new FullVerifications() { + { + configurator.setVerbose(true); + times = 1; + } + }; } @Test public void testRequiredArgs_ShortArgs() throws Exception { setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", false, null); - new FullVerifications() {{ - }}; + new FullVerifications() { + { + } + }; } @Test public void testRequiredArgs_LongArgs() throws Exception { - setupAndRunTest("--input-spec", "swagger.yaml", "--lang", "java", "--output", "src/main/java", false, null); - new FullVerifications() {{ - }}; + setupAndRunTest("--input-spec", "swagger.yaml", "--lang", "java", "--output", + "src/main/java", false, null); + new FullVerifications() { + { + } + }; } @Test @@ -62,17 +71,21 @@ public void testTemplateDir() throws Exception { setupAndRunGenericTest("--template-dir", templateDir); - new FullVerifications() {{ - configurator.setTemplateDir(templateDir); - times = 1; - }}; + new FullVerifications() { + { + configurator.setTemplateDir(templateDir); + times = 1; + } + }; setupAndRunGenericTest("-t", templateDir); - new FullVerifications() {{ - configurator.setTemplateDir(templateDir); - times = 1; - }}; + new FullVerifications() { + { + configurator.setTemplateDir(templateDir); + times = 1; + } + }; } @Test @@ -82,24 +95,30 @@ public void testAuth() throws Exception { setupAndRunGenericTest("--auth", auth); - new FullVerifications() {{ - configurator.setAuth(auth); - times = 1; - }}; + new FullVerifications() { + { + configurator.setAuth(auth); + times = 1; + } + }; setupAndRunGenericTest("-a", auth); - new FullVerifications() {{ - configurator.setAuth(auth); - times = 1; - }}; + new FullVerifications() { + { + configurator.setAuth(auth); + times = 1; + } + }; setupAndRunGenericTest(); - new FullVerifications() {{ - configurator.setAuth(anyString); - times = 0; - }}; + new FullVerifications() { + { + configurator.setAuth(anyString); + times = 0; + } + }; } @Test @@ -107,50 +126,68 @@ public void testSystemProperties() throws Exception { setupAndRunGenericTest("-D", "hello=world,foo=bar"); - new FullVerifications() {{ - configurator.addSystemProperty("hello", "world"); - times = 1; - configurator.addSystemProperty("foo", "bar"); - times = 1; - }}; + new FullVerifications() { + { + configurator.addSystemProperty("hello", "world"); + times = 1; + configurator.addSystemProperty("foo", "bar"); + times = 1; + } + }; setupAndRunGenericTest("-D", "hello=world,key=,foo=bar"); - new FullVerifications() {{ - configurator.addSystemProperty("hello", "world"); - times = 1; - configurator.addSystemProperty("foo", "bar"); - times = 1; - configurator.addSystemProperty("key", anyString); - times = 0; - }}; + new FullVerifications() { + { + configurator.addSystemProperty("hello", "world"); + times = 1; + configurator.addSystemProperty("foo", "bar"); + times = 1; + configurator.addSystemProperty("key", anyString); + times = 0; + } + }; } @Test public void testConfig() throws Exception { - setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", true, "config.json", "-c", "config.json"); + setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", true, + "config.json", "-c", "config.json"); - new FullVerifications(){{}}; + new FullVerifications() { + { + } + }; - setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", true, "config.json", "--config", "config.json"); + setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", true, + "config.json", "--config", "config.json"); - new FullVerifications(){{}}; + new FullVerifications() { + { + } + }; } @Test public void testSkipOverwrite() throws Exception { setupAndRunGenericTest("-s"); - new FullVerifications(){{ - configurator.setSkipOverwrite(true); times=1; - }}; + new FullVerifications() { + { + configurator.setSkipOverwrite(true); + times = 1; + } + }; setupAndRunGenericTest("--skip-overwrite"); - new FullVerifications(){{ - configurator.setSkipOverwrite(true); times=1; - }}; + new FullVerifications() { + { + configurator.setSkipOverwrite(true); + times = 1; + } + }; } @Test @@ -158,9 +195,12 @@ public void testApiPackage() throws Exception { final String value = "io.foo.bar.api"; setupAndRunGenericTest("--api-package", value); - new FullVerifications(){{ - configurator.setApiPackage(value); times=1; - }}; + new FullVerifications() { + { + configurator.setApiPackage(value); + times = 1; + } + }; } @Test @@ -168,9 +208,12 @@ public void testModelPackage() throws Exception { final String value = "io.foo.bar.api"; setupAndRunGenericTest("--model-package", value); - new FullVerifications(){{ - configurator.setModelPackage(value); times=1; - }}; + new FullVerifications() { + { + configurator.setModelPackage(value); + times = 1; + } + }; } @Test @@ -178,72 +221,82 @@ public void testInstantiationTypes() throws Exception { setupAndRunGenericTest("--instantiation-types", "hello=world,key=,foo=bar"); - new FullVerifications() {{ - configurator.addInstantiationType("hello", "world"); - times = 1; - configurator.addInstantiationType("foo", "bar"); - times = 1; - configurator.addInstantiationType("key", anyString); - times = 0; - }}; + new FullVerifications() { + { + configurator.addInstantiationType("hello", "world"); + times = 1; + configurator.addInstantiationType("foo", "bar"); + times = 1; + configurator.addInstantiationType("key", anyString); + times = 0; + } + }; } @Test public void testTypeMappings() throws Exception { setupAndRunGenericTest("--type-mappings", "hello=world,key=,foo=bar"); - new FullVerifications() {{ - configurator.addTypeMapping("hello", "world"); - times = 1; - configurator.addTypeMapping("foo", "bar"); - times = 1; - configurator.addTypeMapping("key", anyString); - times = 0; - }}; + new FullVerifications() { + { + configurator.addTypeMapping("hello", "world"); + times = 1; + configurator.addTypeMapping("foo", "bar"); + times = 1; + configurator.addTypeMapping("key", anyString); + times = 0; + } + }; } @Test public void testAdditionalProperties() throws Exception { setupAndRunGenericTest("--additional-properties", "hello=world,key=,foo=bar"); - new FullVerifications() {{ - configurator.addAdditionalProperty("hello", "world"); - times = 1; - configurator.addAdditionalProperty("foo", "bar"); - times = 1; - configurator.addAdditionalProperty("key", anyString); - times = 0; - }}; + new FullVerifications() { + { + configurator.addAdditionalProperty("hello", "world"); + times = 1; + configurator.addAdditionalProperty("foo", "bar"); + times = 1; + configurator.addAdditionalProperty("key", anyString); + times = 0; + } + }; } @Test public void testLanguageSpecificPrimitives() throws Exception { setupAndRunGenericTest("--language-specific-primitives", "foo,bar,,hello,world"); - new FullVerifications() {{ - configurator.addLanguageSpecificPrimitive("foo"); - times = 1; - configurator.addLanguageSpecificPrimitive("bar"); - times = 1; - configurator.addLanguageSpecificPrimitive("hello"); - times = 1; - configurator.addLanguageSpecificPrimitive("world"); - times = 1; - }}; + new FullVerifications() { + { + configurator.addLanguageSpecificPrimitive("foo"); + times = 1; + configurator.addLanguageSpecificPrimitive("bar"); + times = 1; + configurator.addLanguageSpecificPrimitive("hello"); + times = 1; + configurator.addLanguageSpecificPrimitive("world"); + times = 1; + } + }; } @Test public void testImportMappings() throws Exception { setupAndRunGenericTest("--import-mappings", "hello=world,key=,foo=bar"); - new FullVerifications() {{ - configurator.addImportMapping("hello", "world"); - times = 1; - configurator.addImportMapping("foo", "bar"); - times = 1; - configurator.addImportMapping("key", anyString); - times = 0; - }}; + new FullVerifications() { + { + configurator.addImportMapping("hello", "world"); + times = 1; + configurator.addImportMapping("foo", "bar"); + times = 1; + configurator.addImportMapping("key", anyString); + times = 0; + } + }; } @Test @@ -251,9 +304,12 @@ public void testInvokerPackage() throws Exception { final String value = "io.foo.bar.api"; setupAndRunGenericTest("--invoker-package", value); - new FullVerifications(){{ - configurator.setInvokerPackage(value); times=1; - }}; + new FullVerifications() { + { + configurator.setInvokerPackage(value); + times = 1; + } + }; } @Test @@ -261,9 +317,12 @@ public void testGroupId() throws Exception { final String value = "io.foo.bar.api"; setupAndRunGenericTest("--group-id", value); - new FullVerifications(){{ - configurator.setGroupId(value); times=1; - }}; + new FullVerifications() { + { + configurator.setGroupId(value); + times = 1; + } + }; } @Test @@ -271,9 +330,12 @@ public void testArtifactId() throws Exception { final String value = "awesome-api"; setupAndRunGenericTest("--artifact-id", value); - new FullVerifications(){{ - configurator.setArtifactId(value); times=1; - }}; + new FullVerifications() { + { + configurator.setArtifactId(value); + times = 1; + } + }; } @Test @@ -281,9 +343,12 @@ public void testArtifactVersion() throws Exception { final String value = "1.2.3"; setupAndRunGenericTest("--artifact-version", value); - new FullVerifications(){{ - configurator.setArtifactVersion(value); times=1; - }}; + new FullVerifications() { + { + configurator.setArtifactVersion(value); + times = 1; + } + }; } @Test @@ -291,68 +356,81 @@ public void testLibrary() throws Exception { final String value = "library1"; setupAndRunGenericTest("--library", value); - new FullVerifications(){{ - configurator.setLibrary(value); times=1; - }}; + new FullVerifications() { + { + configurator.setLibrary(value); + times = 1; + } + }; } - private void setupAndRunTest(String specFlag, final String spec, String langFlag, final String lang, - String outputDirFlag, final String outputDir, boolean configuratorFromFile, - final String configFile, String... additionalParameters) { - final String[] commonArgs = {"generate", langFlag, lang, outputDirFlag, outputDir, specFlag, spec}; + private void setupAndRunTest(String specFlag, final String spec, String langFlag, + final String lang, String outputDirFlag, final String outputDir, + boolean configuratorFromFile, final String configFile, String... additionalParameters) { + final String[] commonArgs = + {"generate", langFlag, lang, outputDirFlag, outputDir, specFlag, spec}; String[] argsToUse = ArrayUtils.addAll(commonArgs, additionalParameters); if (configuratorFromFile) { - new Expectations(){{ - CodegenConfigurator.fromFile(configFile); - times = 1; - result = configurator; - }}; + new Expectations() { + { + CodegenConfigurator.fromFile(configFile); + times = 1; + result = configurator; + } + }; } else { - new Expectations() {{ - CodegenConfigurator.fromFile(anyString); - result = null; - - new CodegenConfigurator(); - times = 1; - result = configurator; - }}; + new Expectations() { + { + CodegenConfigurator.fromFile(anyString); + result = null; + + new CodegenConfigurator(); + times = 1; + result = configurator; + } + }; } - new Expectations() {{ + new Expectations() { + { - configurator.toClientOptInput(); - times = 1; - result = clientOptInput; + configurator.toClientOptInput(); + times = 1; + result = clientOptInput; - new DefaultGenerator(); - times = 1; - result = generator; + new DefaultGenerator(); + times = 1; + result = generator; - generator.opts(clientOptInput); - times = 1; - result = generator; + generator.opts(clientOptInput); + times = 1; + result = generator; - generator.generate(); - times = 1; + generator.generate(); + times = 1; - }}; + } + }; SwaggerCodegen.main(argsToUse); - new Verifications() {{ - configurator.setLang(lang); - times = 1; - configurator.setInputSpec(spec); - times = 1; - configurator.setOutputDir(outputDir); - }}; + new Verifications() { + { + configurator.setLang(lang); + times = 1; + configurator.setInputSpec(spec); + times = 1; + configurator.setOutputDir(outputDir); + } + }; } private void setupAndRunGenericTest(String... additionalParameters) { - setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", false, null, additionalParameters); + setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", false, null, + additionalParameters); } } diff --git a/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/utils/OptionUtilsTest.java b/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/utils/OptionUtilsTest.java index db88cdcdb9d..292a5d5520e 100644 --- a/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/utils/OptionUtilsTest.java +++ b/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/utils/OptionUtilsTest.java @@ -24,7 +24,8 @@ public void splitCommaSeparatedList() throws Exception { @Test public void testParseCommaSeparatedTuples() throws Exception { - doTupleListTest("a=1,b=2,c=3", Arrays.asList(Pair.of("a", "1"), Pair.of("b", "2"), Pair.of("c", "3"))); + doTupleListTest("a=1,b=2,c=3", + Arrays.asList(Pair.of("a", "1"), Pair.of("b", "2"), Pair.of("c", "3"))); doTupleListTest("a=1,,c=3", Arrays.asList(Pair.of("a", "1"), Pair.of("c", "3"))); doTupleListTest("a=1,xyz,c=3", Arrays.asList(Pair.of("a", "1"), Pair.of("c", "3"))); doTupleListTest("a=1,=,c=3", Arrays.asList(Pair.of("a", "1"), Pair.of("c", "3"))); diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java index 613c2b9186f..e681a940fa1 100644 --- a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java +++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java @@ -2,18 +2,16 @@ /* * Copyright 2001-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyAdditionalPropertiesKvp; @@ -48,7 +46,7 @@ @Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES) public class CodeGenMojo extends AbstractMojo { - @Parameter(name="verbose", required = false, defaultValue = "false") + @Parameter(name = "verbose", required = false, defaultValue = "false") private boolean verbose; /** @@ -60,8 +58,7 @@ public class CodeGenMojo extends AbstractMojo { /** * Location of the output directory. */ - @Parameter(name = "output", - property = "swagger.codegen.maven.plugin.output", + @Parameter(name = "output", property = "swagger.codegen.maven.plugin.output", defaultValue = "${project.build.directory}/generated-sources/swagger") private File output; @@ -90,10 +87,10 @@ public class CodeGenMojo extends AbstractMojo { private File templateDirectory; /** - * Adds authorization headers when fetching the swagger definitions remotely. - " Pass in a URL-encoded string of name:header with a comma separating multiple values + * Adds authorization headers when fetching the swagger definitions remotely. " Pass in a + * URL-encoded string of name:header with a comma separating multiple values */ - @Parameter(name="auth") + @Parameter(name = "auth") private String auth; /** @@ -105,7 +102,7 @@ public class CodeGenMojo extends AbstractMojo { /** * Specifies if the existing files should be overwritten during the generation. */ - @Parameter(name="skipOverwrite", required=false) + @Parameter(name = "skipOverwrite", required = false) private Boolean skipOverwrite; /** @@ -175,8 +172,8 @@ public class CodeGenMojo extends AbstractMojo { private Map configOptions; /** - * Add the output directory to the project as a source root, so that the - * generated java types are compiled and included in the project artifact. + * Add the output directory to the project as a source root, so that the generated java types + * are compiled and included in the project artifact. */ @Parameter(defaultValue = "true") private boolean addCompileSourceRoot = true; @@ -196,33 +193,33 @@ public class CodeGenMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException { - //attempt to read from config file + // attempt to read from config file CodegenConfigurator configurator = CodegenConfigurator.fromFile(configurationFile); - //if a config file wasn't specified or we were unable to read it - if(configurator == null) { + // if a config file wasn't specified or we were unable to read it + if (configurator == null) { configurator = new CodegenConfigurator(); } configurator.setVerbose(verbose); - if(skipOverwrite != null) { + if (skipOverwrite != null) { configurator.setSkipOverwrite(skipOverwrite); } - if(isNotEmpty(inputSpec)) { + if (isNotEmpty(inputSpec)) { configurator.setInputSpec(inputSpec); } - if(isNotEmpty(gitUserId)) { + if (isNotEmpty(gitUserId)) { configurator.setGitUserId(gitUserId); } - if(isNotEmpty(gitRepoId)) { + if (isNotEmpty(gitRepoId)) { configurator.setGitRepoId(gitRepoId); } - if(isNotEmpty(ignoreFileOverride)) { + if (isNotEmpty(ignoreFileOverride)) { configurator.setIgnoreFileOverride(ignoreFileOverride); } @@ -230,43 +227,43 @@ public void execute() throws MojoExecutionException { configurator.setOutputDir(output.getAbsolutePath()); - if(isNotEmpty(auth)) { + if (isNotEmpty(auth)) { configurator.setAuth(auth); } - if(isNotEmpty(apiPackage)) { + if (isNotEmpty(apiPackage)) { configurator.setApiPackage(apiPackage); } - if(isNotEmpty(modelPackage)) { + if (isNotEmpty(modelPackage)) { configurator.setModelPackage(modelPackage); } - if(isNotEmpty(invokerPackage)) { + if (isNotEmpty(invokerPackage)) { configurator.setInvokerPackage(invokerPackage); } - if(isNotEmpty(groupId)) { + if (isNotEmpty(groupId)) { configurator.setGroupId(groupId); } - if(isNotEmpty(artifactId)) { + if (isNotEmpty(artifactId)) { configurator.setArtifactId(artifactId); } - if(isNotEmpty(artifactVersion)) { + if (isNotEmpty(artifactVersion)) { configurator.setArtifactVersion(artifactVersion); } - if(isNotEmpty(library)) { + if (isNotEmpty(library)) { configurator.setLibrary(library); } - if(isNotEmpty(modelNamePrefix)) { + if (isNotEmpty(modelNamePrefix)) { configurator.setModelNamePrefix(modelNamePrefix); } - if(isNotEmpty(modelNameSuffix)) { + if (isNotEmpty(modelNameSuffix)) { configurator.setModelNameSuffix(modelNameSuffix); } @@ -276,36 +273,41 @@ public void execute() throws MojoExecutionException { if (configOptions != null) { - if(configOptions.containsKey("instantiation-types")) { - applyInstantiationTypesKvp(configOptions.get("instantiation-types").toString(), configurator); + if (configOptions.containsKey("instantiation-types")) { + applyInstantiationTypesKvp(configOptions.get("instantiation-types").toString(), + configurator); } - if(configOptions.containsKey("import-mappings")) { - applyImportMappingsKvp(configOptions.get("import-mappings").toString(), configurator); + if (configOptions.containsKey("import-mappings")) { + applyImportMappingsKvp(configOptions.get("import-mappings").toString(), + configurator); } - if(configOptions.containsKey("type-mappings")) { + if (configOptions.containsKey("type-mappings")) { applyTypeMappingsKvp(configOptions.get("type-mappings").toString(), configurator); } - if(configOptions.containsKey("language-specific-primitives")) { - applyLanguageSpecificPrimitivesCsv(configOptions.get("language-specific-primitives").toString(), configurator); + if (configOptions.containsKey("language-specific-primitives")) { + applyLanguageSpecificPrimitivesCsv(configOptions + .get("language-specific-primitives").toString(), configurator); } - if(configOptions.containsKey("additional-properties")) { - applyAdditionalPropertiesKvp(configOptions.get("additional-properties").toString(), configurator); + if (configOptions.containsKey("additional-properties")) { + applyAdditionalPropertiesKvp(configOptions.get("additional-properties").toString(), + configurator); } - - if(configOptions.containsKey("reserved-words-mappings")) { - applyReservedWordsMappingsKvp(configOptions.get("reserved-words-mappings").toString(), configurator); + + if (configOptions.containsKey("reserved-words-mappings")) { + applyReservedWordsMappingsKvp(configOptions.get("reserved-words-mappings") + .toString(), configurator); } } if (environmentVariables != null) { - for(String key : environmentVariables.keySet()) { + for (String key : environmentVariables.keySet()) { String value = environmentVariables.get(key); - if(value == null) { + if (value == null) { // don't put null values value = ""; } @@ -313,23 +315,24 @@ public void execute() throws MojoExecutionException { configurator.addSystemProperty(key, value); } } - + final ClientOptInput input = configurator.toClientOptInput(); final CodegenConfig config = input.getConfig(); - if(configOptions != null) { + if (configOptions != null) { for (CliOption langCliOption : config.cliOptions()) { if (configOptions.containsKey(langCliOption.getOpt())) { - input.getConfig().additionalProperties().put(langCliOption.getOpt(), - configOptions.get(langCliOption.getOpt())); + input.getConfig().additionalProperties() + .put(langCliOption.getOpt(), configOptions.get(langCliOption.getOpt())); } } } - if(configHelp) { + if (configHelp) { for (CliOption langCliOption : config.cliOptions()) { System.out.println("\t" + langCliOption.getOpt()); - System.out.println("\t " + langCliOption.getOptionHelp().replaceAll("\n", "\n\t ")); + System.out.println("\t " + + langCliOption.getOptionHelp().replaceAll("\n", "\n\t ")); System.out.println(); } return; @@ -340,13 +343,17 @@ public void execute() throws MojoExecutionException { // Maven logs exceptions thrown by plugins only if invoked with -e // I find it annoying to jump through hoops to get basic diagnostic information, // so let's log it in any case: - getLog().error(e); - throw new MojoExecutionException("Code generation failed. See above for the full exception."); + getLog().error(e); + throw new MojoExecutionException( + "Code generation failed. See above for the full exception."); } if (addCompileSourceRoot) { - final Object sourceFolderObject = configOptions == null ? null : configOptions.get(CodegenConstants.SOURCE_FOLDER); - final String sourceFolder = sourceFolderObject == null ? "src/main/java" : sourceFolderObject.toString(); + final Object sourceFolderObject = + configOptions == null ? null : configOptions + .get(CodegenConstants.SOURCE_FOLDER); + final String sourceFolder = + sourceFolderObject == null ? "src/main/java" : sourceFolderObject.toString(); String sourceJavaFolder = output.toString() + "/" + sourceFolder; project.addCompileSourceRoot(sourceJavaFolder); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java index abf77b59cb1..94ae8390ebd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java @@ -28,8 +28,8 @@ public File writeToFile(String filename, String contents) throws IOException { File parent = new File(output.getParent()); parent.mkdirs(); } - Writer out = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(output), "UTF-8")); + Writer out = + new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output), "UTF-8")); out.write(contents); out.close(); @@ -52,7 +52,8 @@ public String readTemplate(String name) { public Reader getTemplateReader(String name) { try { - InputStream is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name)); + InputStream is = + this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name)); if (is == null) { is = new FileInputStream(new File(name)); // May throw but never return a null value } @@ -64,8 +65,8 @@ public Reader getTemplateReader(String name) { } /** - * Get the template file path with template dir prepended, and use the - * library template if exists. + * Get the template file path with template dir prepended, and use the library template if + * exists. * * @param config Codegen config * @param templateFile Template file @@ -78,9 +79,9 @@ public String getFullTemplateFile(CodegenConfig config, String templateFile) { } else { String library = config.getLibrary(); if (library != null && !"".equals(library)) { - String libTemplateFile = config.embeddedTemplateDir() + File.separator + - "libraries" + File.separator + library + File.separator + - templateFile; + String libTemplateFile = + config.embeddedTemplateDir() + File.separator + "libraries" + + File.separator + library + File.separator + templateFile; if (embeddedTemplateExists(libTemplateFile)) { // Fall back to the template file embedded/packaged in the JAR file... return libTemplateFile; @@ -93,7 +94,9 @@ public String getFullTemplateFile(CodegenConfig config, String templateFile) { public String readResourceContents(String resourceFilePath) { StringBuilder sb = new StringBuilder(); - Scanner scanner = new Scanner(this.getClass().getResourceAsStream(getCPResourcePath(resourceFilePath)), "UTF-8"); + Scanner scanner = + new Scanner(this.getClass() + .getResourceAsStream(getCPResourcePath(resourceFilePath)), "UTF-8"); while (scanner.hasNextLine()) { String line = scanner.nextLine(); sb.append(line).append('\n'); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CliOption.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CliOption.java index aacae1808e0..8d18af3c40c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CliOption.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CliOption.java @@ -80,7 +80,8 @@ public void setEnum(Map enumValues) { } public static CliOption newBoolean(String opt, String description) { - return new CliOption(opt, description, BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString()); + return new CliOption(opt, description, BooleanProperty.TYPE).defaultValue(Boolean.FALSE + .toString()); } public static CliOption newString(String opt, String description) { @@ -90,7 +91,7 @@ public static CliOption newString(String opt, String description) { @JsonIgnore public String getOptionHelp() { StringBuilder sb = new StringBuilder(description); - if(defaultValue != null) { + if (defaultValue != null) { sb.append(" (Default: ").append(defaultValue).append(")"); } if (enumValues != null) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java index 57918dd9b35..5d1d7ef0913 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java @@ -73,4 +73,4 @@ public Swagger getSwagger() { public void setSwagger(Swagger swagger) { this.swagger = swagger; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOpts.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOpts.java index 172a057ea43..022a814ece5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOpts.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOpts.java @@ -57,8 +57,10 @@ public String toString() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; ClientOpts that = (ClientOpts) o; @@ -70,7 +72,8 @@ public boolean equals(Object o) { return false; if (properties != null ? !properties.equals(that.properties) : that.properties != null) return false; - return outputDirectory != null ? outputDirectory.equals(that.outputDirectory) : that.outputDirectory == null; + return outputDirectory != null ? outputDirectory.equals(that.outputDirectory) + : that.outputDirectory == null; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java index 839f0800e15..19fc8f3e828 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java @@ -20,8 +20,8 @@ import io.swagger.parser.SwaggerParser; /** - * @deprecated use instead {@link io.swagger.codegen.DefaultGenerator} - * or cli interface from https://github.com/swagger-api/swagger-codegen/pull/547 + * @deprecated use instead {@link io.swagger.codegen.DefaultGenerator} or cli interface from + * https://github.com/swagger-api/swagger-codegen/pull/547 */ @Deprecated public class Codegen extends DefaultGenerator { @@ -30,23 +30,30 @@ public class Codegen extends DefaultGenerator { static Map configs = new HashMap(); static String configString; - static String debugInfoOptions = "\nThe following additional debug options are available for all codegen targets:" + - "\n -DdebugSwagger prints the swagger specification as interpreted by the codegen" + - "\n -DdebugModels prints models passed to the template engine" + - "\n -DdebugOperations prints operations passed to the template engine" + - "\n -DdebugSupportingFiles prints additional data passed to the template engine"; + static String debugInfoOptions = + "\nThe following additional debug options are available for all codegen targets:" + + "\n -DdebugSwagger prints the swagger specification as interpreted by the codegen" + + "\n -DdebugModels prints models passed to the template engine" + + "\n -DdebugOperations prints operations passed to the template engine" + + "\n -DdebugSupportingFiles prints additional data passed to the template engine"; @SuppressWarnings("deprecation") public static void main(String[] args) { Options options = new Options(); options.addOption("h", "help", false, "shows this message"); - options.addOption("l", "lang", true, "client language to generate.\nAvailable languages include:\n\t[" + configString + "]"); + options.addOption("l", "lang", true, + "client language to generate.\nAvailable languages include:\n\t[" + configString + + "]"); options.addOption("o", "output", true, "where to write the generated files"); options.addOption("i", "input-spec", true, "location of the swagger spec, as URL or file"); options.addOption("t", "template-dir", true, "folder containing the template files"); options.addOption("d", "debug-info", false, "prints additional info for debugging"); - options.addOption("a", "auth", true, "adds authorization headers when fetching the swagger definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values"); + options.addOption( + "a", + "auth", + true, + "adds authorization headers when fetching the swagger definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values"); options.addOption("c", "config", true, "location of the configuration file"); ClientOptInput clientOptInput = new ClientOptInput(); @@ -89,7 +96,9 @@ public static void main(String[] args) { return; } if (cmd.hasOption("i")) { - swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true); + swagger = + new SwaggerParser().read(cmd.getOptionValue("i"), + clientOptInput.getAuthorizationValues(), true); } if (cmd.hasOption("c")) { String configFile = cmd.getOptionValue("c"); @@ -98,22 +107,22 @@ public static void main(String[] args) { if (null != genConfig && null != config) { for (CliOption langCliOption : config.cliOptions()) { if (genConfig.hasOption(langCliOption.getOpt())) { - config.additionalProperties().put(langCliOption.getOpt(), genConfig.getOption(langCliOption.getOpt())); + config.additionalProperties().put(langCliOption.getOpt(), + genConfig.getOption(langCliOption.getOpt())); } } } } if (cmd.hasOption("t")) { - clientOpts.getProperties().put(CodegenConstants.TEMPLATE_DIR, String.valueOf(cmd.getOptionValue("t"))); + clientOpts.getProperties().put(CodegenConstants.TEMPLATE_DIR, + String.valueOf(cmd.getOptionValue("t"))); } } catch (Exception e) { usage(options); return; } try { - clientOptInput - .opts(clientOpts) - .swagger(swagger); + clientOptInput.opts(clientOpts).swagger(swagger); new Codegen().opts(clientOptInput).generate(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java index 4ffb9558230..a03b9ffb96e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -14,13 +14,13 @@ public interface CodegenConfig { CodegenType getTag(); - + String getName(); String getHelp(); Map additionalProperties(); - + Map vendorExtensions(); String testPackage(); @@ -91,9 +91,11 @@ public interface CodegenConfig { CodegenModel fromModel(String name, Model model, Map allDefinitions); - CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions, Swagger swagger); - - CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions); + CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, + Map definitions, Swagger swagger); + + CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, + Map definitions); List fromSecurity(Map schemes); @@ -118,7 +120,7 @@ public interface CodegenConfig { Map modelDocTemplateFiles(); Set languageSpecificPrimitives(); - + Map reservedWordsMappings(); void preprocessSwagger(Swagger swagger); @@ -136,19 +138,20 @@ public interface CodegenConfig { String toApiTestFilename(String name); String toModelTestFilename(String name); - + String toApiDocFilename(String name); String toModelDocFilename(String name); - + String toModelImport(String name); String toApiImport(String name); - void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations); + void addOperationToGroup(String tag, String resourcePath, Operation operation, + CodegenOperation co, Map> operations); Map postProcessAllModels(Map objs); - + Map postProcessModels(Map objs); Map postProcessOperations(Map objs); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfigLoader.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfigLoader.java index 45a57e7bb3a..c77d5a483ba 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfigLoader.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfigLoader.java @@ -28,7 +28,8 @@ public static CodegenConfig forName(String name) { try { return (CodegenConfig) Class.forName(name).newInstance(); } catch (Exception e) { - throw new RuntimeException("Can't load config class with name ".concat(name) + " Available: " + availableConfigs.toString(), e); + throw new RuntimeException("Can't load config class with name ".concat(name) + + " Available: " + availableConfigs.toString(), e); } } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index 30707bce341..9754c8240f9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -13,7 +13,8 @@ public class CodegenConstants { public static final String TEMPLATE_DIR = "templateDir"; public static final String ALLOW_UNICODE_IDENTIFIERS = "allowUnicodeIdentifiers"; - public static final String ALLOW_UNICODE_IDENTIFIERS_DESC = "boolean, toggles whether unicode identifiers are allowed in names or not, default is false"; + public static final String ALLOW_UNICODE_IDENTIFIERS_DESC = + "boolean, toggles whether unicode identifiers are allowed in names or not, default is false"; public static final String INVOKER_PACKAGE = "invokerPackage"; public static final String INVOKER_PACKAGE_DESC = "root package for generated code"; @@ -40,13 +41,15 @@ public class CodegenConstants { public static final String ARTIFACT_URL_DESC = "artifact URL in generated pom.xml"; public static final String ARTIFACT_DESCRIPTION = "artifactDescription"; - public static final String ARTIFACT_DESCRIPTION_DESC = "artifact description in generated pom.xml"; + public static final String ARTIFACT_DESCRIPTION_DESC = + "artifact description in generated pom.xml"; public static final String SCM_CONNECTION = "scmConnection"; public static final String SCM_CONNECTION_DESC = "SCM connection in generated pom.xml"; public static final String SCM_DEVELOPER_CONNECTION = "scmDeveloperConnection"; - public static final String SCM_DEVELOPER_CONNECTION_DESC = "SCM developer connection in generated pom.xml"; + public static final String SCM_DEVELOPER_CONNECTION_DESC = + "SCM developer connection in generated pom.xml"; public static final String SCM_URL = "scmUrl"; public static final String SCM_URL_DESC = "SCM URL in generated pom.xml"; @@ -58,10 +61,12 @@ public class CodegenConstants { public static final String DEVELOPER_EMAIL_DESC = "developer email in generated pom.xml"; public static final String DEVELOPER_ORGANIZATION = "developerOrganization"; - public static final String DEVELOPER_ORGANIZATION_DESC = "developer organization in generated pom.xml"; + public static final String DEVELOPER_ORGANIZATION_DESC = + "developer organization in generated pom.xml"; public static final String DEVELOPER_ORGANIZATION_URL = "developerOrganizationUrl"; - public static final String DEVELOPER_ORGANIZATION_URL_DESC = "developer organization URL in generated pom.xml"; + public static final String DEVELOPER_ORGANIZATION_URL_DESC = + "developer organization URL in generated pom.xml"; public static final String LICENSE_NAME = "licenseName"; public static final String LICENSE_NAME_DESC = "The name of the license"; @@ -76,79 +81,101 @@ public class CodegenConstants { public static final String IMPL_FOLDER_DESC = "folder for generated implementation code"; public static final String LOCAL_VARIABLE_PREFIX = "localVariablePrefix"; - public static final String LOCAL_VARIABLE_PREFIX_DESC = "prefix for generated code members and local variables"; + public static final String LOCAL_VARIABLE_PREFIX_DESC = + "prefix for generated code members and local variables"; public static final String SERIALIZABLE_MODEL = "serializableModel"; - public static final String SERIALIZABLE_MODEL_DESC = "boolean - toggle \"implements Serializable\" for generated models"; + public static final String SERIALIZABLE_MODEL_DESC = + "boolean - toggle \"implements Serializable\" for generated models"; public static final String SERIALIZE_BIG_DECIMAL_AS_STRING = "bigDecimalAsString"; - public static final String SERIALIZE_BIG_DECIMAL_AS_STRING_DESC = "Treat BigDecimal values as Strings to avoid precision loss."; + public static final String SERIALIZE_BIG_DECIMAL_AS_STRING_DESC = + "Treat BigDecimal values as Strings to avoid precision loss."; public static final String LIBRARY = "library"; public static final String LIBRARY_DESC = "library template (sub-template)"; public static final String SORT_PARAMS_BY_REQUIRED_FLAG = "sortParamsByRequiredFlag"; - public static final String SORT_PARAMS_BY_REQUIRED_FLAG_DESC = "Sort method arguments to place required parameters before optional parameters."; + public static final String SORT_PARAMS_BY_REQUIRED_FLAG_DESC = + "Sort method arguments to place required parameters before optional parameters."; public static final String USE_DATETIME_OFFSET = "useDateTimeOffset"; - public static final String USE_DATETIME_OFFSET_DESC = "Use DateTimeOffset to model date-time properties"; + public static final String USE_DATETIME_OFFSET_DESC = + "Use DateTimeOffset to model date-time properties"; public static final String ENSURE_UNIQUE_PARAMS = "ensureUniqueParams"; - public static final String ENSURE_UNIQUE_PARAMS_DESC = "Whether to ensure parameter names are unique in an operation (rename parameters that are not)."; + public static final String ENSURE_UNIQUE_PARAMS_DESC = + "Whether to ensure parameter names are unique in an operation (rename parameters that are not)."; public static final String PACKAGE_NAME = "packageName"; public static final String PACKAGE_VERSION = "packageVersion"; public static final String PACKAGE_TITLE = "packageTitle"; - public static final String PACKAGE_TITLE_DESC = "Specifies an AssemblyTitle for the .NET Framework global assembly attributes stored in the AssemblyInfo file."; + public static final String PACKAGE_TITLE_DESC = + "Specifies an AssemblyTitle for the .NET Framework global assembly attributes stored in the AssemblyInfo file."; public static final String PACKAGE_PRODUCTNAME = "packageProductName"; - public static final String PACKAGE_PRODUCTNAME_DESC = "Specifies an AssemblyProduct for the .NET Framework global assembly attributes stored in the AssemblyInfo file."; + public static final String PACKAGE_PRODUCTNAME_DESC = + "Specifies an AssemblyProduct for the .NET Framework global assembly attributes stored in the AssemblyInfo file."; public static final String PACKAGE_DESCRIPTION = "packageDescription"; - public static final String PACKAGE_DESCRIPTION_DESC = "Specifies a AssemblyDescription for the .NET Framework global assembly attributes stored in the AssemblyInfo file."; + public static final String PACKAGE_DESCRIPTION_DESC = + "Specifies a AssemblyDescription for the .NET Framework global assembly attributes stored in the AssemblyInfo file."; public static final String PACKAGE_COMPANY = "packageCompany"; - public static final String PACKAGE_COMPANY_DESC = "Specifies an AssemblyCompany for the .NET Framework global assembly attributes stored in the AssemblyInfo file."; + public static final String PACKAGE_COMPANY_DESC = + "Specifies an AssemblyCompany for the .NET Framework global assembly attributes stored in the AssemblyInfo file."; public static final String PACKAGE_COPYRIGHT = "packageCopyright"; - public static final String PACKAGE_COPYRIGHT_DESC = "Specifies an AssemblyCopyright for the .NET Framework global assembly attributes stored in the AssemblyInfo file."; + public static final String PACKAGE_COPYRIGHT_DESC = + "Specifies an AssemblyCopyright for the .NET Framework global assembly attributes stored in the AssemblyInfo file."; public static final String POD_VERSION = "podVersion"; public static final String OPTIONAL_METHOD_ARGUMENT = "optionalMethodArgument"; - public static final String OPTIONAL_METHOD_ARGUMENT_DESC = "Optional method argument, e.g. void square(int x=10) (.net 4.0+ only)."; + public static final String OPTIONAL_METHOD_ARGUMENT_DESC = + "Optional method argument, e.g. void square(int x=10) (.net 4.0+ only)."; public static final String OPTIONAL_ASSEMBLY_INFO = "optionalAssemblyInfo"; public static final String OPTIONAL_ASSEMBLY_INFO_DESC = "Generate AssemblyInfo.cs."; public static final String USE_COLLECTION = "useCollection"; - public static final String USE_COLLECTION_DESC = "Deserialize array types to Collection instead of List."; + public static final String USE_COLLECTION_DESC = + "Deserialize array types to Collection instead of List."; public static final String INTERFACE_PREFIX = "interfacePrefix"; - public static final String INTERFACE_PREFIX_DESC = "Prefix interfaces with a community standard or widely accepted prefix."; + public static final String INTERFACE_PREFIX_DESC = + "Prefix interfaces with a community standard or widely accepted prefix."; public static final String RETURN_ICOLLECTION = "returnICollection"; - public static final String RETURN_ICOLLECTION_DESC = "Return ICollection instead of the concrete type."; + public static final String RETURN_ICOLLECTION_DESC = + "Return ICollection instead of the concrete type."; public static final String OPTIONAL_PROJECT_FILE = "optionalProjectFile"; public static final String OPTIONAL_PROJECT_FILE_DESC = "Generate {PackageName}.csproj."; public static final String OPTIONAL_PROJECT_GUID = "packageGuid"; - public static final String OPTIONAL_PROJECT_GUID_DESC = "The GUID that will be associated with the C# project"; + public static final String OPTIONAL_PROJECT_GUID_DESC = + "The GUID that will be associated with the C# project"; public static final String MODEL_PROPERTY_NAMING = "modelPropertyNaming"; - public static final String MODEL_PROPERTY_NAMING_DESC = "Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name"; + public static final String MODEL_PROPERTY_NAMING_DESC = + "Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name"; public static final String DOTNET_FRAMEWORK = "targetFramework"; public static final String DOTNET_FRAMEWORK_DESC = "The target .NET framework version."; - public static enum MODEL_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case, original} + public static enum MODEL_PROPERTY_NAMING_TYPE { + camelCase, PascalCase, snake_case, original + } public static final String MODEL_NAME_PREFIX = "modelNamePrefix"; - public static final String MODEL_NAME_PREFIX_DESC = "Prefix that will be prepended to all model names. Default is the empty string."; + public static final String MODEL_NAME_PREFIX_DESC = + "Prefix that will be prepended to all model names. Default is the empty string."; public static final String MODEL_NAME_SUFFIX = "modelNameSuffix"; - public static final String MODEL_NAME_SUFFIX_DESC = "Suffix that will be appended to all model names. Default is the empty string."; + public static final String MODEL_NAME_SUFFIX_DESC = + "Suffix that will be appended to all model names. Default is the empty string."; public static final String OPTIONAL_EMIT_DEFAULT_VALUES = "optionalEmitDefaultValues"; - public static final String OPTIONAL_EMIT_DEFAULT_VALUES_DESC = "Set DataMember's EmitDefaultValue."; + public static final String OPTIONAL_EMIT_DEFAULT_VALUES_DESC = + "Set DataMember's EmitDefaultValue."; public static final String GIT_USER_ID = "gitUserId"; public static final String GIT_USER_ID_DESC = "Git user ID, e.g. swagger-api."; @@ -160,7 +187,8 @@ public static enum MODEL_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case public static final String RELEASE_NOTE_DESC = "Release note, default to 'Minor update'."; public static final String HTTP_USER_AGENT = "httpUserAgent"; - public static final String HTTP_USER_AGENT_DESC = "HTTP user agent, e.g. codegen_csharp_api_client, default to 'Swagger-Codegen/{packageVersion}}/{language}'"; + public static final String HTTP_USER_AGENT_DESC = + "HTTP user agent, e.g. codegen_csharp_api_client, default to 'Swagger-Codegen/{packageVersion}}/{language}'"; public static final String SUPPORTS_ES6 = "supportsES6"; public static final String SUPPORTS_ES6_DESC = "Generate code that conforms to ES6."; @@ -169,21 +197,27 @@ public static enum MODEL_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case public static final String EXCLUDE_TESTS_DESC = "Specifies that no tests are to be generated."; public static final String GENERATE_API_TESTS = "generateApiTests"; - public static final String GENERATE_API_TESTS_DESC = "Specifies that api tests are to be generated."; + public static final String GENERATE_API_TESTS_DESC = + "Specifies that api tests are to be generated."; public static final String GENERATE_MODEL_TESTS = "generateModelTests"; - public static final String GENERATE_MODEL_TESTS_DESC = "Specifies that model tests are to be generated."; + public static final String GENERATE_MODEL_TESTS_DESC = + "Specifies that model tests are to be generated."; public static final String HIDE_GENERATION_TIMESTAMP = "hideGenerationTimestamp"; - public static final String HIDE_GENERATION_TIMESTAMP_DESC = "Hides the generation timestamp when files are generated."; + public static final String HIDE_GENERATION_TIMESTAMP_DESC = + "Hides the generation timestamp when files are generated."; public static final String GENERATE_PROPERTY_CHANGED = "generatePropertyChanged"; - public static final String GENERATE_PROPERTY_CHANGED_DESC = "Specifies that models support raising property changed events."; + public static final String GENERATE_PROPERTY_CHANGED_DESC = + "Specifies that models support raising property changed events."; public static final String NON_PUBLIC_API = "nonPublicApi"; - public static final String NON_PUBLIC_API_DESC = "Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers."; + public static final String NON_PUBLIC_API_DESC = + "Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers."; public static final String IGNORE_FILE_OVERRIDE = "ignoreFileOverride"; - public static final String IGNORE_FILE_OVERRIDE_DESC = "Specifies an override location for the .swagger-codegen-ignore file. Most useful on initial generation."; + public static final String IGNORE_FILE_OVERRIDE_DESC = + "Specifies an override location for the .swagger-codegen-ignore file. Most useful on initial generation."; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java index 7f89ef738a0..8dff0106d8a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java @@ -14,7 +14,8 @@ public class CodegenModel { public String parent, parentSchema; public List interfaces; - // References to parent and interface CodegenModels. Only set when code generator supports inheritance. + // References to parent and interface CodegenModels. Only set when code generator supports + // inheritance. public CodegenModel parentModel; public List interfaceModels; public List children; @@ -26,10 +27,18 @@ public class CodegenModel { public String defaultValue; public String arrayModelType; public List vars = new ArrayList(); - public List requiredVars = new ArrayList(); // a list of required properties - public List optionalVars = new ArrayList(); // a list of optional properties - public List readOnlyVars = new ArrayList(); // a list of read-only properties - public List readWriteVars = new ArrayList(); // a list of properties for read, write + public List requiredVars = new ArrayList(); // a list of + // required + // properties + public List optionalVars = new ArrayList(); // a list of + // optional + // properties + public List readOnlyVars = new ArrayList(); // a list of + // read-only + // properties + public List readWriteVars = new ArrayList(); // a list of + // properties for + // read, write public List allVars; public List parentVars = new ArrayList<>(); public Map allowableValues; @@ -39,17 +48,19 @@ public class CodegenModel { public Set allMandatory; public Set imports = new TreeSet(); - public boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, isArrayModel, hasChildren; + public boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, isArrayModel, + hasChildren; public boolean hasOnlyReadOnly = true; // true if all properties are read-only public ExternalDocs externalDocs; public Map vendorExtensions; - //The type of the value from additional properties. Used in map like objects. + // The type of the value from additional properties. Used in map like objects. public String additionalPropertiesType; { - // By default these are the same collections. Where the code generator supports inheritance, composed models + // By default these are the same collections. Where the code generator supports inheritance, + // composed models // store the complete closure of owned and inherited properties in allVars and allMandatory. allVars = vars; allMandatory = mandatory; @@ -62,20 +73,24 @@ public String toString() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; CodegenModel that = (CodegenModel) o; if (parent != null ? !parent.equals(that.parent) : that.parent != null) return false; - if (parentSchema != null ? !parentSchema.equals(that.parentSchema) : that.parentSchema != null) + if (parentSchema != null ? !parentSchema.equals(that.parentSchema) + : that.parentSchema != null) return false; if (interfaces != null ? !interfaces.equals(that.interfaces) : that.interfaces != null) return false; if (parentModel != null ? !parentModel.equals(that.parentModel) : that.parentModel != null) return false; - if (interfaceModels != null ? !interfaceModels.equals(that.interfaceModels) : that.interfaceModels != null) + if (interfaceModels != null ? !interfaceModels.equals(that.interfaceModels) + : that.interfaceModels != null) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; @@ -85,33 +100,42 @@ public boolean equals(Object o) { return false; if (description != null ? !description.equals(that.description) : that.description != null) return false; - if (classVarName != null ? !classVarName.equals(that.classVarName) : that.classVarName != null) + if (classVarName != null ? !classVarName.equals(that.classVarName) + : that.classVarName != null) return false; if (modelJson != null ? !modelJson.equals(that.modelJson) : that.modelJson != null) return false; if (dataType != null ? !dataType.equals(that.dataType) : that.dataType != null) return false; - if (classFilename != null ? !classFilename.equals(that.classFilename) : that.classFilename != null) + if (classFilename != null ? !classFilename.equals(that.classFilename) + : that.classFilename != null) return false; - if (unescapedDescription != null ? !unescapedDescription.equals(that.unescapedDescription) : that.unescapedDescription != null) + if (unescapedDescription != null ? !unescapedDescription.equals(that.unescapedDescription) + : that.unescapedDescription != null) return false; - if (discriminator != null ? !discriminator.equals(that.discriminator) : that.discriminator != null) + if (discriminator != null ? !discriminator.equals(that.discriminator) + : that.discriminator != null) return false; - if (defaultValue != null ? !defaultValue.equals(that.defaultValue) : that.defaultValue != null) + if (defaultValue != null ? !defaultValue.equals(that.defaultValue) + : that.defaultValue != null) return false; if (vars != null ? !vars.equals(that.vars) : that.vars != null) return false; - if (requiredVars != null ? !requiredVars.equals(that.requiredVars) : that.requiredVars != null) + if (requiredVars != null ? !requiredVars.equals(that.requiredVars) + : that.requiredVars != null) return false; - if (optionalVars != null ? !optionalVars.equals(that.optionalVars) : that.optionalVars != null) + if (optionalVars != null ? !optionalVars.equals(that.optionalVars) + : that.optionalVars != null) return false; if (allVars != null ? !allVars.equals(that.allVars) : that.allVars != null) return false; - if (allowableValues != null ? !allowableValues.equals(that.allowableValues) : that.allowableValues != null) + if (allowableValues != null ? !allowableValues.equals(that.allowableValues) + : that.allowableValues != null) return false; if (mandatory != null ? !mandatory.equals(that.mandatory) : that.mandatory != null) return false; - if (allMandatory != null ? !allMandatory.equals(that.allMandatory) : that.allMandatory != null) + if (allMandatory != null ? !allMandatory.equals(that.allMandatory) + : that.allMandatory != null) return false; if (imports != null ? !imports.equals(that.imports) : that.imports != null) return false; @@ -125,7 +149,8 @@ public boolean equals(Object o) { return false; if (isEnum != that.isEnum) return false; - if (externalDocs != null ? !externalDocs.equals(that.externalDocs) : that.externalDocs != null) + if (externalDocs != null ? !externalDocs.equals(that.externalDocs) + : that.externalDocs != null) return false; if (!Objects.equals(hasOnlyReadOnly, that.hasOnlyReadOnly)) return false; @@ -133,7 +158,8 @@ public boolean equals(Object o) { return false; if (!Objects.equals(parentVars, that.parentVars)) return false; - return vendorExtensions != null ? vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions == null; + return vendorExtensions != null ? vendorExtensions.equals(that.vendorExtensions) + : that.vendorExtensions == null; } @@ -163,11 +189,11 @@ public int hashCode() { result = 31 * result + (mandatory != null ? mandatory.hashCode() : 0); result = 31 * result + (allMandatory != null ? allMandatory.hashCode() : 0); result = 31 * result + (imports != null ? imports.hashCode() : 0); - result = 31 * result + (hasVars ? 13:31); - result = 31 * result + (emptyVars ? 13:31); - result = 31 * result + (hasMoreModels ? 13:31); - result = 31 * result + (hasEnums ? 13:31); - result = 31 * result + (isEnum ? 13:31); + result = 31 * result + (hasVars ? 13 : 31); + result = 31 * result + (emptyVars ? 13 : 31); + result = 31 * result + (hasMoreModels ? 13 : 31); + result = 31 * result + (hasEnums ? 13 : 31); + result = 31 * result + (isEnum ? 13 : 31); result = 31 * result + (externalDocs != null ? externalDocs.hashCode() : 0); result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0); result = 31 * result + Objects.hash(hasOnlyReadOnly); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java index d0a93731a30..f1659f0e232 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java @@ -5,17 +5,20 @@ public final class CodegenModelFactory { - private static final Map> typeMapping = new HashMap>(); + private static final Map> typeMapping = + new HashMap>(); /** * Configure a different implementation class. * - * @param type the type that shall be replaced - * @param implementation the implementation class must extend the default class and must provide a public no-arg constructor + * @param type the type that shall be replaced + * @param implementation the implementation class must extend the default class and must provide + * a public no-arg constructor */ public static void setTypeMapping(CodegenModelType type, Class implementation) { if (!type.getDefaultImplementation().isAssignableFrom(implementation)) { - throw new IllegalArgumentException(implementation.getSimpleName() + " doesn't extend " + type.getDefaultImplementation().getSimpleName()); + throw new IllegalArgumentException(implementation.getSimpleName() + " doesn't extend " + + type.getDefaultImplementation().getSimpleName()); } try { implementation.newInstance(); @@ -29,7 +32,8 @@ public static void setTypeMapping(CodegenModelType type, Class implementation public static T newInstance(CodegenModelType type) { Class classType = typeMapping.get(type); try { - return (T) (classType != null ? classType : type.getDefaultImplementation()).newInstance(); + return (T) (classType != null ? classType : type.getDefaultImplementation()) + .newInstance(); } catch (IllegalAccessException | InstantiationException e) { throw new RuntimeException(e); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelType.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelType.java index dce8ab0e2e5..fa511db91a1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelType.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelType.java @@ -2,12 +2,8 @@ public enum CodegenModelType { - MODEL(CodegenModel.class), - OPERATION(CodegenOperation.class), - PARAMETER(CodegenParameter.class), - PROPERTY(CodegenProperty.class), - RESPONSE(CodegenResponse.class), - SECURITY(CodegenSecurity.class); + MODEL(CodegenModel.class), OPERATION(CodegenOperation.class), PARAMETER(CodegenParameter.class), PROPERTY( + CodegenProperty.class), RESPONSE(CodegenResponse.class), SECURITY(CodegenSecurity.class); private final Class defaultImplementation; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index fc07e0d7174..29f8b4ff8f7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -13,12 +13,11 @@ public class CodegenOperation { public final List responseHeaders = new ArrayList(); public boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams, returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer, - isListContainer, isMultipart, hasMore = true, - isResponseBinary = false, isResponseFile = false, hasReference = false, - isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy, - isRestful; - public String path, operationId, returnType, httpMethod, returnBaseType, - returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse, discriminator; + isListContainer, isMultipart, hasMore = true, isResponseBinary = false, + isResponseFile = false, hasReference = false, isRestfulIndex, isRestfulShow, + isRestfulCreate, isRestfulUpdate, isRestfulDestroy, isRestful; + public String path, operationId, returnType, httpMethod, returnBaseType, returnContainer, + summary, unescapedNotes, notes, baseName, defaultResponse, discriminator; public List> consumes, produces, prioritizedContentTypes; public CodegenParameter bodyParam; public List allParams = new ArrayList(); @@ -45,7 +44,7 @@ public class CodegenOperation { private static boolean nonempty(List params) { return params != null && params.size() > 0; } - + /** * Check if there's at least one body parameter * @@ -151,7 +150,8 @@ public boolean isRestfulDestroy() { * @return true if Restful-style, false otherwise */ public boolean isRestful() { - return isRestfulIndex() || isRestfulShow() || isRestfulCreate() || isRestfulUpdate() || isRestfulDestroy(); + return isRestfulIndex() || isRestfulShow() || isRestfulCreate() || isRestfulUpdate() + || isRestfulDestroy(); } /** @@ -169,7 +169,8 @@ private String pathWithoutBaseName() { * @return true if path act as member */ private boolean isMemberPath() { - if (pathParams.size() != 1) return false; + if (pathParams.size() != 1) + return false; String id = pathParams.get(0).baseName; return ("/{" + id + "}").equals(pathWithoutBaseName()); @@ -182,12 +183,15 @@ public String toString() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; CodegenOperation that = (CodegenOperation) o; - if (responseHeaders != null ? !responseHeaders.equals(that.responseHeaders) : that.responseHeaders != null) + if (responseHeaders != null ? !responseHeaders.equals(that.responseHeaders) + : that.responseHeaders != null) return false; if (hasAuthMethods != that.hasAuthMethods) return false; @@ -227,21 +231,26 @@ public boolean equals(Object o) { return false; if (httpMethod != null ? !httpMethod.equals(that.httpMethod) : that.httpMethod != null) return false; - if (returnBaseType != null ? !returnBaseType.equals(that.returnBaseType) : that.returnBaseType != null) + if (returnBaseType != null ? !returnBaseType.equals(that.returnBaseType) + : that.returnBaseType != null) return false; - if (returnContainer != null ? !returnContainer.equals(that.returnContainer) : that.returnContainer != null) + if (returnContainer != null ? !returnContainer.equals(that.returnContainer) + : that.returnContainer != null) return false; if (summary != null ? !summary.equals(that.summary) : that.summary != null) return false; - if (unescapedNotes != null ? !unescapedNotes.equals(that.unescapedNotes) : that.unescapedNotes != null) + if (unescapedNotes != null ? !unescapedNotes.equals(that.unescapedNotes) + : that.unescapedNotes != null) return false; if (notes != null ? !notes.equals(that.notes) : that.notes != null) return false; if (baseName != null ? !baseName.equals(that.baseName) : that.baseName != null) return false; - if (defaultResponse != null ? !defaultResponse.equals(that.defaultResponse) : that.defaultResponse != null) + if (defaultResponse != null ? !defaultResponse.equals(that.defaultResponse) + : that.defaultResponse != null) return false; - if (discriminator != null ? !discriminator.equals(that.discriminator) : that.discriminator != null) + if (discriminator != null ? !discriminator.equals(that.discriminator) + : that.discriminator != null) return false; if (consumes != null ? !consumes.equals(that.consumes) : that.consumes != null) return false; @@ -257,7 +266,8 @@ public boolean equals(Object o) { return false; if (queryParams != null ? !queryParams.equals(that.queryParams) : that.queryParams != null) return false; - if (headerParams != null ? !headerParams.equals(that.headerParams) : that.headerParams != null) + if (headerParams != null ? !headerParams.equals(that.headerParams) + : that.headerParams != null) return false; if (formParams != null ? !formParams.equals(that.formParams) : that.formParams != null) return false; @@ -271,36 +281,40 @@ public boolean equals(Object o) { return false; if (examples != null ? !examples.equals(that.examples) : that.examples != null) return false; - if (externalDocs != null ? !externalDocs.equals(that.externalDocs) : that.externalDocs != null) + if (externalDocs != null ? !externalDocs.equals(that.externalDocs) + : that.externalDocs != null) return false; - if (vendorExtensions != null ? !vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions != null) + if (vendorExtensions != null ? !vendorExtensions.equals(that.vendorExtensions) + : that.vendorExtensions != null) return false; if (nickname != null ? !nickname.equals(that.nickname) : that.nickname != null) return false; - if ( prioritizedContentTypes != null ? !prioritizedContentTypes.equals(that.prioritizedContentTypes) : that.prioritizedContentTypes != null ) + if (prioritizedContentTypes != null ? !prioritizedContentTypes + .equals(that.prioritizedContentTypes) : that.prioritizedContentTypes != null) return false; - return operationIdLowerCase != null ? operationIdLowerCase.equals(that.operationIdLowerCase) : that.operationIdLowerCase == null; + return operationIdLowerCase != null ? operationIdLowerCase + .equals(that.operationIdLowerCase) : that.operationIdLowerCase == null; } @Override public int hashCode() { int result = responseHeaders.hashCode(); - result = 31 * result + (hasAuthMethods ? 13:31); - result = 31 * result + (hasConsumes ? 13:31); - result = 31 * result + (hasProduces ? 13:31); - result = 31 * result + (hasParams ? 13:31); - result = 31 * result + (hasOptionalParams ? 13:31); - result = 31 * result + (returnTypeIsPrimitive ? 13:31); - result = 31 * result + (returnSimpleType ? 13:31); - result = 31 * result + (subresourceOperation ? 13:31); - result = 31 * result + (isMapContainer ? 13:31); - result = 31 * result + (isListContainer ? 13:31); - result = 31 * result + (isMultipart ? 13:31); - result = 31 * result + (hasMore ? 13:31); - result = 31 * result + (isResponseBinary ? 13:31); - result = 31 * result + (isResponseFile ? 13:31); - result = 31 * result + (hasReference ? 13:31); + result = 31 * result + (hasAuthMethods ? 13 : 31); + result = 31 * result + (hasConsumes ? 13 : 31); + result = 31 * result + (hasProduces ? 13 : 31); + result = 31 * result + (hasParams ? 13 : 31); + result = 31 * result + (hasOptionalParams ? 13 : 31); + result = 31 * result + (returnTypeIsPrimitive ? 13 : 31); + result = 31 * result + (returnSimpleType ? 13 : 31); + result = 31 * result + (subresourceOperation ? 13 : 31); + result = 31 * result + (isMapContainer ? 13 : 31); + result = 31 * result + (isListContainer ? 13 : 31); + result = 31 * result + (isMultipart ? 13 : 31); + result = 31 * result + (hasMore ? 13 : 31); + result = 31 * result + (isResponseBinary ? 13 : 31); + result = 31 * result + (isResponseFile ? 13 : 31); + result = 31 * result + (hasReference ? 13 : 31); result = 31 * result + (path != null ? path.hashCode() : 0); result = 31 * result + (operationId != null ? operationId.hashCode() : 0); result = 31 * result + (returnType != null ? returnType.hashCode() : 0); @@ -330,7 +344,10 @@ public int hashCode() { result = 31 * result + (externalDocs != null ? externalDocs.hashCode() : 0); result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0); result = 31 * result + (nickname != null ? nickname.hashCode() : 0); - result = 31 * result + (prioritizedContentTypes != null ? prioritizedContentTypes.hashCode() : 0); + result = + 31 + * result + + (prioritizedContentTypes != null ? prioritizedContentTypes.hashCode() : 0); result = 31 * result + (operationIdLowerCase != null ? operationIdLowerCase.hashCode() : 0); return result; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java index e30159f9553..c8e5119a91f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java @@ -6,14 +6,15 @@ import java.util.List; public class CodegenParameter { - public boolean isFormParam, isQueryParam, isPathParam, isHeaderParam, - isCookieParam, isBodyParam, hasMore, isContainer, - secondaryParam, isCollectionFormatMulti, isPrimitiveType; - public String baseName, paramName, dataType, datatypeWithEnum, dataFormat, - collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName; + public boolean isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, + isBodyParam, hasMore, isContainer, secondaryParam, isCollectionFormatMulti, + isPrimitiveType; + public String baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, + description, unescapedDescription, baseType, defaultValue, enumName; public String example; // example value (x-example) public String jsonSchema; - public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime; + public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, + isBoolean, isDate, isDateTime; public boolean isListContainer, isMapContainer; public boolean isFile, notFile; public boolean isEnum; @@ -24,57 +25,57 @@ public class CodegenParameter { public boolean hasValidation; /** - * Determines whether this parameter is mandatory. If the parameter is in "path", - * this property is required and its value MUST be true. Otherwise, the property - * MAY be included and its default value is false. + * Determines whether this parameter is mandatory. If the parameter is in "path", this property + * is required and its value MUST be true. Otherwise, the property MAY be included and its + * default value is false. */ public boolean required; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor17. - */ + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor17. + */ public String maximum; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor17 - */ + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor17 + */ public boolean exclusiveMaximum; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor21 - */ + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor21 + */ public String minimum; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor21 - */ + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor21 + */ public boolean exclusiveMinimum; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor26 - */ + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor26 + */ public Integer maxLength; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor29 - */ + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor29 + */ public Integer minLength; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor33 - */ + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor33 + */ public String pattern; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor42 - */ + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor42 + */ public Integer maxItems; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor45 - */ + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor45 + */ public Integer minItems; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor49 - */ + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor49 + */ public boolean uniqueItems; - /** - * See http://json-schema.org/latest/json-schema-validation.html#anchor14 - */ + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor14 + */ public Number multipleOf; - + public CodegenParameter copy() { CodegenParameter output = new CodegenParameter(); output.isFile = this.isFile; @@ -124,7 +125,7 @@ public CodegenParameter copy() { if (this.items != null) { output.items = this.items; } - if(this.vendorExtensions != null){ + if (this.vendorExtensions != null) { output.vendorExtensions = new HashMap(this.vendorExtensions); } output.hasValidation = this.hasValidation; @@ -151,12 +152,15 @@ public String toString() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; CodegenParameter that = (CodegenParameter) o; - if (isEnum != that.isEnum) return false; + if (isEnum != that.isEnum) + return false; if (isFormParam != that.isFormParam) return false; if (isQueryParam != that.isQueryParam) @@ -185,21 +189,25 @@ public boolean equals(Object o) { return false; if (dataType != null ? !dataType.equals(that.dataType) : that.dataType != null) return false; - if (datatypeWithEnum != null ? !datatypeWithEnum.equals(that.datatypeWithEnum) : that.datatypeWithEnum != null) + if (datatypeWithEnum != null ? !datatypeWithEnum.equals(that.datatypeWithEnum) + : that.datatypeWithEnum != null) return false; if (enumName != null ? !enumName.equals(that.enumName) : that.enumName != null) return false; if (dataFormat != null ? !dataFormat.equals(that.dataFormat) : that.dataFormat != null) return false; - if (collectionFormat != null ? !collectionFormat.equals(that.collectionFormat) : that.collectionFormat != null) + if (collectionFormat != null ? !collectionFormat.equals(that.collectionFormat) + : that.collectionFormat != null) return false; if (description != null ? !description.equals(that.description) : that.description != null) return false; - if (unescapedDescription != null ? !unescapedDescription.equals(that.unescapedDescription) : that.unescapedDescription != null) + if (unescapedDescription != null ? !unescapedDescription.equals(that.unescapedDescription) + : that.unescapedDescription != null) return false; if (baseType != null ? !baseType.equals(that.baseType) : that.baseType != null) return false; - if (defaultValue != null ? !defaultValue.equals(that.defaultValue) : that.defaultValue != null) + if (defaultValue != null ? !defaultValue.equals(that.defaultValue) + : that.defaultValue != null) return false; if (example != null ? !example.equals(that.example) : that.example != null) return false; @@ -235,11 +243,13 @@ public boolean equals(Object o) { return false; if (_enum != null ? !_enum.equals(that._enum) : that._enum != null) return false; - if (allowableValues != null ? !allowableValues.equals(that.allowableValues) : that.allowableValues != null) + if (allowableValues != null ? !allowableValues.equals(that.allowableValues) + : that.allowableValues != null) return false; if (items != null ? !items.equals(that.items) : that.items != null) return false; - if (vendorExtensions != null ? !vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions != null) + if (vendorExtensions != null ? !vendorExtensions.equals(that.vendorExtensions) + : that.vendorExtensions != null) return false; if (hasValidation != that.hasValidation) return false; @@ -271,17 +281,17 @@ public boolean equals(Object o) { @Override public int hashCode() { - int result = isFormParam ? 13:31; - result = 31 * result + (isQueryParam ? 13:31); - result = 31 * result + (isPathParam ? 13:31); - result = 31 * result + (isHeaderParam ? 13:31); - result = 31 * result + (isCookieParam ? 13:31); - result = 31 * result + (isBodyParam ? 13:31); - result = 31 * result + (hasMore ? 13:31); - result = 31 * result + (isContainer ? 13:31); - result = 31 * result + (secondaryParam ? 13:31); - result = 31 * result + (isCollectionFormatMulti ? 13:31); - result = 31 * result + (isPrimitiveType ? 13:31); + int result = isFormParam ? 13 : 31; + result = 31 * result + (isQueryParam ? 13 : 31); + result = 31 * result + (isPathParam ? 13 : 31); + result = 31 * result + (isHeaderParam ? 13 : 31); + result = 31 * result + (isCookieParam ? 13 : 31); + result = 31 * result + (isBodyParam ? 13 : 31); + result = 31 * result + (hasMore ? 13 : 31); + result = 31 * result + (isContainer ? 13 : 31); + result = 31 * result + (secondaryParam ? 13 : 31); + result = 31 * result + (isCollectionFormatMulti ? 13 : 31); + result = 31 * result + (isPrimitiveType ? 13 : 31); result = 31 * result + (baseName != null ? baseName.hashCode() : 0); result = 31 * result + (paramName != null ? paramName.hashCode() : 0); result = 31 * result + (dataType != null ? dataType.hashCode() : 0); @@ -295,39 +305,38 @@ public int hashCode() { result = 31 * result + (defaultValue != null ? defaultValue.hashCode() : 0); result = 31 * result + (example != null ? example.hashCode() : 0); result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0); - result = 31 * result + (isString ? 13:31); - result = 31 * result + (isInteger ? 13:31); - result = 31 * result + (isLong ? 13:31); - result = 31 * result + (isFloat ? 13:31); - result = 31 * result + (isDouble ? 13:31); - result = 31 * result + (isByteArray ? 13:31); - result = 31 * result + (isBinary ? 13:31); - result = 31 * result + (isBoolean ? 13:31); - result = 31 * result + (isDate ? 13:31); - result = 31 * result + (isDateTime ? 13:31); - result = 31 * result + (isListContainer ? 13:31); - result = 31 * result + (isMapContainer ? 13:31); - result = 31 * result + (isFile ? 13:31); - result = 31 * result + (notFile ? 13:31); + result = 31 * result + (isString ? 13 : 31); + result = 31 * result + (isInteger ? 13 : 31); + result = 31 * result + (isLong ? 13 : 31); + result = 31 * result + (isFloat ? 13 : 31); + result = 31 * result + (isDouble ? 13 : 31); + result = 31 * result + (isByteArray ? 13 : 31); + result = 31 * result + (isBinary ? 13 : 31); + result = 31 * result + (isBoolean ? 13 : 31); + result = 31 * result + (isDate ? 13 : 31); + result = 31 * result + (isDateTime ? 13 : 31); + result = 31 * result + (isListContainer ? 13 : 31); + result = 31 * result + (isMapContainer ? 13 : 31); + result = 31 * result + (isFile ? 13 : 31); + result = 31 * result + (notFile ? 13 : 31); result = 31 * result + (isEnum ? 1 : 0); result = 31 * result + (_enum != null ? _enum.hashCode() : 0); result = 31 * result + (allowableValues != null ? allowableValues.hashCode() : 0); result = 31 * result + (items != null ? items.hashCode() : 0); result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0); - result = 31 * result + (hasValidation ? 13:31); - result = 31 * result + (required ? 13:31); + result = 31 * result + (hasValidation ? 13 : 31); + result = 31 * result + (required ? 13 : 31); result = 31 * result + (maximum != null ? maximum.hashCode() : 0); - result = 31 * result + (exclusiveMaximum ? 13:31); + result = 31 * result + (exclusiveMaximum ? 13 : 31); result = 31 * result + (minimum != null ? minimum.hashCode() : 0); - result = 31 * result + (exclusiveMinimum ? 13:31); + result = 31 * result + (exclusiveMinimum ? 13 : 31); result = 31 * result + (maxLength != null ? maxLength.hashCode() : 0); result = 31 * result + (minLength != null ? minLength.hashCode() : 0); result = 31 * result + (pattern != null ? pattern.hashCode() : 0); result = 31 * result + (maxItems != null ? maxItems.hashCode() : 0); result = 31 * result + (minItems != null ? minItems.hashCode() : 0); - result = 31 * result + (uniqueItems ? 13:31); + result = 31 * result + (uniqueItems ? 13 : 31); result = 31 * result + (multipleOf != null ? multipleOf.hashCode() : 0); return result; } } - diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java index de6ebb715f2..97c42658f2d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java @@ -7,23 +7,29 @@ import java.util.Objects; public class CodegenProperty implements Cloneable { - public String baseName, complexType, getter, setter, description, datatype, - datatypeWithEnum, dataFormat, name, min, max, defaultValue, defaultValueWithParam, - baseType, containerType, title; + public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum, + dataFormat, name, min, max, defaultValue, defaultValueWithParam, baseType, + containerType, title; - /** The 'description' string without escape charcters needed by some programming languages/targets */ + /** + * The 'description' string without escape charcters needed by some programming + * languages/targets + */ public String unescapedDescription; /** - * maxLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.1 + * maxLength validation for strings, see + * http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.1 */ public Integer maxLength; /** - * minLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.2 + * minLength validation for strings, see + * http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.2 */ public Integer minLength; /** - * pattern validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.3 + * pattern validation for strings, see + * http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.3 */ public String pattern; /** @@ -37,9 +43,11 @@ public class CodegenProperty implements Cloneable { public boolean exclusiveMinimum; public boolean exclusiveMaximum; public boolean hasMore, required, secondaryParam; - public boolean hasMoreNonReadOnly; // for model constructor, true if next properyt is not readonly + public boolean hasMoreNonReadOnly; // for model constructor, true if next properyt is not + // readonly public boolean isPrimitiveType, isContainer, isNotContainer; - public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isFile, isBoolean, isDate, isDateTime; + public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isFile, + isBoolean, isDate, isDateTime; public boolean isListContainer, isMapContainer; public boolean isEnum; public boolean isReadOnly = false; @@ -47,10 +55,12 @@ public class CodegenProperty implements Cloneable { public Map allowableValues; public CodegenProperty items; public Map vendorExtensions; - public boolean hasValidation; // true if pattern, maximum, etc are set (only used in the mustache template) + public boolean hasValidation; // true if pattern, maximum, etc are set (only used in the + // mustache template) public boolean isInherited; public String nameInCamelCase; // property name in camel case - // enum name based on the property name, usually use as a prefix (e.g. VAR_NAME) for enum name (e.g. VAR_NAME_VALUE1) + // enum name based on the property name, usually use as a prefix (e.g. VAR_NAME) for enum name + // (e.g. VAR_NAME_VALUE1) public String enumName; public Integer maxItems; public Integer minItems; @@ -63,8 +73,7 @@ public String toString() { @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((_enum == null) ? 0 : _enum.hashCode()); @@ -77,20 +86,22 @@ public int hashCode() result = prime * result + ((datatypeWithEnum == null) ? 0 : datatypeWithEnum.hashCode()); result = prime * result + ((dataFormat == null) ? 0 : dataFormat.hashCode()); result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode()); - result = prime * result + ((defaultValueWithParam == null) ? 0 : defaultValueWithParam.hashCode()); + result = + prime * result + + ((defaultValueWithParam == null) ? 0 : defaultValueWithParam.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((title == null) ? 0 : title.hashCode()); result = prime * result + ((example == null) ? 0 : example.hashCode()); - result = prime * result + (exclusiveMaximum ? 13:31); - result = prime * result + (exclusiveMinimum ? 13:31); + result = prime * result + (exclusiveMaximum ? 13 : 31); + result = prime * result + (exclusiveMinimum ? 13 : 31); result = prime * result + ((getter == null) ? 0 : getter.hashCode()); - result = prime * result + (hasMore ? 13:31); - result = prime * result + ((hasMoreNonReadOnly ? 13:31)); - result = prime * result + ((isContainer ? 13:31)); + result = prime * result + (hasMore ? 13 : 31); + result = prime * result + ((hasMoreNonReadOnly ? 13 : 31)); + result = prime * result + ((isContainer ? 13 : 31)); result = prime * result + (isEnum ? 1231 : 1237); - result = prime * result + ((isNotContainer ? 13:31)); - result = prime * result + ((isPrimitiveType ? 13:31)); - result = prime * result + ((isReadOnly ? 13:31)); + result = prime * result + ((isNotContainer ? 13 : 31)); + result = prime * result + ((isPrimitiveType ? 13 : 31)); + result = prime * result + ((isReadOnly ? 13 : 31)); result = prime * result + ((items == null) ? 0 : items.hashCode()); result = prime * result + ((jsonSchema == null) ? 0 : jsonSchema.hashCode()); result = prime * result + ((max == null) ? 0 : max.hashCode()); @@ -101,25 +112,27 @@ public int hashCode() result = prime * result + ((minimum == null) ? 0 : minimum.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((pattern == null) ? 0 : pattern.hashCode()); - result = prime * result + ((required ? 13:31)); - result = prime * result + ((secondaryParam ? 13:31)); + result = prime * result + ((required ? 13 : 31)); + result = prime * result + ((secondaryParam ? 13 : 31)); result = prime * result + ((setter == null) ? 0 : setter.hashCode()); - result = prime * result + ((unescapedDescription == null) ? 0 : unescapedDescription.hashCode()); + result = + prime * result + + ((unescapedDescription == null) ? 0 : unescapedDescription.hashCode()); result = prime * result + ((vendorExtensions == null) ? 0 : vendorExtensions.hashCode()); - result = prime * result + ((hasValidation ? 13:31)); - result = prime * result + ((isString ? 13:31)); - result = prime * result + ((isInteger ? 13:31)); - result = prime * result + ((isLong ?13:31)); - result = prime * result + ((isFloat ? 13:31)); - result = prime * result + ((isDouble ? 13:31)); - result = prime * result + ((isByteArray ? 13:31)); - result = prime * result + ((isBinary ? 13:31)); - result = prime * result + ((isFile ? 13:31)); - result = prime * result + ((isBoolean ? 13:31)); - result = prime * result + ((isDate ? 13:31)); - result = prime * result + ((isDateTime ? 13:31)); - result = prime * result + ((isMapContainer ? 13:31)); - result = prime * result + ((isListContainer ? 13:31)); + result = prime * result + ((hasValidation ? 13 : 31)); + result = prime * result + ((isString ? 13 : 31)); + result = prime * result + ((isInteger ? 13 : 31)); + result = prime * result + ((isLong ? 13 : 31)); + result = prime * result + ((isFloat ? 13 : 31)); + result = prime * result + ((isDouble ? 13 : 31)); + result = prime * result + ((isByteArray ? 13 : 31)); + result = prime * result + ((isBinary ? 13 : 31)); + result = prime * result + ((isFile ? 13 : 31)); + result = prime * result + ((isBoolean ? 13 : 31)); + result = prime * result + ((isDate ? 13 : 31)); + result = prime * result + ((isDateTime ? 13 : 31)); + result = prime * result + ((isMapContainer ? 13 : 31)); + result = prime * result + ((isListContainer ? 13 : 31)); result = prime * result + Objects.hashCode(isInherited); result = prime * result + Objects.hashCode(nameInCamelCase); result = prime * result + Objects.hashCode(enumName); @@ -137,10 +150,12 @@ public boolean equals(Object obj) { return false; } final CodegenProperty other = (CodegenProperty) obj; - if ((this.baseName == null) ? (other.baseName != null) : !this.baseName.equals(other.baseName)) { + if ((this.baseName == null) ? (other.baseName != null) : !this.baseName + .equals(other.baseName)) { return false; } - if ((this.complexType == null) ? (other.complexType != null) : !this.complexType.equals(other.complexType)) { + if ((this.complexType == null) ? (other.complexType != null) : !this.complexType + .equals(other.complexType)) { return false; } if ((this.getter == null) ? (other.getter != null) : !this.getter.equals(other.getter)) { @@ -149,19 +164,23 @@ public boolean equals(Object obj) { if ((this.setter == null) ? (other.setter != null) : !this.setter.equals(other.setter)) { return false; } - if ((this.description == null) ? (other.description != null) : !this.description.equals(other.description)) { + if ((this.description == null) ? (other.description != null) : !this.description + .equals(other.description)) { return false; } if ((this.title == null) ? (other.title != null) : !this.title.equals(other.title)) { return false; } - if ((this.datatype == null) ? (other.datatype != null) : !this.datatype.equals(other.datatype)) { + if ((this.datatype == null) ? (other.datatype != null) : !this.datatype + .equals(other.datatype)) { return false; } - if ((this.datatypeWithEnum == null) ? (other.datatypeWithEnum != null) : !this.datatypeWithEnum.equals(other.datatypeWithEnum)) { + if ((this.datatypeWithEnum == null) ? (other.datatypeWithEnum != null) + : !this.datatypeWithEnum.equals(other.datatypeWithEnum)) { return false; } - if ((this.dataFormat == null) ? (other.dataFormat != null) : !this.dataFormat.equals(other.dataFormat)) { + if ((this.dataFormat == null) ? (other.dataFormat != null) : !this.dataFormat + .equals(other.dataFormat)) { return false; } if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { @@ -173,19 +192,24 @@ public boolean equals(Object obj) { if ((this.max == null) ? (other.max != null) : !this.max.equals(other.max)) { return false; } - if ((this.defaultValue == null) ? (other.defaultValue != null) : !this.defaultValue.equals(other.defaultValue)) { + if ((this.defaultValue == null) ? (other.defaultValue != null) : !this.defaultValue + .equals(other.defaultValue)) { return false; } - if ((this.baseType == null) ? (other.baseType != null) : !this.baseType.equals(other.baseType)) { + if ((this.baseType == null) ? (other.baseType != null) : !this.baseType + .equals(other.baseType)) { return false; } - if ((this.containerType == null) ? (other.containerType != null) : !this.containerType.equals(other.containerType)) { + if ((this.containerType == null) ? (other.containerType != null) : !this.containerType + .equals(other.containerType)) { return false; } - if (this.maxLength != other.maxLength && (this.maxLength == null || !this.maxLength.equals(other.maxLength))) { + if (this.maxLength != other.maxLength + && (this.maxLength == null || !this.maxLength.equals(other.maxLength))) { return false; } - if (this.minLength != other.minLength && (this.minLength == null || !this.minLength.equals(other.minLength))) { + if (this.minLength != other.minLength + && (this.minLength == null || !this.minLength.equals(other.minLength))) { return false; } if ((this.pattern == null) ? (other.pattern != null) : !this.pattern.equals(other.pattern)) { @@ -194,13 +218,16 @@ public boolean equals(Object obj) { if ((this.example == null) ? (other.example != null) : !this.example.equals(other.example)) { return false; } - if ((this.jsonSchema == null) ? (other.jsonSchema != null) : !this.jsonSchema.equals(other.jsonSchema)) { + if ((this.jsonSchema == null) ? (other.jsonSchema != null) : !this.jsonSchema + .equals(other.jsonSchema)) { return false; } - if (this.minimum != other.minimum && (this.minimum == null || !this.minimum.equals(other.minimum))) { + if (this.minimum != other.minimum + && (this.minimum == null || !this.minimum.equals(other.minimum))) { return false; } - if (this.maximum != other.maximum && (this.maximum == null || !this.maximum.equals(other.maximum))) { + if (this.maximum != other.maximum + && (this.maximum == null || !this.maximum.equals(other.maximum))) { return false; } if (this.exclusiveMinimum != other.exclusiveMinimum) { @@ -233,11 +260,15 @@ public boolean equals(Object obj) { if (this._enum != other._enum && (this._enum == null || !this._enum.equals(other._enum))) { return false; } - if (this.allowableValues != other.allowableValues && (this.allowableValues == null || !this.allowableValues.equals(other.allowableValues))) { + if (this.allowableValues != other.allowableValues + && (this.allowableValues == null || !this.allowableValues + .equals(other.allowableValues))) { return false; } - if (this.vendorExtensions != other.vendorExtensions && (this.vendorExtensions == null || !this.vendorExtensions.equals(other.vendorExtensions))) { + if (this.vendorExtensions != other.vendorExtensions + && (this.vendorExtensions == null || !this.vendorExtensions + .equals(other.vendorExtensions))) { return false; } @@ -294,10 +325,12 @@ public boolean equals(Object obj) { if (!Objects.equals(this.enumName, other.enumName)) { return false; } - if (this.maxItems != other.maxItems && (this.maxItems == null || !this.maxItems.equals(other.maxItems))) { + if (this.maxItems != other.maxItems + && (this.maxItems == null || !this.maxItems.equals(other.maxItems))) { return false; } - if (this.minItems != other.minItems && (this.minItems == null || !this.minItems.equals(other.minItems))) { + if (this.minItems != other.minItems + && (this.minItems == null || !this.minItems.equals(other.minItems))) { return false; } return true; @@ -306,8 +339,8 @@ public boolean equals(Object obj) { @Override public CodegenProperty clone() { try { - CodegenProperty cp = (CodegenProperty) super.clone(); - if (this._enum != null) { + CodegenProperty cp = (CodegenProperty) super.clone(); + if (this._enum != null) { cp._enum = new ArrayList(this._enum); } if (this.allowableValues != null) { @@ -316,10 +349,10 @@ public CodegenProperty clone() { if (this.items != null) { cp.items = this.items; } - if(this.vendorExtensions != null){ + if (this.vendorExtensions != null) { cp.vendorExtensions = new HashMap(this.vendorExtensions); } - return cp; + return cp; } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java index b2a734fc9b2..356658ce7c5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java @@ -11,7 +11,8 @@ public class CodegenResponse { public List> examples; public String dataType, baseType, containerType; public boolean hasHeaders; - public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBoolean, isDate, isDateTime; + public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBoolean, isDate, + isDateTime; public boolean isDefault; public boolean simpleType; public boolean primitiveType; @@ -30,8 +31,10 @@ public String toString() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; CodegenResponse that = (CodegenResponse) o; @@ -49,7 +52,8 @@ public boolean equals(Object o) { return false; if (baseType != null ? !baseType.equals(that.baseType) : that.baseType != null) return false; - if (containerType != null ? !containerType.equals(that.containerType) : that.containerType != null) + if (containerType != null ? !containerType.equals(that.containerType) + : that.containerType != null) return false; if (isDefault != that.isDefault) return false; @@ -67,7 +71,8 @@ public boolean equals(Object o) { return false; if (schema != null ? !schema.equals(that.schema) : that.schema != null) return false; - if (vendorExtensions != null ? !vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions != null) + if (vendorExtensions != null ? !vendorExtensions.equals(that.vendorExtensions) + : that.vendorExtensions != null) return false; return jsonSchema != null ? jsonSchema.equals(that.jsonSchema) : that.jsonSchema == null; @@ -78,18 +83,18 @@ public int hashCode() { int result = headers.hashCode(); result = 31 * result + (code != null ? code.hashCode() : 0); result = 31 * result + (message != null ? message.hashCode() : 0); - result = 31 * result + (hasMore ? 13:31); + result = 31 * result + (hasMore ? 13 : 31); result = 31 * result + (examples != null ? examples.hashCode() : 0); result = 31 * result + (dataType != null ? dataType.hashCode() : 0); result = 31 * result + (baseType != null ? baseType.hashCode() : 0); result = 31 * result + (containerType != null ? containerType.hashCode() : 0); - result = 31 * result + (isDefault ? 13:31); - result = 31 * result + (simpleType ? 13:31); - result = 31 * result + (primitiveType ? 13:31); - result = 31 * result + (isMapContainer ? 13:31); - result = 31 * result + (isListContainer ? 13:31); - result = 31 * result + (isBinary ? 13:31); - result = 31 * result + (isFile ? 13:31); + result = 31 * result + (isDefault ? 13 : 31); + result = 31 * result + (simpleType ? 13 : 31); + result = 31 * result + (primitiveType ? 13 : 31); + result = 31 * result + (isMapContainer ? 13 : 31); + result = 31 * result + (isListContainer ? 13 : 31); + result = 31 * result + (isBinary ? 13 : 31); + result = 31 * result + (isFile ? 13 : 31); result = 31 * result + (schema != null ? schema.hashCode() : 0); result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0); result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java index 4e9dd098a4e..85bdee2c400 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java @@ -22,8 +22,10 @@ public String toString() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; CodegenSecurity that = (CodegenSecurity) o; @@ -39,15 +41,19 @@ public boolean equals(Object o) { return false; if (isApiKey != null ? !isApiKey.equals(that.isApiKey) : that.isApiKey != null) return false; - if (keyParamName != null ? !keyParamName.equals(that.keyParamName) : that.keyParamName != null) + if (keyParamName != null ? !keyParamName.equals(that.keyParamName) + : that.keyParamName != null) return false; - if (isKeyInQuery != null ? !isKeyInQuery.equals(that.isKeyInQuery) : that.isKeyInQuery != null) + if (isKeyInQuery != null ? !isKeyInQuery.equals(that.isKeyInQuery) + : that.isKeyInQuery != null) return false; - if (isKeyInHeader != null ? !isKeyInHeader.equals(that.isKeyInHeader) : that.isKeyInHeader != null) + if (isKeyInHeader != null ? !isKeyInHeader.equals(that.isKeyInHeader) + : that.isKeyInHeader != null) return false; if (flow != null ? !flow.equals(that.flow) : that.flow != null) return false; - if (authorizationUrl != null ? !authorizationUrl.equals(that.authorizationUrl) : that.authorizationUrl != null) + if (authorizationUrl != null ? !authorizationUrl.equals(that.authorizationUrl) + : that.authorizationUrl != null) return false; if (tokenUrl != null ? !tokenUrl.equals(that.tokenUrl) : that.tokenUrl != null) return false; @@ -55,7 +61,8 @@ public boolean equals(Object o) { return false; if (isPassword != null ? !isPassword.equals(that.isPassword) : that.isPassword != null) return false; - if (isApplication != null ? !isApplication.equals(that.isApplication) : that.isApplication != null) + if (isApplication != null ? !isApplication.equals(that.isApplication) + : that.isApplication != null) return false; if (isImplicit != null ? !isImplicit.equals(that.isImplicit) : that.isImplicit != null) return false; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenType.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenType.java index 8d65290e8f8..99a90eb04e6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenType.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenType.java @@ -33,4 +33,4 @@ public String toValue() { names.put("documentation", DOCUMENTATION); names.put("other", OTHER); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 586a95fefb4..4321446b27e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -74,7 +74,7 @@ public class DefaultCodegen { protected static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); - + protected String inputSpec; protected String outputFolder = ""; protected Set defaultIncludes = new HashSet(); @@ -136,31 +136,33 @@ public void processOpts() { } if (additionalProperties.containsKey(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) { - this.setSortParamsByRequiredFlag(Boolean.valueOf(additionalProperties - .get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString())); + this.setSortParamsByRequiredFlag(Boolean.valueOf(additionalProperties.get( + CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString())); } if (additionalProperties.containsKey(CodegenConstants.ENSURE_UNIQUE_PARAMS)) { - this.setEnsureUniqueParams(Boolean.valueOf(additionalProperties - .get(CodegenConstants.ENSURE_UNIQUE_PARAMS).toString())); + this.setEnsureUniqueParams(Boolean.valueOf(additionalProperties.get( + CodegenConstants.ENSURE_UNIQUE_PARAMS).toString())); } if (additionalProperties.containsKey(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS)) { - this.setAllowUnicodeIdentifiers(Boolean.valueOf(additionalProperties - .get(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS).toString())); + this.setAllowUnicodeIdentifiers(Boolean.valueOf(additionalProperties.get( + CodegenConstants.ALLOW_UNICODE_IDENTIFIERS).toString())); } - if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_PREFIX)){ - this.setModelNamePrefix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_PREFIX)); + if (additionalProperties.containsKey(CodegenConstants.MODEL_NAME_PREFIX)) { + this.setModelNamePrefix((String) additionalProperties + .get(CodegenConstants.MODEL_NAME_PREFIX)); } - if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_SUFFIX)){ - this.setModelNameSuffix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_SUFFIX)); + if (additionalProperties.containsKey(CodegenConstants.MODEL_NAME_SUFFIX)) { + this.setModelNameSuffix((String) additionalProperties + .get(CodegenConstants.MODEL_NAME_SUFFIX)); } } // override with any special post-processing for all models - @SuppressWarnings({ "static-method", "unchecked" }) + @SuppressWarnings({"static-method", "unchecked"}) public Map postProcessAllModels(Map objs) { if (supportsInheritance) { // Index all CodegenModels by model name. @@ -193,11 +195,13 @@ public Map postProcessAllModels(Map objs) { for (String name : allModels.keySet()) { CodegenModel cm = allModels.get(name); CodegenModel parent = allModels.get(cm.parent); - // if a discriminator exists on the parent, don't add this child to the inheritance heirarchy - // TODO Determine what to do if the parent discriminator name == the grandparent discriminator name + // if a discriminator exists on the parent, don't add this child to the inheritance + // heirarchy + // TODO Determine what to do if the parent discriminator name == the grandparent + // discriminator name while (parent != null) { if (parent.children == null) { - parent.children = new ArrayList(); + parent.children = new ArrayList(); } parent.children.add(cm); if (parent.discriminator == null) { @@ -281,7 +285,7 @@ public String findCommonPrefixOfVars(List vars) { return ""; } } - + /** * Return the enum default value in the language specified format * @@ -294,8 +298,7 @@ public String toEnumDefaultValue(String value, String datatype) { } /** - * Return the enum value in the language specified format - * e.g. status becomes "status" + * Return the enum value in the language specified format e.g. status becomes "status" * * @param value enum variable name * @param datatype data type @@ -308,7 +311,7 @@ public String toEnumValue(String value, String datatype) { return "\"" + escapeText(value) + "\""; } } - + /** * Return the sanitized variable name for enum * @@ -343,24 +346,20 @@ public Map postProcessSupportingFileData(Map obj // override to post-process any model properties @SuppressWarnings("unused") - public void postProcessModelProperty(CodegenModel model, CodegenProperty property){ - } + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {} // override to post-process any parameters @SuppressWarnings("unused") - public void postProcessParameter(CodegenParameter parameter){ - } + public void postProcessParameter(CodegenParameter parameter) {} - //override with any special handling of the entire swagger spec + // override with any special handling of the entire swagger spec @SuppressWarnings("unused") - public void preprocessSwagger(Swagger swagger) { - } + public void preprocessSwagger(Swagger swagger) {} // override with any special handling of the entire swagger spec @SuppressWarnings("unused") - public void processSwagger(Swagger swagger) { - } - + public void processSwagger(Swagger swagger) {} + // override with any special handling of the JMustache compiler @SuppressWarnings("unused") public Compiler processCompiler(Compiler compiler) { @@ -379,24 +378,21 @@ public String escapeText(String input) { // replace " with \" // outter unescape to retain the original multi-byte characters // finally escalate characters avoiding code injection - return escapeUnsafeCharacters( - StringEscapeUtils.unescapeJava( - StringEscapeUtils.escapeJava(input) - .replace("\\/", "/")) - .replaceAll("[\\t\\n\\r]"," ") - .replace("\\", "\\\\") - .replace("\"", "\\\"")); + return escapeUnsafeCharacters(StringEscapeUtils + .unescapeJava(StringEscapeUtils.escapeJava(input).replace("\\/", "/")) + .replaceAll("[\\t\\n\\r]", " ").replace("\\", "\\\\").replace("\"", "\\\"")); } /** - * override with any special text escaping logic to handle unsafe - * characters so as to avoid code injection + * override with any special text escaping logic to handle unsafe characters so as to avoid code + * injection + * * @param input String to be cleaned up * @return string with unsafe characters removed or escaped */ public String escapeUnsafeCharacters(String input) { - LOGGER.warn("escapeUnsafeCharacters should be overridden in the code generator with proper logic to escape " + - "unsafe characters"); + LOGGER.warn("escapeUnsafeCharacters should be overridden in the code generator with proper logic to escape " + + "unsafe characters"); // doing nothing by default and code generator should implement // the logic to prevent code injection // later we'll make this method abstract to make sure @@ -405,13 +401,14 @@ public String escapeUnsafeCharacters(String input) { } /** - * Escape single and/or double quote to avoid code injection + * Escape single and/or double quote to avoid code injection + * * @param input String to be cleaned up * @return string with quotation mark removed or escaped */ public String escapeQuotationMark(String input) { - LOGGER.warn("escapeQuotationMark should be overridden in the code generator with proper logic to escape " + - "single/double quote"); + LOGGER.warn("escapeQuotationMark should be overridden in the code generator with proper logic to escape " + + "single/double quote"); return input.replace("\"", "\\\""); } @@ -482,7 +479,7 @@ public Map apiDocTemplateFiles() { public Map modelDocTemplateFiles() { return modelDocTemplateFiles; } - + public Map reservedWordsMappings() { return reservedWordsMappings; } @@ -567,11 +564,11 @@ public void setModelPackage(String modelPackage) { this.modelPackage = modelPackage; } - public void setModelNamePrefix(String modelNamePrefix){ + public void setModelNamePrefix(String modelNamePrefix) { this.modelNamePrefix = modelNamePrefix; } - public void setModelNameSuffix(String modelNameSuffix){ + public void setModelNameSuffix(String modelNameSuffix) { this.modelNameSuffix = modelNameSuffix; } @@ -592,7 +589,8 @@ public void setAllowUnicodeIdentifiers(Boolean allowUnicodeIdentifiers) { } /** - * Return the regular expression/JSON schema pattern (http://json-schema.org/latest/json-schema-validation.html#anchor33) + * Return the regular expression/JSON schema pattern + * (http://json-schema.org/latest/json-schema-validation.html#anchor33) * * @param pattern the pattern (regular expression) * @return properly-escaped pattern @@ -612,7 +610,7 @@ public String toApiFilename(String name) { } /** - * Return the file name of the Api Documentation + * Return the file name of the Api Documentation * * @param name the file name of the Api * @return the file name of the Api @@ -670,7 +668,7 @@ public String toModelTestFilename(String name) { public String toModelDocFilename(String name) { return initialCaps(name); } - + /** * Return the operation ID (method name) * @@ -688,8 +686,8 @@ public String toOperationId(String operationId) { } /** - * Return the variable name by removing invalid characters and proper escaping if - * it's a reserved word. + * Return the variable name by removing invalid characters and proper escaping if it's a + * reserved word. * * @param name the variable name * @return the sanitized variable name @@ -703,14 +701,16 @@ public String toVarName(String name) { } /** - * Return the parameter name by removing invalid characters and proper escaping if - * it's a reserved word. + * Return the parameter name by removing invalid characters and proper escaping if it's a + * reserved word. * * @param name Codegen property object * @return the sanitized parameter name */ public String toParamName(String name) { - name = removeNonNameElementToCamelCase(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = removeNonNameElementToCamelCase(name); // FIXME: a parameter should not be assigned. + // Also declare the methods parameters as + // 'final'. if (reservedWords.contains(name)) { return escapeReservedWord(name); } @@ -734,7 +734,7 @@ public String toEnumName(CodegenProperty property) { * @param name the name to be escaped * @return the escaped reserved word * - * throws Runtime exception as reserved word is not allowed (default behavior) + * throws Runtime exception as reserved word is not allowed (default behavior) */ @SuppressWarnings("static-method") public String escapeReservedWord(String name) { @@ -766,31 +766,18 @@ public String toApiImport(String name) { } /** - * Default constructor. - * This method will map between Swagger type and language-specified type, as well as mapping - * between Swagger type and the corresponding import statement for the language. This will - * also add some language specified CLI options, if any. + * Default constructor. This method will map between Swagger type and language-specified type, + * as well as mapping between Swagger type and the corresponding import statement for the + * language. This will also add some language specified CLI options, if any. * * * returns string presentation of the example path (it's a constructor) */ public DefaultCodegen() { - defaultIncludes = new HashSet( - Arrays.asList("double", - "int", - "long", - "short", - "char", - "float", - "String", - "boolean", - "Boolean", - "Double", - "Void", - "Integer", - "Long", - "Float") - ); + defaultIncludes = + new HashSet(Arrays.asList("double", "int", "long", "short", "char", + "float", "String", "boolean", "Boolean", "Double", "Void", "Integer", + "Long", "Float")); typeMapping = new HashMap(); typeMapping.put("array", "List"); @@ -834,20 +821,22 @@ public DefaultCodegen() { importMapping.put("LocalDate", "org.joda.time.*"); importMapping.put("LocalTime", "org.joda.time.*"); - // we've used the .swagger-codegen-ignore approach as + // we've used the .swagger-codegen-ignore approach as // suppportingFiles can be cleared by code generator that extends - // the default codegen, leaving the commented code below for + // the default codegen, leaving the commented code below for // future reference - //supportingFiles.add(new GlobalSupportingFile("LICENSE", "LICENSE")); + // supportingFiles.add(new GlobalSupportingFile("LICENSE", "LICENSE")); cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, - CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); - cliOptions.add(CliOption.newBoolean(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants - .ENSURE_UNIQUE_PARAMS_DESC).defaultValue(Boolean.TRUE.toString())); + CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue( + Boolean.TRUE.toString())); + cliOptions.add(CliOption.newBoolean(CodegenConstants.ENSURE_UNIQUE_PARAMS, + CodegenConstants.ENSURE_UNIQUE_PARAMS_DESC).defaultValue(Boolean.TRUE.toString())); - //name formatting options - cliOptions.add(CliOption.newBoolean(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, CodegenConstants - .ALLOW_UNICODE_IDENTIFIERS_DESC).defaultValue(Boolean.FALSE.toString())); + // name formatting options + cliOptions.add(CliOption.newBoolean(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, + CodegenConstants.ALLOW_UNICODE_IDENTIFIERS_DESC).defaultValue( + Boolean.FALSE.toString())); // initialize special character mapping initalizeSpecialCharacterMapping(); @@ -975,8 +964,9 @@ public String toInstantiationType(Property p) { Property additionalProperties2 = ap.getAdditionalProperties(); String type = additionalProperties2.getType(); if (null == type) { - LOGGER.error("No Type defined for Additional Property " + additionalProperties2 + "\n" // - + "\tIn Property: " + p); + LOGGER.error("No Type defined for Additional Property " + additionalProperties2 + + "\n" // + + "\tIn Property: " + p); } String inner = getSwaggerType(additionalProperties2); return instantiationTypes.get("map") + ""; @@ -990,7 +980,7 @@ public String toInstantiationType(Property p) { } /** - * Return the example value of the parameter. + * Return the example value of the parameter. * * @param p Swagger property object */ @@ -1005,7 +995,7 @@ public void setParameterExampleValue(CodegenParameter p) { * @return string presentation of the example value of the property */ public String toExampleValue(Property p) { - if(p.getExample() != null) { + if (p.getExample() != null) { return p.getExample().toString(); } if (p instanceof StringProperty) { @@ -1091,8 +1081,8 @@ public String toDefaultValue(Property p) { } /** - * Return the property initialized from a data object - * Useful for initialization with a plain object in Javascript + * Return the property initialized from a data object Useful for initialization with a plain + * object in Javascript * * @param name Name of the property object * @param p Swagger property object @@ -1105,6 +1095,7 @@ public String toDefaultValueWithParam(String name, Property p) { /** * returns the swagger type for the property + * * @param p Swagger property object * @return string presentation of the type **/ @@ -1139,7 +1130,7 @@ public String getSwaggerType(Property p) { datatype = "map"; } else if (p instanceof DecimalProperty) { datatype = "number"; - } else if ( p instanceof UUIDProperty) { + } else if (p instanceof UUIDProperty) { datatype = "UUID"; } else if (p instanceof RefProperty) { try { @@ -1149,7 +1140,8 @@ public String getSwaggerType(Property p) { datatype = datatype.substring("#/definitions/".length()); } } catch (Exception e) { - LOGGER.warn("Error obtaining the datatype from RefProperty:" + p + ". Datatype default to Object"); + LOGGER.warn("Error obtaining the datatype from RefProperty:" + p + + ". Datatype default to Object"); datatype = "Object"; LOGGER.error(e.getMessage(), e); } @@ -1169,7 +1161,8 @@ public String getSwaggerType(Property p) { */ @SuppressWarnings("static-method") public String snakeCase(String name) { - return (name.length() > 0) ? (Character.toLowerCase(name.charAt(0)) + name.substring(1)) : ""; + return (name.length() > 0) ? (Character.toLowerCase(name.charAt(0)) + name.substring(1)) + : ""; } /** @@ -1209,8 +1202,8 @@ public String getTypeDeclaration(Property p) { } /** - * Output the API (class) name (capitalized) ending with "Api" - * Return DefaultApi if name is empty + * Output the API (class) name (capitalized) ending with "Api" Return DefaultApi if name is + * empty * * @param name the name of the Api * @return capitalized Api name ending with "Api" @@ -1223,8 +1216,8 @@ public String toApiName(String name) { } /** - * Output the proper model name (capitalized). - * In case the name belongs to the TypeSystem it won't be renamed. + * Output the proper model name (capitalized). In case the name belongs to the TypeSystem it + * won't be renamed. * * @param name the name of the model * @return capitalized model name @@ -1292,7 +1285,7 @@ public CodegenModel fromModel(String name, Model model, Map allDe allRequired = new ArrayList(); m.allVars = new ArrayList(); int modelImplCnt = 0; // only one inline object allowed in a ComposedModel - for (Model innerModel: ((ComposedModel)model).getAllOf()) { + for (Model innerModel : ((ComposedModel) model).getAllOf()) { if (innerModel instanceof ModelImpl) { if (m.discriminator == null) { m.discriminator = ((ModelImpl) innerModel).getDiscriminator(); @@ -1321,8 +1314,9 @@ public CodegenModel fromModel(String name, Model model, Map allDe } // set first interface with discriminator found as parent if (parent == null - && ((interfaceModel instanceof ModelImpl && ((ModelImpl) interfaceModel).getDiscriminator() != null) - || (interfaceModel instanceof ComposedModel && isDiscriminatorInInterfaceTree((ComposedModel) interfaceModel, allDefinitions)))) { + && ((interfaceModel instanceof ModelImpl && ((ModelImpl) interfaceModel) + .getDiscriminator() != null) || (interfaceModel instanceof ComposedModel && isDiscriminatorInInterfaceTree( + (ComposedModel) interfaceModel, allDefinitions)))) { parent = _interface; } else { final String interfaceRef = toModelName(_interface.getSimpleRef()); @@ -1333,7 +1327,8 @@ public CodegenModel fromModel(String name, Model model, Map allDe addProperties(properties, required, interfaceModel, allDefinitions); } if (supportsInheritance) { - addProperties(allProperties, allRequired, interfaceModel, allDefinitions); + addProperties(allProperties, allRequired, interfaceModel, + allDefinitions); } } } @@ -1374,7 +1369,7 @@ public CodegenModel fromModel(String name, Model model, Map allDe Property p = PropertyBuilder.build(impl.getType(), impl.getFormat(), null); m.dataType = getSwaggerType(p); } - if(impl.getEnum() != null && impl.getEnum().size() > 0) { + if (impl.getEnum() != null && impl.getEnum().size() > 0) { m.isEnum = true; // comment out below as allowableValues is not set in post processing model enum m.allowableValues = new HashMap(); @@ -1387,7 +1382,7 @@ public CodegenModel fromModel(String name, Model model, Map allDe } if (m.vars != null) { - for(CodegenProperty prop : m.vars) { + for (CodegenProperty prop : m.vars) { postProcessModelProperty(m, prop); } } @@ -1397,7 +1392,8 @@ public CodegenModel fromModel(String name, Model model, Map allDe /** * Recursively look for a discriminator in the interface tree */ - private boolean isDiscriminatorInInterfaceTree(ComposedModel model, Map allDefinitions) { + private boolean isDiscriminatorInInterfaceTree(ComposedModel model, + Map allDefinitions) { if (model == null || allDefinitions == null) return false; @@ -1407,25 +1403,27 @@ private boolean isDiscriminatorInInterfaceTree(ComposedModel model, Map properties, - List required, Model model, - Map allDefinitions) { + protected void addProperties(Map properties, List required, + Model model, Map allDefinitions) { if (model instanceof ModelImpl) { ModelImpl mi = (ModelImpl) model; @@ -1440,7 +1438,7 @@ protected void addProperties(Map properties, Model interfaceModel = allDefinitions.get(interfaceRef); addProperties(properties, required, interfaceModel, allDefinitions); } else if (model instanceof ComposedModel) { - for (Model component :((ComposedModel) model).getAllOf()) { + for (Model component : ((ComposedModel) model).getAllOf()) { addProperties(properties, required, component, allDefinitions); } } @@ -1494,18 +1492,18 @@ public CodegenProperty fromProperty(String name, Property p) { if (p instanceof AbstractNumericProperty) { AbstractNumericProperty np = (AbstractNumericProperty) p; if (np.getMinimum() != null) { - if (p instanceof BaseIntegerProperty) { // int, long - property.minimum = String.valueOf(np.getMinimum().longValue()); - } else { // double, decimal - property.minimum = String.valueOf(np.getMinimum()); - } + if (p instanceof BaseIntegerProperty) { // int, long + property.minimum = String.valueOf(np.getMinimum().longValue()); + } else { // double, decimal + property.minimum = String.valueOf(np.getMinimum()); + } } if (np.getMaximum() != null) { - if (p instanceof BaseIntegerProperty) { // int, long - property.maximum = String.valueOf(np.getMaximum().longValue()); - } else { // double, decimal - property.maximum = String.valueOf(np.getMaximum()); - } + if (p instanceof BaseIntegerProperty) { // int, long + property.maximum = String.valueOf(np.getMaximum().longValue()); + } else { // double, decimal + property.maximum = String.valueOf(np.getMaximum()); + } } if (np.getExclusiveMinimum() != null) { @@ -1528,8 +1526,8 @@ public CodegenProperty fromProperty(String name, Property p) { if (np.getMaximum() != null) { allowableValues.put("max", np.getMaximum()); } - if(allowableValues.size() > 0) { - property.allowableValues = allowableValues; + if (allowableValues.size() > 0) { + property.allowableValues = allowableValues; } } @@ -1540,7 +1538,8 @@ public CodegenProperty fromProperty(String name, Property p) { property.pattern = toRegularExpression(sp.getPattern()); // check if any validation rule defined - if (property.pattern != null || property.minLength != null || property.maxLength != null) + if (property.pattern != null || property.minLength != null + || property.maxLength != null) property.hasValidation = true; property.isString = true; @@ -1557,7 +1556,8 @@ public CodegenProperty fromProperty(String name, Property p) { } // type is integer and without format - if (p instanceof BaseIntegerProperty && !(p instanceof IntegerProperty) && !(p instanceof LongProperty)) { + if (p instanceof BaseIntegerProperty && !(p instanceof IntegerProperty) + && !(p instanceof LongProperty)) { BaseIntegerProperty sp = (BaseIntegerProperty) p; property.isInteger = true; /*if (sp.getEnum() != null) { @@ -1580,8 +1580,8 @@ public CodegenProperty fromProperty(String name, Property p) { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for(Integer i : _enum) { - property._enum.add(i.toString()); + for (Integer i : _enum) { + property._enum.add(i.toString()); } property.isEnum = true; @@ -1597,8 +1597,8 @@ public CodegenProperty fromProperty(String name, Property p) { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for(Long i : _enum) { - property._enum.add(i.toString()); + for (Long i : _enum) { + property._enum.add(i.toString()); } property.isEnum = true; @@ -1624,7 +1624,8 @@ public CodegenProperty fromProperty(String name, Property p) { property.isByteArray = true; } // type is number and without format - if (p instanceof DecimalProperty && !(p instanceof DoubleProperty) && !(p instanceof FloatProperty)) { + if (p instanceof DecimalProperty && !(p instanceof DoubleProperty) + && !(p instanceof FloatProperty)) { DecimalProperty sp = (DecimalProperty) p; property.isFloat = true; /*if (sp.getEnum() != null) { @@ -1647,8 +1648,8 @@ public CodegenProperty fromProperty(String name, Property p) { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for(Double i : _enum) { - property._enum.add(i.toString()); + for (Double i : _enum) { + property._enum.add(i.toString()); } property.isEnum = true; @@ -1664,8 +1665,8 @@ public CodegenProperty fromProperty(String name, Property p) { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for(Float i : _enum) { - property._enum.add(i.toString()); + for (Float i : _enum) { + property._enum.add(i.toString()); } property.isEnum = true; @@ -1682,8 +1683,8 @@ public CodegenProperty fromProperty(String name, Property p) { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for(String i : _enum) { - property._enum.add(i); + for (String i : _enum) { + property._enum.add(i); } property.isEnum = true; @@ -1699,8 +1700,8 @@ public CodegenProperty fromProperty(String name, Property p) { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for(String i : _enum) { - property._enum.add(i); + for (String i : _enum) { + property._enum.add(i); } property.isEnum = true; @@ -1723,7 +1724,7 @@ public CodegenProperty fromProperty(String name, Property p) { property.baseType = getSwaggerType(p); - if (p instanceof ArrayProperty) { + if (p instanceof ArrayProperty) { property.isContainer = true; property.isListContainer = true; property.containerType = "array"; @@ -1734,7 +1735,7 @@ public CodegenProperty fromProperty(String name, Property p) { property.minItems = ap.getMinItems(); CodegenProperty cp = fromProperty(property.name, ap.getItems()); updatePropertyForArray(property, cp); - } else if (p instanceof MapProperty) { + } else if (p instanceof MapProperty) { property.isContainer = true; property.isMapContainer = true; property.containerType = "map"; @@ -1751,6 +1752,7 @@ public CodegenProperty fromProperty(String name, Property p) { /** * Update property for array(list) container + * * @param property Codegen property * @param innerProperty Codegen inner property of map or list */ @@ -1782,6 +1784,7 @@ protected void updatePropertyForArray(CodegenProperty property, CodegenProperty /** * Update property for map container + * * @param property Codegen property * @param innerProperty Codegen inner property of map or list */ @@ -1813,13 +1816,15 @@ protected void updatePropertyForMap(CodegenProperty property, CodegenProperty in /** * Update property for map container + * * @param property Codegen property * @return True if the inner most type is enum */ protected Boolean isPropertyInnerMostEnum(CodegenProperty property) { CodegenProperty currentProperty = property; - while (currentProperty != null && (Boolean.TRUE.equals(currentProperty.isMapContainer) - || Boolean.TRUE.equals(currentProperty.isListContainer))) { + while (currentProperty != null + && (Boolean.TRUE.equals(currentProperty.isMapContainer) || Boolean.TRUE + .equals(currentProperty.isListContainer))) { currentProperty = currentProperty.items; } @@ -1828,8 +1833,9 @@ protected Boolean isPropertyInnerMostEnum(CodegenProperty property) { protected Map getInnerEnumAllowableValues(CodegenProperty property) { CodegenProperty currentProperty = property; - while (currentProperty != null && (Boolean.TRUE.equals(currentProperty.isMapContainer) - || Boolean.TRUE.equals(currentProperty.isListContainer))) { + while (currentProperty != null + && (Boolean.TRUE.equals(currentProperty.isMapContainer) || Boolean.TRUE + .equals(currentProperty.isListContainer))) { currentProperty = currentProperty.items; } @@ -1839,16 +1845,19 @@ protected Map getInnerEnumAllowableValues(CodegenProperty proper /** * Update datatypeWithEnum for array container + * * @param property Codegen property */ protected void updateDataTypeWithEnumForArray(CodegenProperty property) { CodegenProperty baseItem = property.items; - while (baseItem != null && (Boolean.TRUE.equals(baseItem.isMapContainer) - || Boolean.TRUE.equals(baseItem.isListContainer))) { + while (baseItem != null + && (Boolean.TRUE.equals(baseItem.isMapContainer) || Boolean.TRUE + .equals(baseItem.isListContainer))) { baseItem = baseItem.items; } // set both datatype and datetypeWithEnum as only the inner type is enum - property.datatypeWithEnum = property.datatypeWithEnum.replace(baseItem.baseType, toEnumName(baseItem)); + property.datatypeWithEnum = + property.datatypeWithEnum.replace(baseItem.baseType, toEnumName(baseItem)); // naming the enum with respect to the language enum naming convention // e.g. remove [], {} from array/map of enum @@ -1856,22 +1865,27 @@ protected void updateDataTypeWithEnumForArray(CodegenProperty property) { // set default value for variable with inner enum if (property.defaultValue != null) { - property.defaultValue = property.defaultValue.replace(baseItem.baseType, toEnumName(baseItem)); + property.defaultValue = + property.defaultValue.replace(baseItem.baseType, toEnumName(baseItem)); } } /** * Update datatypeWithEnum for map container + * * @param property Codegen property */ protected void updateDataTypeWithEnumForMap(CodegenProperty property) { CodegenProperty baseItem = property.items; - while (baseItem != null && (Boolean.TRUE.equals(baseItem.isMapContainer) - || Boolean.TRUE.equals(baseItem.isListContainer))) { + while (baseItem != null + && (Boolean.TRUE.equals(baseItem.isMapContainer) || Boolean.TRUE + .equals(baseItem.isListContainer))) { baseItem = baseItem.items; } // set both datatype and datetypeWithEnum as only the inner type is enum - property.datatypeWithEnum = property.datatypeWithEnum.replace(", " + baseItem.baseType, ", " + toEnumName(baseItem)); + property.datatypeWithEnum = + property.datatypeWithEnum.replace(", " + baseItem.baseType, ", " + + toEnumName(baseItem)); // naming the enum with respect to the language enum naming convention // e.g. remove [], {} from array/map of enum @@ -1879,7 +1893,9 @@ protected void updateDataTypeWithEnumForMap(CodegenProperty property) { // set default value for variable with inner enum if (property.defaultValue != null) { - property.defaultValue = property.defaultValue.replace(", " + property.items.baseType, ", " + toEnumName(property.items)); + property.defaultValue = + property.defaultValue.replace(", " + property.items.baseType, ", " + + toEnumName(property.items)); } } @@ -1894,6 +1910,7 @@ protected void setNonArrayMapProperty(CodegenProperty property, String type) { /** * Override with any special handling of response codes + * * @param responses Swagger Operation's responses * @return default method response or null if not found */ @@ -1914,7 +1931,8 @@ protected Response findMethodResponse(Map responses) { } /** - * Convert Swagger Operation object to Codegen Operation object (without providing a Swagger object) + * Convert Swagger Operation object to Codegen Operation object (without providing a Swagger + * object) * * @param path the path of the operation * @param httpMethod HTTP method @@ -1922,7 +1940,8 @@ protected Response findMethodResponse(Map responses) { * @param definitions a map of Swagger models * @return Codegen Operation object */ - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, + Map definitions) { return fromOperation(path, httpMethod, operation, definitions, null); } @@ -1936,11 +1955,8 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation * @param swagger a Swagger object representing the spec * @return Codegen Operation object */ - public CodegenOperation fromOperation(String path, - String httpMethod, - Operation operation, - Map definitions, - Swagger swagger) { + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, + Map definitions, Swagger swagger) { CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION); Set imports = new HashSet(); op.vendorExtensions = operation.getVendorExtensions(); @@ -1964,10 +1980,12 @@ public CodegenOperation fromOperation(String path, } else { // empty list, do nothing to override global setting } - } else if (swagger != null && swagger.getConsumes() != null && swagger.getConsumes().size() > 0) { + } else if (swagger != null && swagger.getConsumes() != null + && swagger.getConsumes().size() > 0) { // use consumes defined globally consumes = swagger.getConsumes(); - LOGGER.debug("No consumes defined in operation. Using global consumes (" + swagger.getConsumes() + ") for " + op.operationId); + LOGGER.debug("No consumes defined in operation. Using global consumes (" + + swagger.getConsumes() + ") for " + op.operationId); } // if "consumes" is defined (per operation or using global definition) @@ -2002,10 +2020,12 @@ public CodegenOperation fromOperation(String path, } else { // empty list, do nothing to override global setting } - } else if (swagger != null && swagger.getProduces() != null && swagger.getProduces().size() > 0) { + } else if (swagger != null && swagger.getProduces() != null + && swagger.getProduces().size() > 0) { // use produces defined globally produces = swagger.getProduces(); - LOGGER.debug("No produces defined in operation. Using global produces (" + swagger.getProduces() + ") for " + op.operationId); + LOGGER.debug("No produces defined in operation. Using global produces (" + + swagger.getProduces() + ") for " + op.operationId); } // if "produces" is defined (per operation or using global definition) @@ -2039,17 +2059,16 @@ public CodegenOperation fromOperation(String path, Response response = entry.getValue(); CodegenResponse r = fromResponse(entry.getKey(), response); r.hasMore = true; - if (r.baseType != null && - !defaultIncludes.contains(r.baseType) && - !languageSpecificPrimitives.contains(r.baseType)) { + if (r.baseType != null && !defaultIncludes.contains(r.baseType) + && !languageSpecificPrimitives.contains(r.baseType)) { imports.add(r.baseType); } r.isDefault = response == methodResponse; op.responses.add(r); - if (Boolean.TRUE.equals(r.isBinary) && Boolean.TRUE.equals(r.isDefault)){ + if (Boolean.TRUE.equals(r.isBinary) && Boolean.TRUE.equals(r.isDefault)) { op.isResponseBinary = Boolean.TRUE; } - if (Boolean.TRUE.equals(r.isFile) && Boolean.TRUE.equals(r.isDefault)){ + if (Boolean.TRUE.equals(r.isFile) && Boolean.TRUE.equals(r.isDefault)) { op.isResponseFile = Boolean.TRUE; } } @@ -2072,10 +2091,14 @@ public CodegenOperation fromOperation(String path, op.returnBaseType = cm.baseType; } } - op.examples = new ExampleGenerator(definitions).generate(methodResponse.getExamples(), operation.getProduces(), responseProperty); + op.examples = + new ExampleGenerator(definitions).generate( + methodResponse.getExamples(), operation.getProduces(), + responseProperty); op.defaultResponse = toDefaultValue(responseProperty); op.returnType = cm.datatype; - op.hasReference = definitions != null && definitions.containsKey(op.returnBaseType); + op.hasReference = + definitions != null && definitions.containsKey(op.returnBaseType); // lookup discriminator if (definitions != null) { @@ -2098,7 +2121,8 @@ public CodegenOperation fromOperation(String path, } else { op.returnSimpleType = true; } - if (languageSpecificPrimitives().contains(op.returnBaseType) || op.returnBaseType == null) { + if (languageSpecificPrimitives().contains(op.returnBaseType) + || op.returnBaseType == null) { op.returnTypeIsPrimitive = true; } } @@ -2176,14 +2200,17 @@ public CodegenOperation fromOperation(String path, // move "required" parameters in front of "optional" parameters if (sortParamsByRequiredFlag) { - Collections.sort(allParams, new Comparator() { - @Override - public int compare(CodegenParameter one, CodegenParameter another) { - if (one.required == another.required) return 0; - else if (one.required) return -1; - else return 1; - } - }); + Collections.sort(allParams, new Comparator() { + @Override + public int compare(CodegenParameter one, CodegenParameter another) { + if (one.required == another.required) + return 0; + else if (one.required) + return -1; + else + return 1; + } + }); } op.allParams = addHasMore(allParams); op.bodyParams = addHasMore(bodyParams); @@ -2281,11 +2308,14 @@ public CodegenResponse fromResponse(String responseCode, Response response) { r.simpleType = false; r.containerType = cm.containerType; r.isMapContainer = "map".equals(cm.containerType); - r.isListContainer = "list".equalsIgnoreCase(cm.containerType) || "array".equalsIgnoreCase(cm.containerType); + r.isListContainer = + "list".equalsIgnoreCase(cm.containerType) + || "array".equalsIgnoreCase(cm.containerType); } else { r.simpleType = true; } - r.primitiveType = (r.baseType == null || languageSpecificPrimitives().contains(r.baseType)); + r.primitiveType = + (r.baseType == null || languageSpecificPrimitives().contains(r.baseType)); } if (r.baseType == null) { r.isMapContainer = false; @@ -2320,17 +2350,17 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { // move the defaultValue for headers, forms and params if (param instanceof QueryParameter) { QueryParameter qp = (QueryParameter) param; - if(qp.getDefaultValue() != null) { + if (qp.getDefaultValue() != null) { p.defaultValue = qp.getDefaultValue().toString(); } } else if (param instanceof HeaderParameter) { HeaderParameter hp = (HeaderParameter) param; - if(hp.getDefaultValue() != null) { + if (hp.getDefaultValue() != null) { p.defaultValue = hp.getDefaultValue().toString(); } } else if (param instanceof FormParameter) { FormParameter fp = (FormParameter) param; - if(fp.getDefaultValue() != null) { + if (fp.getDefaultValue() != null) { p.defaultValue = fp.getDefaultValue().toString(); } } @@ -2348,8 +2378,11 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { if ("array".equals(type)) { // for array parameter Property inner = qp.getItems(); if (inner == null) { - LOGGER.warn("warning! No inner type supplied for array parameter \"" + qp.getName() + "\", using String"); - inner = new StringProperty().description("//TODO automatically added by swagger-codegen"); + LOGGER.warn("warning! No inner type supplied for array parameter \"" + + qp.getName() + "\", using String"); + inner = + new StringProperty() + .description("//TODO automatically added by swagger-codegen"); } property = new ArrayProperty(inner); collectionFormat = qp.getCollectionFormat(); @@ -2365,8 +2398,11 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { } else if ("object".equals(type)) { // for map parameter Property inner = qp.getItems(); if (inner == null) { - LOGGER.warn("warning! No inner type supplied for map parameter \"" + qp.getName() + "\", using String"); - inner = new StringProperty().description("//TODO automatically added by swagger-codegen"); + LOGGER.warn("warning! No inner type supplied for map parameter \"" + + qp.getName() + "\", using String"); + inner = + new StringProperty() + .description("//TODO automatically added by swagger-codegen"); } property = new MapProperty(inner); collectionFormat = qp.getCollectionFormat(); @@ -2384,8 +2420,12 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { } if (property == null) { - LOGGER.warn("warning! Property type \"" + type + "\" not found for parameter \"" + param.getName() + "\", using String"); - property = new StringProperty().description("//TODO automatically added by swagger-codegen. Type was " + type + " but not supported"); + LOGGER.warn("warning! Property type \"" + type + "\" not found for parameter \"" + + param.getName() + "\", using String"); + property = + new StringProperty() + .description("//TODO automatically added by swagger-codegen. Type was " + + type + " but not supported"); } property.setRequired(param.getRequired()); @@ -2396,7 +2436,7 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { p.dataType = cp.datatype; p.dataFormat = cp.dataFormat; - if(cp.isEnum) { + if (cp.isEnum) { p.datatypeWithEnum = cp.datatypeWithEnum; p.enumName = cp.enumName; } @@ -2414,7 +2454,7 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { p.items = cp.items; } p.collectionFormat = collectionFormat; - if(collectionFormat != null && collectionFormat.equals("multi")) { + if (collectionFormat != null && collectionFormat.equals("multi")) { p.isCollectionFormatMulti = true; } p.paramName = toParamName(qp.getName()); @@ -2427,8 +2467,12 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { // validation // handle maximum, minimum properly for int/long by removing the trailing ".0" if ("integer".equals(qp.getType())) { - p.maximum = qp.getMaximum() == null ? null : String.valueOf(qp.getMaximum().longValue()); - p.minimum = qp.getMinimum() == null ? null : String.valueOf(qp.getMinimum().longValue()); + p.maximum = + qp.getMaximum() == null ? null : String + .valueOf(qp.getMaximum().longValue()); + p.minimum = + qp.getMinimum() == null ? null : String + .valueOf(qp.getMinimum().longValue()); } else { p.maximum = qp.getMaximum() == null ? null : String.valueOf(qp.getMaximum()); p.minimum = qp.getMinimum() == null ? null : String.valueOf(qp.getMinimum()); @@ -2445,10 +2489,9 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { p.multipleOf = qp.getMultipleOf(); // exclusive* are noop without corresponding min/max - if (p.maximum != null || p.minimum != null || - p.maxLength != null || p.minLength != null || - p.maxItems != null || p.minItems != null || - p.pattern != null) { + if (p.maximum != null || p.minimum != null || p.maxLength != null + || p.minLength != null || p.maxItems != null || p.minItems != null + || p.pattern != null) { p.hasValidation = true; } @@ -2540,7 +2583,8 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { p.isBodyParam = true; p.isBinary = isDataTypeBinary(p.dataType); } else if (param instanceof FormParameter) { - if ("file".equalsIgnoreCase(((FormParameter) param).getType()) || "file".equals(p.baseType)) { + if ("file".equalsIgnoreCase(((FormParameter) param).getType()) + || "file".equals(p.baseType)) { p.isFile = true; } else { p.notFile = true; @@ -2607,7 +2651,8 @@ public List fromSecurity(Map } List secs = new ArrayList(schemes.size()); - for (Iterator> it = schemes.entrySet().iterator(); it.hasNext(); ) { + for (Iterator> it = + schemes.entrySet().iterator(); it.hasNext();) { final Map.Entry entry = it.next(); final SecuritySchemeDefinition schemeDefinition = entry.getValue(); @@ -2617,13 +2662,14 @@ public List fromSecurity(Map sec.isCode = sec.isPassword = sec.isApplication = sec.isImplicit = false; if (schemeDefinition instanceof ApiKeyAuthDefinition) { - final ApiKeyAuthDefinition apiKeyDefinition = (ApiKeyAuthDefinition) schemeDefinition; + final ApiKeyAuthDefinition apiKeyDefinition = + (ApiKeyAuthDefinition) schemeDefinition; sec.isBasic = sec.isOAuth = false; sec.isApiKey = true; sec.keyParamName = apiKeyDefinition.getName(); sec.isKeyInHeader = apiKeyDefinition.getIn() == In.HEADER; sec.isKeyInQuery = !sec.isKeyInHeader; - } else if(schemeDefinition instanceof BasicAuthDefinition) { + } else if (schemeDefinition instanceof BasicAuthDefinition) { sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isOAuth = false; sec.isBasic = true; } else { @@ -2634,7 +2680,7 @@ public List fromSecurity(Map if (sec.flow == null) { throw new RuntimeException("missing oauth flow in " + sec.name); } - switch(sec.flow) { + switch (sec.flow) { case "accessCode": sec.isCode = true; break; @@ -2655,7 +2701,8 @@ public List fromSecurity(Map if (oauth2Definition.getScopes() != null) { List> scopes = new ArrayList>(); int count = 0, numScopes = oauth2Definition.getScopes().size(); - for(Map.Entry scopeEntry : oauth2Definition.getScopes().entrySet()) { + for (Map.Entry scopeEntry : oauth2Definition.getScopes() + .entrySet()) { Map scope = new HashMap(); scope.put("scope", scopeEntry.getKey()); scope.put("description", escapeText(scopeEntry.getValue())); @@ -2680,10 +2727,10 @@ public List fromSecurity(Map } protected void setReservedWordsLowerCase(List words) { - reservedWords = new HashSet(); - for (String word : words) { - reservedWords.add(word.toLowerCase()); - } + reservedWords = new HashSet(); + for (String word : words) { + reservedWords.add(word.toLowerCase()); + } } protected boolean isReservedWord(String word) { @@ -2691,7 +2738,8 @@ protected boolean isReservedWord(String word) { } /** - * Get operationId from the operation object, and if it's blank, generate a new one from the given parameters. + * Get operationId from the operation object, and if it's blank, generate a new one from the + * given parameters. * * @param operation the operation object * @param path the path of the operation @@ -2721,7 +2769,8 @@ protected String getOrGenerateOperationId(Operation operation, String path, Stri } } operationId = sanitizeName(builder.toString()); - LOGGER.warn("Empty operationId found for path: " + httpMethod + " " + path + ". Renamed to auto-generated operationId: " + operationId); + LOGGER.warn("Empty operationId found for path: " + httpMethod + " " + path + + ". Renamed to auto-generated operationId: " + operationId); } return operationId; } @@ -2733,8 +2782,7 @@ protected String getOrGenerateOperationId(Operation operation, String path, Stri * @return true if the library/module/package of the corresponding type needs to be imported */ protected boolean needToImport(String type) { - return !defaultIncludes.contains(type) - && !languageSpecificPrimitives.contains(type); + return !defaultIncludes.contains(type) && !languageSpecificPrimitives.contains(type); } @SuppressWarnings("static-method") @@ -2743,7 +2791,8 @@ protected List> toExamples(Map examples) { return null; } - final List> output = new ArrayList>(examples.size()); + final List> output = + new ArrayList>(examples.size()); for (Map.Entry entry : examples.entrySet()) { final Map kv = new HashMap(); kv.put("contentType", entry.getKey()); @@ -2799,7 +2848,8 @@ private static Map addHasMore(Map objs) { * @param operations map of Codegen operations */ @SuppressWarnings("static-method") - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + public void addOperationToGroup(String tag, String resourcePath, Operation operation, + CodegenOperation co, Map> operations) { List opList = operations.get(tag); if (opList == null) { opList = new ArrayList(); @@ -2809,13 +2859,13 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera String uniqueName = co.operationId; int counter = 0; - for(CodegenOperation op : opList) { - if(uniqueName.equals(op.operationId)) { + for (CodegenOperation op : opList) { + if (uniqueName.equals(op.operationId)) { uniqueName = co.operationId + "_" + counter; - counter ++; + counter++; } } - if(!co.operationId.equals(uniqueName)) { + if (!co.operationId.equals(uniqueName)) { LOGGER.warn("generated unique operationId `" + uniqueName + "`"); } co.operationId = uniqueName; @@ -2840,9 +2890,9 @@ private void addParentContainer(CodegenModel m, String name, Property property) } /** - * Underscore the given word. - * Copied from Twitter elephant bird - * https://github.com/twitter/elephant-bird/blob/master/core/src/main/java/com/twitter/elephantbird/util/Strings.java + * Underscore the given word. Copied from Twitter elephant bird + * https://github.com/twitter/elephant + * -bird/blob/master/core/src/main/java/com/twitter/elephantbird/util/Strings.java * * @param word The word * @return The underscored version of the word @@ -2852,7 +2902,8 @@ public static String underscore(String word) { String secondPattern = "([a-z\\d])([A-Z])"; String replacementPattern = "$1_$2"; // Replace package separator with slash. - word = word.replaceAll("\\.", "/"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + word = word.replaceAll("\\.", "/"); // FIXME: a parameter should not be assigned. Also + // declare the methods parameters as 'final'. // Replace $ with two underscores for inner classes. word = word.replaceAll("\\$", "__"); // Replace capital letter with _ plus lowercase letter. @@ -2875,11 +2926,9 @@ protected String dashize(String word) { } /** - * Generate the next name for the given name, i.e. append "2" to the base name if not ending with a number, - * otherwise increase the number by 1. For example: - * status => status2 - * status2 => status3 - * myName100 => myName101 + * Generate the next name for the given name, i.e. append "2" to the base name if not ending + * with a number, otherwise increase the number by 1. For example: status => status2 status2 => + * status3 myName100 => myName101 * * @param name The base name * @return The next name for the base name @@ -2915,8 +2964,9 @@ private void addVars(CodegenModel m, Map properties, List mandatory = required == null ? Collections. emptySet() - : new TreeSet(required); + Set mandatory = + required == null ? Collections.emptySet() : new TreeSet( + required); addVars(m, m.vars, properties, mandatory); m.allMandatory = m.mandatory = mandatory; } else { @@ -2926,20 +2976,23 @@ private void addVars(CodegenModel m, Map properties, List allMandatory = allRequired == null ? Collections. emptySet() - : new TreeSet(allRequired); + Set allMandatory = + allRequired == null ? Collections.emptySet() : new TreeSet( + allRequired); addVars(m, m.allVars, allProperties, allMandatory); m.allMandatory = allMandatory; } } - private void addVars(CodegenModel m, List vars, Map properties, Set mandatory) { + private void addVars(CodegenModel m, List vars, + Map properties, Set mandatory) { // convert set to list so that we can access the next entry in the loop - List> propertyList = new ArrayList>(properties.entrySet()); + List> propertyList = + new ArrayList>(properties.entrySet()); final int totalCount = propertyList.size(); for (int i = 0; i < totalCount; i++) { Map.Entry entry = propertyList.get(i); - + final String key = entry.getKey(); final Property prop = entry.getValue(); @@ -2950,8 +3003,10 @@ private void addVars(CodegenModel m, List vars, Map vars, Map vars, Map() { - @Nullable - @Override - public String apply(String input) { - return StringUtils.capitalize(input); - } - }), ""); + protected String removeNonNameElementToCamelCase(final String name, + final String nonNameElementPattern) { + String result = + StringUtils.join(Lists.transform( + Lists.newArrayList(name.split(nonNameElementPattern)), + new Function() { + @Nullable + @Override + public String apply(String input) { + return StringUtils.capitalize(input); + } + }), ""); if (result.length() > 0) { result = result.substring(0, 1).toLowerCase() + result.substring(1); } @@ -3030,9 +3091,10 @@ public String apply(String input) { } /** - * Camelize name (parameter, property, method, etc) with upper case for first letter - * copied from Twitter elephant bird - * https://github.com/twitter/elephant-bird/blob/master/core/src/main/java/com/twitter/elephantbird/util/Strings.java + * Camelize name (parameter, property, method, etc) with upper case for first letter copied from + * Twitter elephant bird + * https://github.com/twitter/elephant-bird/blob/master/core/src/main/java/ + * com/twitter/elephantbird/util/Strings.java * * @param word string to be camelize * @return camelized string @@ -3053,7 +3115,10 @@ public static String camelize(String word, boolean lowercaseFirstLetter) { Pattern p = Pattern.compile("\\/(.?)"); Matcher m = p.matcher(word); while (m.find()) { - word = m.replaceFirst("." + m.group(1)/*.toUpperCase()*/); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + word = m.replaceFirst("." + m.group(1)/*.toUpperCase()*/); // FIXME: a parameter should + // not be assigned. Also + // declare the methods + // parameters as 'final'. m = p.matcher(word); } @@ -3069,7 +3134,9 @@ public static String camelize(String word, boolean lowercaseFirstLetter) { m = p.matcher(word); while (m.find()) { - word = m.replaceFirst("" + Character.toUpperCase(m.group(1).charAt(0)) + m.group(1).substring(1)/*.toUpperCase()*/); + word = + m.replaceFirst("" + Character.toUpperCase(m.group(1).charAt(0)) + + m.group(1).substring(1)/*.toUpperCase()*/); m = p.matcher(word); } @@ -3141,8 +3208,8 @@ public void setSkipOverwrite(boolean skipOverwrite) { } /** - * All library templates supported. - * (key: library name, value: library description) + * All library templates supported. (key: library name, value: library description) + * * @return the supported libraries */ public Map supportedLibraries() { @@ -3152,7 +3219,7 @@ public Map supportedLibraries() { /** * Set library template (sub-template). * - * @param library Library template + * @param library Library template */ public void setLibrary(String library) { if (library != null && !supportedLibraries.containsKey(library)) @@ -3172,7 +3239,7 @@ public String getLibrary() { /** * Set Git user ID. * - * @param gitUserId Git user ID + * @param gitUserId Git user ID */ public void setGitUserId(String gitUserId) { this.gitUserId = gitUserId; @@ -3190,7 +3257,7 @@ public String getGitUserId() { /** * Set Git repo ID. * - * @param gitRepoId Git repo ID + * @param gitRepoId Git repo ID */ public void setGitRepoId(String gitRepoId) { this.gitRepoId = gitRepoId; @@ -3233,7 +3300,7 @@ public void setHttpUserAgent(String httpUserAgent) { } /** - * HTTP user agent + * HTTP user agent * * @return HTTP user agent */ @@ -3275,7 +3342,8 @@ public String sanitizeName(String name) { } // input[] => input - name = name.replaceAll("\\[\\]", ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = name.replaceAll("\\[\\]", ""); // FIXME: a parameter should not be assigned. Also + // declare the methods parameters as 'final'. // input[a][b] => input_a_b name = name.replaceAll("\\[", "_"); @@ -3296,10 +3364,11 @@ public String sanitizeName(String name) { // remove everything else other than word, number and _ // $php_variable => php_variable - if (allowUnicodeIdentifiers) { //could be converted to a single line with ?: operator - name = Pattern.compile("\\W", Pattern.UNICODE_CHARACTER_CLASS).matcher(name).replaceAll(""); - } - else { + if (allowUnicodeIdentifiers) { // could be converted to a single line with ?: operator + name = + Pattern.compile("\\W", Pattern.UNICODE_CHARACTER_CLASS).matcher(name) + .replaceAll(""); + } else { name = name.replaceAll("\\W", ""); } @@ -3338,20 +3407,20 @@ public String sanitizeTag(String tag) { public void writeOptional(String outputFolder, SupportingFile supportingFile) { String folder = ""; - if(outputFolder != null && !"".equals(outputFolder)) { + if (outputFolder != null && !"".equals(outputFolder)) { folder += outputFolder + File.separator; } folder += supportingFile.folder; - if(!"".equals(folder)) { + if (!"".equals(folder)) { folder += File.separator + supportingFile.destinationFilename; - } - else { + } else { folder = supportingFile.destinationFilename; } - if(!new File(folder).exists()) { + if (!new File(folder).exists()) { supportingFiles.add(supportingFile); } else { - LOGGER.info("Skipped overwriting " + supportingFile.destinationFilename + " as the file already exists in " + folder); + LOGGER.info("Skipped overwriting " + supportingFile.destinationFilename + + " as the file already exists in " + folder); } } @@ -3359,9 +3428,10 @@ public void writeOptional(String outputFolder, SupportingFile supportingFile) { * Set CodegenParameter boolean flag using CodegenProperty. * * @param parameter Codegen Parameter - * @param property Codegen property + * @param property Codegen property */ - public void setParameterBooleanFlagWithCodegenProperty(CodegenParameter parameter, CodegenProperty property) { + public void setParameterBooleanFlagWithCodegenProperty(CodegenParameter parameter, + CodegenProperty property) { if (parameter == null) { LOGGER.error("Codegen Parameter cannot be null."); return; @@ -3399,7 +3469,7 @@ public void setParameterBooleanFlagWithCodegenProperty(CodegenParameter paramete } else if (Boolean.TRUE.equals(property.isFile)) { parameter.isFile = true; // file is *not* a primitive type - //parameter.isPrimitiveType = true; + // parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isDate)) { parameter.isDate = true; parameter.isPrimitiveType = true; @@ -3471,8 +3541,8 @@ public void updateCodegenPropertyEnum(CodegenProperty var) { } /** - * If the pattern misses the delimiter, add "/" to the beginning and end - * Otherwise, return the original pattern + * If the pattern misses the delimiter, add "/" to the beginning and end Otherwise, return the + * original pattern * * @param pattern the pattern (regular expression) * @return the pattern with delimiter @@ -3485,9 +3555,8 @@ public String addRegularExpressionDelimiter(String pattern) { } /** - * reads propertyKey from additionalProperties, converts it to a boolean and - * writes it back to additionalProperties to be usable as a boolean in - * mustache files. + * reads propertyKey from additionalProperties, converts it to a boolean and writes it back to + * additionalProperties to be usable as a boolean in mustache files. * * @param propertyKey * @return property value as boolean @@ -3515,7 +3584,8 @@ public String getIgnoreFilePathOverride() { } /** - * Sets an override location for the .swagger-codegen.ignore location for the first code generation. + * Sets an override location for the .swagger-codegen.ignore location for the first code + * generation. * * @param ignoreFileOverride The full path to an ignore file */ @@ -3531,7 +3601,7 @@ public boolean convertPropertyToBoolean(String propertyKey) { return booleanValue; } - + public void writePropertyBack(String propertyKey, boolean value) { additionalProperties.put(propertyKey, value); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index f6983d0340f..14762190225 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -44,16 +44,18 @@ public Generator opts(ClientOptInput opts) { this.config.additionalProperties().putAll(opts.getOpts().getProperties()); String ignoreFileLocation = this.config.getIgnoreFilePathOverride(); - if(ignoreFileLocation != null) { + if (ignoreFileLocation != null) { final File ignoreFile = new File(ignoreFileLocation); - if(ignoreFile.exists() && ignoreFile.canRead()) { + if (ignoreFile.exists() && ignoreFile.canRead()) { this.ignoreProcessor = new CodegenIgnoreProcessor(ignoreFile); } else { - LOGGER.warn("Ignore file specified at {} is not valid. This will fall back to an existing ignore file if present in the output directory.", ignoreFileLocation); + LOGGER.warn( + "Ignore file specified at {} is not valid. This will fall back to an existing ignore file if present in the output directory.", + ignoreFileLocation); } } - if(this.ignoreProcessor == null) { + if (this.ignoreProcessor == null) { this.ignoreProcessor = new CodegenIgnoreProcessor(this.config.getOutputDir()); } @@ -71,7 +73,7 @@ private String getScheme() { return scheme; } - private String getHost(){ + private String getHost() { StringBuilder hostBuilder = new StringBuilder(); hostBuilder.append(getScheme()); hostBuilder.append("://"); @@ -89,36 +91,46 @@ private String getHost(){ private void configureGeneratorProperties() { // allows generating only models by specifying a CSV of models to generate, or empty for all - generateApis = System.getProperty("apis") != null ? true:null; - generateModels = System.getProperty("models") != null ? true: null; - generateSupportingFiles = System.getProperty("supportingFiles") != null ? true:null; + generateApis = System.getProperty("apis") != null ? true : null; + generateModels = System.getProperty("models") != null ? true : null; + generateSupportingFiles = System.getProperty("supportingFiles") != null ? true : null; if (generateApis == null && generateModels == null && generateSupportingFiles == null) { // no specifics are set, generate everything generateApis = generateModels = generateSupportingFiles = true; } else { - if(generateApis == null) { + if (generateApis == null) { generateApis = false; } - if(generateModels == null) { + if (generateModels == null) { generateModels = false; } - if(generateSupportingFiles == null) { + if (generateSupportingFiles == null) { generateSupportingFiles = false; } } - // model/api tests and documentation options rely on parent generate options (api or model) and no other options. + // model/api tests and documentation options rely on parent generate options (api or model) + // and no other options. // They default to true in all scenarios and can only be marked false explicitly - generateModelTests = System.getProperty("modelTests") != null ? Boolean.valueOf(System.getProperty("modelTests")): true; - generateModelDocumentation = System.getProperty("modelDocs") != null ? Boolean.valueOf(System.getProperty("modelDocs")):true; - generateApiTests = System.getProperty("apiTests") != null ? Boolean.valueOf(System.getProperty("apiTests")): true; - generateApiDocumentation = System.getProperty("apiDocs") != null ? Boolean.valueOf(System.getProperty("apiDocs")):true; + generateModelTests = + System.getProperty("modelTests") != null ? Boolean.valueOf(System + .getProperty("modelTests")) : true; + generateModelDocumentation = + System.getProperty("modelDocs") != null ? Boolean.valueOf(System + .getProperty("modelDocs")) : true; + generateApiTests = + System.getProperty("apiTests") != null ? Boolean.valueOf(System + .getProperty("apiTests")) : true; + generateApiDocumentation = + System.getProperty("apiDocs") != null ? Boolean.valueOf(System + .getProperty("apiDocs")) : true; // Additional properties added for tests to exclude references in project related files config.additionalProperties().put(CodegenConstants.GENERATE_API_TESTS, generateApiTests); - config.additionalProperties().put(CodegenConstants.GENERATE_MODEL_TESTS, generateModelTests); - if(!generateApiTests && !generateModelTests) { + config.additionalProperties() + .put(CodegenConstants.GENERATE_MODEL_TESTS, generateModelTests); + if (!generateApiTests && !generateModelTests) { config.additionalProperties().put(CodegenConstants.EXCLUDE_TESTS, true); } if (System.getProperty("debugSwagger") != null) { @@ -152,11 +164,15 @@ private void configureSwaggerInfo() { } if (StringUtils.isEmpty(info.getDescription())) { // set a default description if none if provided - config.additionalProperties().put("appDescription", - "No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)"); - config.additionalProperties().put("unescapedAppDescription", "No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)"); + config.additionalProperties() + .put("appDescription", + "No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)"); + config.additionalProperties() + .put("unescapedAppDescription", + "No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)"); } else { - config.additionalProperties().put("appDescription", config.escapeText(info.getDescription())); + config.additionalProperties().put("appDescription", + config.escapeText(info.getDescription())); config.additionalProperties().put("unescapedAppDescription", info.getDescription()); } @@ -164,31 +180,38 @@ private void configureSwaggerInfo() { Contact contact = info.getContact(); config.additionalProperties().put("infoUrl", config.escapeText(contact.getUrl())); if (contact.getEmail() != null) { - config.additionalProperties().put("infoEmail", config.escapeText(contact.getEmail())); + config.additionalProperties().put("infoEmail", + config.escapeText(contact.getEmail())); } } if (info.getLicense() != null) { License license = info.getLicense(); if (license.getName() != null) { - config.additionalProperties().put("licenseInfo", config.escapeText(license.getName())); + config.additionalProperties().put("licenseInfo", + config.escapeText(license.getName())); } if (license.getUrl() != null) { - config.additionalProperties().put("licenseUrl", config.escapeText(license.getUrl())); + config.additionalProperties() + .put("licenseUrl", config.escapeText(license.getUrl())); } } if (info.getVersion() != null) { config.additionalProperties().put("version", config.escapeText(info.getVersion())); } if (info.getTermsOfService() != null) { - config.additionalProperties().put("termsOfService", config.escapeText(info.getTermsOfService())); + config.additionalProperties().put("termsOfService", + config.escapeText(info.getTermsOfService())); } } - private void generateModelTests(List files, Map models, String modelName) throws IOException{ + private void generateModelTests(List files, Map models, String modelName) + throws IOException { // to generate model test files for (String templateName : config.modelTestTemplateFiles().keySet()) { String suffix = config.modelTestTemplateFiles().get(templateName); - String filename = config.modelTestFileFolder() + File.separator + config.toModelTestFilename(modelName) + suffix; + String filename = + config.modelTestFileFolder() + File.separator + + config.toModelTestFilename(modelName) + suffix; // do not overwrite test file that already exists if (new File(filename).exists()) { LOGGER.info("File exists. Skipped overwriting " + filename); @@ -201,10 +224,13 @@ private void generateModelTests(List files, Map models, St } } - private void generateModelDocumentation(List files, Map models, String modelName) throws IOException { + private void generateModelDocumentation(List files, Map models, + String modelName) throws IOException { for (String templateName : config.modelDocTemplateFiles().keySet()) { String suffix = config.modelDocTemplateFiles().get(templateName); - String filename = config.modelDocFileFolder() + File.separator + config.toModelDocFilename(modelName) + suffix; + String filename = + config.modelDocFileFolder() + File.separator + + config.toModelDocFilename(modelName) + suffix; if (!config.shouldOverwrite(filename)) { LOGGER.info("Skipped overwriting " + filename); continue; @@ -229,15 +255,15 @@ private void generateModels(List files, List allModels) { String modelNames = System.getProperty("models"); Set modelsToGenerate = null; - if(modelNames != null && !modelNames.isEmpty()) { + if (modelNames != null && !modelNames.isEmpty()) { modelsToGenerate = new HashSet(Arrays.asList(modelNames.split(","))); } Set modelKeys = definitions.keySet(); - if(modelsToGenerate != null && !modelsToGenerate.isEmpty()) { + if (modelsToGenerate != null && !modelsToGenerate.isEmpty()) { Set updatedKeys = new HashSet(); - for(String m : modelKeys) { - if(modelsToGenerate.contains(m)) { + for (String m : modelKeys) { + if (modelsToGenerate.contains(m)) { updatedKeys.add(m); } } @@ -245,53 +271,55 @@ private void generateModels(List files, List allModels) { } // store all processed models - Map allProcessedModels = new TreeMap(new Comparator() { - @Override - public int compare(String o1, String o2) { - Model model1 = definitions.get(o1); - Model model2 = definitions.get(o2); - - int model1InheritanceDepth = getInheritanceDepth(model1); - int model2InheritanceDepth = getInheritanceDepth(model2); - - if (model1InheritanceDepth == model2InheritanceDepth) { - return ObjectUtils.compare(config.toModelName(o1), config.toModelName(o2)); - } else if (model1InheritanceDepth > model2InheritanceDepth) { - return 1; - } else { - return -1; - } - } - - private int getInheritanceDepth(Model model) { - int inheritanceDepth = 0; - Model parent = getParent(model); + Map allProcessedModels = + new TreeMap(new Comparator() { + @Override + public int compare(String o1, String o2) { + Model model1 = definitions.get(o1); + Model model2 = definitions.get(o2); + + int model1InheritanceDepth = getInheritanceDepth(model1); + int model2InheritanceDepth = getInheritanceDepth(model2); + + if (model1InheritanceDepth == model2InheritanceDepth) { + return ObjectUtils.compare(config.toModelName(o1), + config.toModelName(o2)); + } else if (model1InheritanceDepth > model2InheritanceDepth) { + return 1; + } else { + return -1; + } + } - while (parent != null) { - inheritanceDepth++; - parent = getParent(parent); - } + private int getInheritanceDepth(Model model) { + int inheritanceDepth = 0; + Model parent = getParent(model); - return inheritanceDepth; - } + while (parent != null) { + inheritanceDepth++; + parent = getParent(parent); + } - private Model getParent(Model model) { - if (model instanceof ComposedModel) { - Model parent = ((ComposedModel) model).getParent(); - if(parent != null) { - return definitions.get(parent.getReference()); + return inheritanceDepth; } - } - return null; - } - }); + private Model getParent(Model model) { + if (model instanceof ComposedModel) { + Model parent = ((ComposedModel) model).getParent(); + if (parent != null) { + return definitions.get(parent.getReference()); + } + } + + return null; + } + }); // process models only for (String name : modelKeys) { try { - //don't generate models that have an import mapping - if(config.importMapping().containsKey(name)) { + // don't generate models that have an import mapping + if (config.importMapping().containsKey(name)) { LOGGER.info("Model " + name + " not imported due to import mapping"); continue; } @@ -303,7 +331,8 @@ private Model getParent(Model model) { models.putAll(config.additionalProperties()); allProcessedModels.put(name, models); } catch (Exception e) { - throw new RuntimeException("Could not process model '" + name + "'" + ".Please make sure that your schema is correct!", e); + throw new RuntimeException("Could not process model '" + name + "'" + + ".Please make sure that your schema is correct!", e); } } @@ -311,30 +340,32 @@ private Model getParent(Model model) { allProcessedModels = config.postProcessAllModels(allProcessedModels); // generate files based on processed models - for (String modelName: allProcessedModels.keySet()) { - Map models = (Map)allProcessedModels.get(modelName); + for (String modelName : allProcessedModels.keySet()) { + Map models = (Map) allProcessedModels.get(modelName); try { - //don't generate models that have an import mapping - if(config.importMapping().containsKey(modelName)) { + // don't generate models that have an import mapping + if (config.importMapping().containsKey(modelName)) { continue; } allModels.add(((List) models.get("models")).get(0)); for (String templateName : config.modelTemplateFiles().keySet()) { String suffix = config.modelTemplateFiles().get(templateName); - String filename = config.modelFileFolder() + File.separator + config.toModelFilename(modelName) + suffix; + String filename = + config.modelFileFolder() + File.separator + + config.toModelFilename(modelName) + suffix; if (!config.shouldOverwrite(filename)) { LOGGER.info("Skipped overwriting " + filename); continue; } File written = processTemplateToFile(models, templateName, filename); - if(written != null) { + if (written != null) { files.add(written); } } - if(generateModelTests) { + if (generateModelTests) { generateModelTests(files, models, modelName); } - if(generateModelDocumentation) { + if (generateModelDocumentation) { // to generate model documentation files generateModelDocumentation(files, models, modelName); } @@ -356,13 +387,14 @@ private void generateApis(List files, List allOperations) { Map> paths = processPaths(swagger.getPaths()); Set apisToGenerate = null; String apiNames = System.getProperty("apis"); - if(apiNames != null && !apiNames.isEmpty()) { + if (apiNames != null && !apiNames.isEmpty()) { apisToGenerate = new HashSet(Arrays.asList(apiNames.split(","))); } - if(apisToGenerate != null && !apisToGenerate.isEmpty()) { - Map> updatedPaths = new TreeMap>(); - for(String m : paths.keySet()) { - if(apisToGenerate.contains(m)) { + if (apisToGenerate != null && !apisToGenerate.isEmpty()) { + Map> updatedPaths = + new TreeMap>(); + for (String m : paths.keySet()) { + if (apisToGenerate.contains(m)) { updatedPaths.put(m, paths.get(m)); } } @@ -390,14 +422,17 @@ public int compare(CodegenOperation one, CodegenOperation another) { operation.put("importPath", config.toApiImport(tag)); operation.put("classFilename", config.toApiFilename(tag)); - if(!config.vendorExtensions().isEmpty()) { + if (!config.vendorExtensions().isEmpty()) { operation.put("vendorExtensions", config.vendorExtensions()); } // Pass sortParamsByRequiredFlag through to the Mustache template... boolean sortParamsByRequiredFlag = true; - if (this.config.additionalProperties().containsKey(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) { - sortParamsByRequiredFlag = Boolean.valueOf(this.config.additionalProperties().get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString()); + if (this.config.additionalProperties().containsKey( + CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) { + sortParamsByRequiredFlag = + Boolean.valueOf(this.config.additionalProperties() + .get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString()); } operation.put("sortParamsByRequiredFlag", sortParamsByRequiredFlag); @@ -420,12 +455,12 @@ public int compare(CodegenOperation one, CodegenOperation another) { } File written = processTemplateToFile(operation, templateName, filename); - if(written != null) { + if (written != null) { files.add(written); } } - if(generateApiTests) { + if (generateApiTests) { // to generate api test files for (String templateName : config.apiTestTemplateFiles().keySet()) { String filename = config.apiTestFilename(templateName, tag); @@ -443,7 +478,7 @@ public int compare(CodegenOperation one, CodegenOperation another) { } - if(generateApiDocumentation) { + if (generateApiDocumentation) { // to generate api documentation files for (String templateName : config.apiDocTemplateFiles().keySet()) { String filename = config.apiDocFilename(templateName, tag); @@ -476,8 +511,9 @@ private void generateSupportingFiles(List files, Map bundl } Set supportingFilesToGenerate = null; String supportingFiles = System.getProperty("supportingFiles"); - if(supportingFiles!= null && !supportingFiles.isEmpty()) { - supportingFilesToGenerate = new HashSet(Arrays.asList(supportingFiles.split(","))); + if (supportingFiles != null && !supportingFiles.isEmpty()) { + supportingFilesToGenerate = + new HashSet(Arrays.asList(supportingFiles.split(","))); } for (SupportingFile support : config.supportingFiles()) { @@ -490,39 +526,41 @@ private void generateSupportingFiles(List files, Map bundl if (!of.isDirectory()) { of.mkdirs(); } - String outputFilename = outputFolder + File.separator + support.destinationFilename.replace('/', File.separatorChar); + String outputFilename = + outputFolder + File.separator + + support.destinationFilename.replace('/', File.separatorChar); if (!config.shouldOverwrite(outputFilename)) { LOGGER.info("Skipped overwriting " + outputFilename); continue; } String templateFile; - if( support instanceof GlobalSupportingFile) { - templateFile = config.getCommonTemplateDir() + File.separator + support.templateFile; + if (support instanceof GlobalSupportingFile) { + templateFile = + config.getCommonTemplateDir() + File.separator + support.templateFile; } else { templateFile = getFullTemplateFile(config, support.templateFile); } boolean shouldGenerate = true; - if(supportingFilesToGenerate != null && !supportingFilesToGenerate.isEmpty()) { - shouldGenerate = supportingFilesToGenerate.contains(support.destinationFilename); + if (supportingFilesToGenerate != null && !supportingFilesToGenerate.isEmpty()) { + shouldGenerate = + supportingFilesToGenerate.contains(support.destinationFilename); } - if (!shouldGenerate){ + if (!shouldGenerate) { continue; } - if(ignoreProcessor.allowsFile(new File(outputFilename))) { + if (ignoreProcessor.allowsFile(new File(outputFilename))) { if (templateFile.endsWith("mustache")) { String template = readTemplate(templateFile); Mustache.Compiler compiler = Mustache.compiler(); compiler = config.processCompiler(compiler); - Template tmpl = compiler - .withLoader(new Mustache.TemplateLoader() { - @Override - public Reader getTemplate(String name) { - return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); - } - }) - .defaultValue("") - .compile(template); + Template tmpl = compiler.withLoader(new Mustache.TemplateLoader() { + @Override + public Reader getTemplate(String name) { + return getTemplateReader(getFullTemplateFile(config, name + + ".mustache")); + } + }).defaultValue("").compile(template); writeToFile(outputFilename, tmpl.execute(bundle)); files.add(new File(outputFilename)); @@ -535,7 +573,9 @@ public Reader getTemplate(String name) { // continue } if (in == null) { - in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(templateFile)); + in = + this.getClass().getClassLoader() + .getResourceAsStream(getCPResourcePath(templateFile)); } File outputFile = new File(outputFilename); OutputStream out = new FileOutputStream(outputFile, false); @@ -549,25 +589,31 @@ public Reader getTemplate(String name) { files.add(outputFile); } } else { - LOGGER.info("Skipped generation of " + outputFilename + " due to rule in .swagger-codegen-ignore"); + LOGGER.info("Skipped generation of " + outputFilename + + " due to rule in .swagger-codegen-ignore"); } } catch (Exception e) { - throw new RuntimeException("Could not generate supporting file '" + support + "'", e); + throw new RuntimeException("Could not generate supporting file '" + support + "'", + e); } } // Consider .swagger-codegen-ignore a supporting file - // Output .swagger-codegen-ignore if it doesn't exist and wasn't explicitly created by a generator + // Output .swagger-codegen-ignore if it doesn't exist and wasn't explicitly created by a + // generator final String swaggerCodegenIgnore = ".swagger-codegen-ignore"; String ignoreFileNameTarget = config.outputFolder() + File.separator + swaggerCodegenIgnore; File ignoreFile = new File(ignoreFileNameTarget); - if(!ignoreFile.exists()) { - String ignoreFileNameSource = File.separator + config.getCommonTemplateDir() + File.separator + swaggerCodegenIgnore; + if (!ignoreFile.exists()) { + String ignoreFileNameSource = + File.separator + config.getCommonTemplateDir() + File.separator + + swaggerCodegenIgnore; String ignoreFileContents = readResourceContents(ignoreFileNameSource); try { writeToFile(ignoreFileNameTarget, ignoreFileContents); } catch (IOException e) { - throw new RuntimeException("Could not generate supporting file '" + swaggerCodegenIgnore + "'", e); + throw new RuntimeException("Could not generate supporting file '" + + swaggerCodegenIgnore + "'", e); } files.add(ignoreFile); } @@ -592,7 +638,8 @@ public Reader getTemplate(String name) { } - private Map buildSupportFileBundle(List allOperations, List allModels) { + private Map buildSupportFileBundle(List allOperations, + List allModels) { Map bundle = new HashMap(); bundle.putAll(config.additionalProperties()); @@ -607,7 +654,7 @@ private Map buildSupportFileBundle(List allOperations, L bundle.put("swagger", this.swagger); bundle.put("basePath", basePath); - bundle.put("basePathWithoutHost",basePathWithoutHost); + bundle.put("basePathWithoutHost", basePathWithoutHost); bundle.put("scheme", getScheme()); bundle.put("contextPath", contextPath); bundle.put("apiInfo", apis); @@ -672,33 +719,34 @@ public List generate() { return files; } - private File processTemplateToFile(Map templateData, String templateName, String outputFilename) throws IOException { - String adjustedOutputFilename = outputFilename.replaceAll("//", "/").replace('/', File.separatorChar); - if(ignoreProcessor.allowsFile(new File(adjustedOutputFilename))) { + private File processTemplateToFile(Map templateData, String templateName, + String outputFilename) throws IOException { + String adjustedOutputFilename = + outputFilename.replaceAll("//", "/").replace('/', File.separatorChar); + if (ignoreProcessor.allowsFile(new File(adjustedOutputFilename))) { String templateFile = getFullTemplateFile(config, templateName); String template = readTemplate(templateFile); Mustache.Compiler compiler = Mustache.compiler(); compiler = config.processCompiler(compiler); - Template tmpl = compiler - .withLoader(new Mustache.TemplateLoader() { - @Override - public Reader getTemplate(String name) { - return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); - } - }) - .defaultValue("") - .compile(template); + Template tmpl = compiler.withLoader(new Mustache.TemplateLoader() { + @Override + public Reader getTemplate(String name) { + return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); + } + }).defaultValue("").compile(template); writeToFile(adjustedOutputFilename, tmpl.execute(templateData)); return new File(adjustedOutputFilename); } - LOGGER.info("Skipped generation of " + adjustedOutputFilename + " due to rule in .swagger-codegen-ignore"); + LOGGER.info("Skipped generation of " + adjustedOutputFilename + + " due to rule in .swagger-codegen-ignore"); return null; } - private static void processMimeTypes(List mimeTypeList, Map operation, String source) { - if (mimeTypeList == null || mimeTypeList.isEmpty()){ + private static void processMimeTypes(List mimeTypeList, Map operation, + String source) { + if (mimeTypeList == null || mimeTypeList.isEmpty()) { return; } List> c = new ArrayList>(); @@ -735,12 +783,14 @@ public Map> processPaths(Map paths) return ops; } - private void processOperation(String resourcePath, String httpMethod, Operation operation, Map> operations, Path path) { + private void processOperation(String resourcePath, String httpMethod, Operation operation, + Map> operations, Path path) { if (operation == null) { return; } if (System.getProperty("debugOperations") != null) { - LOGGER.info("processOperation: resourcePath= " + resourcePath + "\t;" + httpMethod + " " + operation + "\n"); + LOGGER.info("processOperation: resourcePath= " + resourcePath + "\t;" + httpMethod + + " " + operation + "\n"); } List tags = operation.getTags(); if (tags == null) { @@ -759,10 +809,11 @@ private void processOperation(String resourcePath, String httpMethod, Operation } } - //need to propagate path level down to the operation + // need to propagate path level down to the operation if (path.getParameters() != null) { for (Parameter parameter : path.getParameters()) { - //skip propagation if a parameter with the same name is already defined at the operation level + // skip propagation if a parameter with the same name is already defined at the + // operation level if (!operationParameters.contains(generateParameterId(parameter))) { operation.addParameter(parameter); } @@ -771,10 +822,13 @@ private void processOperation(String resourcePath, String httpMethod, Operation for (String tag : tags) { try { - CodegenOperation codegenOperation = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions(), swagger); + CodegenOperation codegenOperation = + config.fromOperation(resourcePath, httpMethod, operation, + swagger.getDefinitions(), swagger); codegenOperation.tags = new ArrayList(); codegenOperation.tags.add(config.sanitizeTag(tag)); - config.addOperationToGroup(config.sanitizeTag(tag), resourcePath, operation, codegenOperation, operations); + config.addOperationToGroup(config.sanitizeTag(tag), resourcePath, operation, + codegenOperation, operations); List>> securities = operation.getSecurity(); if (securities == null && swagger.getSecurity() != null) { @@ -786,24 +840,29 @@ private void processOperation(String resourcePath, String httpMethod, Operation if (securities == null || swagger.getSecurityDefinitions() == null) { continue; } - Map authMethods = new HashMap(); - for (Map> security: securities) { + Map authMethods = + new HashMap(); + for (Map> security : securities) { for (String securityName : security.keySet()) { - SecuritySchemeDefinition securityDefinition = swagger.getSecurityDefinitions().get(securityName); + SecuritySchemeDefinition securityDefinition = + swagger.getSecurityDefinitions().get(securityName); if (securityDefinition == null) { continue; } if (securityDefinition instanceof OAuth2Definition) { - OAuth2Definition oauth2Definition = (OAuth2Definition) securityDefinition; + OAuth2Definition oauth2Definition = + (OAuth2Definition) securityDefinition; OAuth2Definition oauth2Operation = new OAuth2Definition(); oauth2Operation.setType(oauth2Definition.getType()); - oauth2Operation.setAuthorizationUrl(oauth2Definition.getAuthorizationUrl()); + oauth2Operation.setAuthorizationUrl(oauth2Definition + .getAuthorizationUrl()); oauth2Operation.setFlow(oauth2Definition.getFlow()); oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl()); oauth2Operation.setScopes(new HashMap()); for (String scope : security.get(securityName)) { if (oauth2Definition.getScopes().containsKey(scope)) { - oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope)); + oauth2Operation.addScope(scope, oauth2Definition.getScopes() + .get(scope)); } } authMethods.put(securityName, oauth2Operation); @@ -816,13 +875,12 @@ private void processOperation(String resourcePath, String httpMethod, Operation codegenOperation.authMethods = config.fromSecurity(authMethods); codegenOperation.hasAuthMethods = true; } - } - catch (Exception ex) { + } catch (Exception ex) { String msg = "Could not process operation:\n" // + " Tag: " + tag + "\n"// + " Operation: " + operation.getOperationId() + "\n" // + " Resource: " + httpMethod + " " + resourcePath + "\n"// - + " Definitions: " + swagger.getDefinitions() + "\n" // + + " Definitions: " + swagger.getDefinitions() + "\n" // + " Exception: " + ex.getMessage(); throw new RuntimeException(msg, ex); } @@ -835,7 +893,8 @@ private static String generateParameterId(Parameter parameter) { } - private Map processOperations(CodegenConfig config, String tag, List ops) { + private Map processOperations(CodegenConfig config, String tag, + List ops) { Map operations = new HashMap(); Map objs = new HashMap(); objs.put("classname", config.toApiName(tag)); @@ -895,7 +954,8 @@ private Map processOperations(CodegenConfig config, String tag, } - private Map processModels(CodegenConfig config, Map definitions, Map allDefinitions) { + private Map processModels(CodegenConfig config, Map definitions, + Map allDefinitions) { Map objs = new HashMap(); objs.put("package", config.modelPackage()); List models = new ArrayList(); @@ -927,7 +987,7 @@ private Map processModels(CodegenConfig config, Map> imports = new ArrayList>(); - for(String s: importSet) { + for (String s : importSet) { Map item = new HashMap(); item.put("import", s); imports.add(item); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Generator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Generator.java index 926eb54b2b7..4618a02a989 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Generator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Generator.java @@ -7,4 +7,4 @@ public interface Generator { Generator opts(ClientOptInput opts); List generate(); -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java index 34b0906fd10..d4cd27da1c8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java @@ -48,9 +48,12 @@ public void flatten(Swagger swagger) { if (model instanceof ModelImpl) { ModelImpl obj = (ModelImpl) model; if (obj.getType() == null || "object".equals(obj.getType())) { - if (obj.getProperties() != null && obj.getProperties().size() > 0) { + if (obj.getProperties() != null + && obj.getProperties().size() > 0) { flattenProperties(obj.getProperties(), pathname); - String modelName = resolveModelName(obj.getTitle(), bp.getName()); + String modelName = + resolveModelName(obj.getTitle(), + bp.getName()); bp.setSchema(new RefModel(modelName)); addGenerated(modelName, model); swagger.addDefinition(modelName, model); @@ -62,9 +65,12 @@ public void flatten(Swagger swagger) { if (inner instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) inner; - if (op.getProperties() != null && op.getProperties().size() > 0) { + if (op.getProperties() != null + && op.getProperties().size() > 0) { flattenProperties(op.getProperties(), pathname); - String modelName = resolveModelName(op.getTitle(), bp.getName()); + String modelName = + resolveModelName(op.getTitle(), + bp.getName()); Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { @@ -90,13 +96,17 @@ public void flatten(Swagger swagger) { if (property instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) property; if (op.getProperties() != null && op.getProperties().size() > 0) { - String modelName = resolveModelName(op.getTitle(), "inline_response_" + key); + String modelName = + resolveModelName(op.getTitle(), "inline_response_" + + key); Model model = modelFromProperty(op, modelName); String existing = matchGenerated(model); if (existing != null) { - response.setSchema(this.makeRefProperty(existing, property)); + response.setSchema(this.makeRefProperty(existing, + property)); } else { - response.setSchema(this.makeRefProperty(modelName, property)); + response.setSchema(this.makeRefProperty(modelName, + property)); addGenerated(modelName, model); swagger.addDefinition(modelName, model); } @@ -107,10 +117,12 @@ public void flatten(Swagger swagger) { if (inner instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) inner; - if (op.getProperties() != null && op.getProperties().size() > 0) { + if (op.getProperties() != null + && op.getProperties().size() > 0) { flattenProperties(op.getProperties(), pathname); - String modelName = resolveModelName(op.getTitle(), - "inline_response_" + key); + String modelName = + resolveModelName(op.getTitle(), + "inline_response_" + key); Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { @@ -128,16 +140,19 @@ public void flatten(Swagger swagger) { Property innerProperty = mp.getAdditionalProperties(); if (innerProperty instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) innerProperty; - if (op.getProperties() != null && op.getProperties().size() > 0) { + if (op.getProperties() != null + && op.getProperties().size() > 0) { flattenProperties(op.getProperties(), pathname); - String modelName = resolveModelName(op.getTitle(), - "inline_response_" + key); + String modelName = + resolveModelName(op.getTitle(), + "inline_response_" + key); Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { mp.setAdditionalProperties(new RefProperty(existing)); } else { - mp.setAdditionalProperties(new RefProperty(modelName)); + mp.setAdditionalProperties(new RefProperty( + modelName)); addGenerated(modelName, innerModel); swagger.addDefinition(modelName, innerModel); } @@ -168,7 +183,8 @@ public void flatten(Swagger swagger) { if (inner instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) inner; if (op.getProperties() != null && op.getProperties().size() > 0) { - String innerModelName = resolveModelName(op.getTitle(), modelName + "_inner"); + String innerModelName = + resolveModelName(op.getTitle(), modelName + "_inner"); Model innerModel = modelFromProperty(op, innerModelName); String existing = matchGenerated(innerModel); if (existing == null) { @@ -245,7 +261,8 @@ public void flattenProperties(Map properties, String path) { Map modelsToAdd = new HashMap(); for (String key : properties.keySet()) { Property property = properties.get(key); - if (property instanceof ObjectProperty && ((ObjectProperty) property).getProperties() != null + if (property instanceof ObjectProperty + && ((ObjectProperty) property).getProperties() != null && ((ObjectProperty) property).getProperties().size() > 0) { ObjectProperty op = (ObjectProperty) property; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java index 45eb05e56fb..61c31d6f69c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java @@ -21,8 +21,8 @@ import java.util.ServiceLoader; /** - * @deprecated use instead {@link io.swagger.codegen.DefaultGenerator} - * or cli interface from https://github.com/swagger-api/swagger-codegen/pull/547 + * @deprecated use instead {@link io.swagger.codegen.DefaultGenerator} or cli interface from + * https://github.com/swagger-api/swagger-codegen/pull/547 */ @Deprecated public class MetaGenerator extends AbstractGenerator { @@ -47,9 +47,9 @@ public static List getExtensions() { static void usage(Options options) { HelpFormatter formatter = new HelpFormatter(); - formatter.printHelp("MetaGenerator. Generator for creating a new template set " + - "and configuration for Codegen. The output will be based on the language you " + - "specify, and includes default templates to include.", options); + formatter.printHelp("MetaGenerator. Generator for creating a new template set " + + "and configuration for Codegen. The output will be based on the language you " + + "specify, and includes default templates to include.", options); } public static CodegenConfig getConfig(String name) { @@ -67,10 +67,13 @@ protected void generate(String[] args) { Options options = new Options(); options.addOption("h", "help", false, "shows this message"); - options.addOption("l", "lang", false, "client language to generate.\nAvailable languages include:\n\t[" + configString + "]"); + options.addOption("l", "lang", false, + "client language to generate.\nAvailable languages include:\n\t[" + configString + + "]"); options.addOption("o", "output", true, "where to write the generated files"); options.addOption("n", "name", true, "the human-readable name of the generator"); - options.addOption("p", "package", true, "the package to put the main class into (defaults to io.swagger.codegen"); + options.addOption("p", "package", true, + "the package to put the main class into (defaults to io.swagger.codegen"); CommandLine cmd = null; try { @@ -83,7 +86,7 @@ protected void generate(String[] args) { if (cmd.hasOption("n")) { name = cmd.getOptionValue("n"); } else { - System.out.println("name is required"); //FIXME replace by LOGGER + System.out.println("name is required"); // FIXME replace by LOGGER usage(options); return; } @@ -108,11 +111,14 @@ protected void generate(String[] args) { if (!outputFolderLocation.exists()) { outputFolderLocation.mkdirs(); } - File sourceFolder = new File(outputFolder + File.separator + "src/main/java/" + targetPackage.replace('.', File.separatorChar)); + File sourceFolder = + new File(outputFolder + File.separator + "src/main/java/" + + targetPackage.replace('.', File.separatorChar)); if (!sourceFolder.exists()) { sourceFolder.mkdirs(); } - File resourcesFolder = new File(outputFolder + File.separator + "src/main/resources/META-INF/services"); + File resourcesFolder = + new File(outputFolder + File.separator + "src/main/resources/META-INF/services"); if (!resourcesFolder.exists()) { resourcesFolder.mkdirs(); } @@ -121,14 +127,17 @@ protected void generate(String[] args) { List supportingFiles = new ArrayList(); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - supportingFiles.add(new SupportingFile("generatorClass.mustache", - "src/main/java/" + File.separator + targetPackage.replace('.', File.separatorChar), - mainClass + ".java")); + supportingFiles.add(new SupportingFile("generatorClass.mustache", "src/main/java/" + + File.separator + targetPackage.replace('.', File.separatorChar), mainClass + + ".java")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache")); - supportingFiles.add(new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache")); + supportingFiles.add(new SupportingFile("api.template", "src/main/resources" + + File.separator + name, "api.mustache")); + supportingFiles.add(new SupportingFile("model.template", "src/main/resources" + + File.separator + name, "model.mustache")); - supportingFiles.add(new SupportingFile("services.mustache", "src/main/resources/META-INF/services", "io.swagger.codegen.CodegenConfig")); + supportingFiles.add(new SupportingFile("services.mustache", + "src/main/resources/META-INF/services", "io.swagger.codegen.CodegenConfig")); List files = new ArrayList(); @@ -148,24 +157,25 @@ protected void generate(String[] args) { if (!of.isDirectory()) { of.mkdirs(); } - String outputFilename = destinationFolder + File.separator + support.destinationFilename; + String outputFilename = + destinationFolder + File.separator + support.destinationFilename; if (support.templateFile.endsWith("mustache")) { - String template = readTemplate(templateDir + File.separator + support.templateFile); - Template tmpl = Mustache.compiler() - .withLoader(new Mustache.TemplateLoader() { - @Override - public Reader getTemplate(String name) { - return getTemplateReader(templateDir + File.separator + name + ".mustache"); - } - }) - .defaultValue("") - .compile(template); + String template = + readTemplate(templateDir + File.separator + support.templateFile); + Template tmpl = Mustache.compiler().withLoader(new Mustache.TemplateLoader() { + @Override + public Reader getTemplate(String name) { + return getTemplateReader(templateDir + File.separator + name + + ".mustache"); + } + }).defaultValue("").compile(template); writeToFile(outputFilename, tmpl.execute(data)); files.add(new File(outputFilename)); } else { - String template = readTemplate(templateDir + File.separator + support.templateFile); + String template = + readTemplate(templateDir + File.separator + support.templateFile); FileUtils.writeStringToFile(new File(outputFilename), template); LOGGER.info("copying file to " + outputFilename); files.add(new File(outputFilename)); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java index 74bee83ef24..e438b14126d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java @@ -28,16 +28,20 @@ public String toString() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; SupportingFile that = (SupportingFile) o; - if (templateFile != null ? !templateFile.equals(that.templateFile) : that.templateFile != null) + if (templateFile != null ? !templateFile.equals(that.templateFile) + : that.templateFile != null) return false; if (folder != null ? !folder.equals(that.folder) : that.folder != null) return false; - return destinationFilename != null ? destinationFilename.equals(that.destinationFilename) : that.destinationFilename == null; + return destinationFilename != null ? destinationFilename.equals(that.destinationFilename) + : that.destinationFilename == null; } @@ -49,5 +53,3 @@ public int hashCode() { return result; } } - - diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthMethod.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthMethod.java index 9a526f1ecf1..a4283c612fb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthMethod.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthMethod.java @@ -4,4 +4,4 @@ public interface AuthMethod { String getType(); void setType(String type); -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthParser.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthParser.java index 65896dc5933..5e42d2485f4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthParser.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthParser.java @@ -15,7 +15,7 @@ import static org.apache.commons.lang3.StringUtils.isNotEmpty; public class AuthParser { - + private static final Logger LOGGER = LoggerFactory.getLogger(AuthParser.class); public static List parse(String urlEncodedAuthStr) { @@ -25,7 +25,10 @@ public static List parse(String urlEncodedAuthStr) { for (String part : parts) { String[] kvPair = part.split(":"); if (kvPair.length == 2) { - auths.add(new AuthorizationValue(URLDecoder.decode(kvPair[0]), URLDecoder.decode(kvPair[1]), "header")); // FIXME replace the deprecated method by decode(string, encoding). Which encoding is used ? Default UTF-8 ? + auths.add(new AuthorizationValue(URLDecoder.decode(kvPair[0]), URLDecoder + .decode(kvPair[1]), "header")); // FIXME replace the deprecated method + // by decode(string, encoding). Which + // encoding is used ? Default UTF-8 ? } } } @@ -40,8 +43,7 @@ public static String reconstruct(List authorizationValueList if (b.toString().length() > 0) { b.append(","); } - b.append(URLEncoder.encode(v.getKeyName(), "UTF-8")) - .append(":") + b.append(URLEncoder.encode(v.getKeyName(), "UTF-8")).append(":") .append(URLEncoder.encode(v.getValue(), "UTF-8")); } catch (Exception e) { // continue diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java index b21e89711ff..105d920ee11 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java @@ -29,10 +29,10 @@ import static org.apache.commons.lang3.StringUtils.isNotEmpty; /** - * A class that contains all codegen configuration properties a user would want to manipulate. - * An instance could be created by deserializing a JSON file or being populated from CLI or Maven plugin parameters. - * It also has a convenience method for creating a ClientOptInput class which is THE object DefaultGenerator.java needs - * to generate code. + * A class that contains all codegen configuration properties a user would want to manipulate. An + * instance could be created by deserializing a JSON file or being populated from CLI or Maven + * plugin parameters. It also has a convenience method for creating a ClientOptInput class which is + * THE object DefaultGenerator.java needs to generate code. */ public class CodegenConfigurator { @@ -61,14 +61,19 @@ public class CodegenConfigurator { private Map additionalProperties = new HashMap(); private Map importMappings = new HashMap(); private Set languageSpecificPrimitives = new HashSet(); - private Map reservedWordMappings = new HashMap(); - - private String gitUserId="GIT_USER_ID"; - private String gitRepoId="GIT_REPO_ID"; - private String releaseNote="Minor update"; + private Map reservedWordMappings = new HashMap(); + + private String gitUserId = "GIT_USER_ID"; + private String gitRepoId = "GIT_REPO_ID"; + private String releaseNote = "Minor update"; private String httpUserAgent; - private final Map dynamicProperties = new HashMap(); //the map that holds the JsonAnySetter/JsonAnyGetter values + private final Map dynamicProperties = new HashMap(); // the map + // that + // holds + // the + // JsonAnySetter/JsonAnyGetter + // values public CodegenConfigurator() { this.setOutputDir("."); @@ -155,7 +160,8 @@ public CodegenConfigurator setTemplateDir(String templateDir) { // check to see if the folder exists if (!(f.exists() && f.isDirectory())) { - throw new IllegalArgumentException("Template directory " + templateDir + " does not exist."); + throw new IllegalArgumentException("Template directory " + templateDir + + " does not exist."); } this.templateDir = f.getAbsolutePath(); @@ -266,7 +272,7 @@ public CodegenConfigurator setAdditionalProperties(Map additiona this.additionalProperties = additionalProperties; return this; } - + public CodegenConfigurator addAdditionalProperty(String key, Object value) { this.additionalProperties.put(key, value); return this; @@ -341,19 +347,19 @@ public String getHttpUserAgent() { } public CodegenConfigurator setHttpUserAgent(String httpUserAgent) { - this.httpUserAgent= httpUserAgent; + this.httpUserAgent = httpUserAgent; return this; } - - public Map getReservedWordsMappings() { + + public Map getReservedWordsMappings() { return reservedWordMappings; } - + public CodegenConfigurator setReservedWordsMappings(Map reservedWordsMappings) { this.reservedWordMappings = reservedWordsMappings; return this; } - + public CodegenConfigurator addAdditionalReservedWordMapping(String key, String value) { this.reservedWordMappings.put(key, value); return this; @@ -367,7 +373,7 @@ public CodegenConfigurator setIgnoreFileOverride(final String ignoreFileOverride this.ignoreFileOverride = ignoreFileOverride; return this; } - + public ClientOptInput toClientOptInput() { Validate.notEmpty(lang, "language must be specified"); @@ -388,14 +394,15 @@ public ClientOptInput toClientOptInput() { config.importMapping().putAll(importMappings); config.languageSpecificPrimitives().addAll(languageSpecificPrimitives); config.reservedWordsMappings().putAll(reservedWordMappings); - + checkAndSetAdditionalProperty(apiPackage, CodegenConstants.API_PACKAGE); checkAndSetAdditionalProperty(modelPackage, CodegenConstants.MODEL_PACKAGE); checkAndSetAdditionalProperty(invokerPackage, CodegenConstants.INVOKER_PACKAGE); checkAndSetAdditionalProperty(groupId, CodegenConstants.GROUP_ID); checkAndSetAdditionalProperty(artifactId, CodegenConstants.ARTIFACT_ID); checkAndSetAdditionalProperty(artifactVersion, CodegenConstants.ARTIFACT_VERSION); - checkAndSetAdditionalProperty(templateDir, toAbsolutePathStr(templateDir), CodegenConstants.TEMPLATE_DIR); + checkAndSetAdditionalProperty(templateDir, toAbsolutePathStr(templateDir), + CodegenConstants.TEMPLATE_DIR); checkAndSetAdditionalProperty(modelNamePrefix, CodegenConstants.MODEL_NAME_PREFIX); checkAndSetAdditionalProperty(modelNameSuffix, CodegenConstants.MODEL_NAME_SUFFIX); checkAndSetAdditionalProperty(gitUserId, CodegenConstants.GIT_USER_ID); @@ -411,15 +418,13 @@ public ClientOptInput toClientOptInput() { config.additionalProperties().putAll(additionalProperties); - ClientOptInput input = new ClientOptInput() - .config(config); + ClientOptInput input = new ClientOptInput().config(config); final List authorizationValues = AuthParser.parse(auth); Swagger swagger = new SwaggerParser().read(inputSpec, authorizationValues, true); - input.opts(new ClientOpts()) - .swagger(swagger); + input.opts(new ClientOpts()).swagger(swagger); return input; } @@ -440,8 +445,7 @@ private void handleDynamicProperties(CodegenConfig codegenConfig) { String opt = langCliOption.getOpt(); if (dynamicProperties.containsKey(opt)) { codegenConfig.additionalProperties().put(opt, dynamicProperties.get(opt)); - } - else if(systemProperties.containsKey(opt)) { + } else if (systemProperties.containsKey(opt)) { codegenConfig.additionalProperties().put(opt, systemProperties.get(opt)); } } @@ -451,11 +455,11 @@ private void setVerboseFlags() { if (!verbose) { return; } - LOGGER.info("\nVERBOSE MODE: ON. Additional debug options are injected" + - "\n - [debugSwagger] prints the swagger specification as interpreted by the codegen" + - "\n - [debugModels] prints models passed to the template engine" + - "\n - [debugOperations] prints operations passed to the template engine" + - "\n - [debugSupportingFiles] prints additional data passed to the template engine"); + LOGGER.info("\nVERBOSE MODE: ON. Additional debug options are injected" + + "\n - [debugSwagger] prints the swagger specification as interpreted by the codegen" + + "\n - [debugModels] prints models passed to the template engine" + + "\n - [debugOperations] prints operations passed to the template engine" + + "\n - [debugSupportingFiles] prints additional data passed to the template engine"); System.setProperty("debugSwagger", ""); System.setProperty("debugModels", ""); @@ -482,7 +486,8 @@ private void checkAndSetAdditionalProperty(String property, String propertyKey) checkAndSetAdditionalProperty(property, property, propertyKey); } - private void checkAndSetAdditionalProperty(String property, String valueToSet, String propertyKey) { + private void checkAndSetAdditionalProperty(String property, String valueToSet, + String propertyKey) { if (isNotEmpty(property)) { additionalProperties.put(propertyKey, valueToSet); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfiguratorUtils.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfiguratorUtils.java index 90a96837797..799982a5873 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfiguratorUtils.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfiguratorUtils.java @@ -6,31 +6,34 @@ import java.util.*; /** - * Contains shared logic for applying key-value pairs and CSV strings - * to specific settings in CodegenConfigurator. + * Contains shared logic for applying key-value pairs and CSV strings to specific settings in + * CodegenConfigurator. * *

- * This class exists to facilitate testing. These methods could be applied - * to CodegenConfigurator, but this complicates things when mocking CodegenConfigurator. + * This class exists to facilitate testing. These methods could be applied to CodegenConfigurator, + * but this complicates things when mocking CodegenConfigurator. *

*/ public final class CodegenConfiguratorUtils { - public static void applySystemPropertiesKvp(String systemProperties, CodegenConfigurator configurator) { + public static void applySystemPropertiesKvp(String systemProperties, + CodegenConfigurator configurator) { final Map map = createMapFromKeyValuePairs(systemProperties); for (Map.Entry entry : map.entrySet()) { configurator.addSystemProperty(entry.getKey(), entry.getValue()); } } - public static void applyInstantiationTypesKvp(String instantiationTypes, CodegenConfigurator configurator) { + public static void applyInstantiationTypesKvp(String instantiationTypes, + CodegenConfigurator configurator) { final Map map = createMapFromKeyValuePairs(instantiationTypes); for (Map.Entry entry : map.entrySet()) { configurator.addInstantiationType(entry.getKey(), entry.getValue()); } } - public static void applyImportMappingsKvp(String importMappings, CodegenConfigurator configurator) { + public static void applyImportMappingsKvp(String importMappings, + CodegenConfigurator configurator) { final Map map = createMapFromKeyValuePairs(importMappings); for (Map.Entry entry : map.entrySet()) { configurator.addImportMapping(entry.getKey().trim(), entry.getValue().trim()); @@ -44,34 +47,38 @@ public static void applyTypeMappingsKvp(String typeMappings, CodegenConfigurator } } - public static void applyAdditionalPropertiesKvp(String additionalProperties, CodegenConfigurator configurator) { + public static void applyAdditionalPropertiesKvp(String additionalProperties, + CodegenConfigurator configurator) { final Map map = createMapFromKeyValuePairs(additionalProperties); for (Map.Entry entry : map.entrySet()) { configurator.addAdditionalProperty(entry.getKey(), entry.getValue()); } } - public static void applyLanguageSpecificPrimitivesCsv(String languageSpecificPrimitives, CodegenConfigurator configurator) { + public static void applyLanguageSpecificPrimitivesCsv(String languageSpecificPrimitives, + CodegenConfigurator configurator) { final Set set = createSetFromCsvList(languageSpecificPrimitives); for (String item : set) { configurator.addLanguageSpecificPrimitive(item); } } - public static void applyReservedWordsMappingsKvp(String reservedWordMappings, CodegenConfigurator configurator) { + public static void applyReservedWordsMappingsKvp(String reservedWordMappings, + CodegenConfigurator configurator) { final Map map = createMapFromKeyValuePairs(reservedWordMappings); for (Map.Entry entry : map.entrySet()) { configurator.addAdditionalReservedWordMapping(entry.getKey(), entry.getValue()); - } + } } - + private static Set createSetFromCsvList(String csvProperty) { final List values = OptionUtils.splitCommaSeparatedList(csvProperty); return new HashSet(values); } private static Map createMapFromKeyValuePairs(String commaSeparatedKVPairs) { - final List> pairs = OptionUtils.parseCommaSeparatedTuples(commaSeparatedKVPairs); + final List> pairs = + OptionUtils.parseCommaSeparatedTuples(commaSeparatedKVPairs); Map result = new HashMap(); @@ -81,6 +88,6 @@ private static Map createMapFromKeyValuePairs(String commaSepara return result; } - - + + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java index bff78820b25..fca81f0bd54 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java @@ -37,19 +37,24 @@ public ExampleGenerator(Map examples) { this.examples = examples; } - public List> generate(Map examples, List mediaTypes, Property property) { + public List> generate(Map examples, + List mediaTypes, Property property) { List> output = new ArrayList>(); Set processedModels = new HashSet(); if (examples == null) { if (mediaTypes == null) { // assume application/json for this - mediaTypes = Arrays.asList("application/json"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + mediaTypes = Arrays.asList("application/json"); // FIXME: a parameter should not be + // assigned. Also declare the + // methods parameters as 'final'. } for (String mediaType : mediaTypes) { Map kv = new HashMap(); kv.put("contentType", mediaType); if (property != null && mediaType.startsWith("application/json")) { - String example = Json.pretty(resolvePropertyToExample(mediaType, property, processedModels)); + String example = + Json.pretty(resolvePropertyToExample(mediaType, property, + processedModels)); if (example != null) { kv.put("example", example); @@ -79,7 +84,8 @@ public List> generate(Map examples, List processedModels) { + protected Object resolvePropertyToExample(String mediaType, Property property, + Set processedModels) { if (property.getExample() != null) { return property.getExample(); } else if (property instanceof StringProperty) { @@ -89,37 +95,37 @@ protected Object resolvePropertyToExample(String mediaType, Property property, S } else if (property instanceof ArrayProperty) { Property innerType = ((ArrayProperty) property).getItems(); if (innerType != null) { - return new Object[]{ - resolvePropertyToExample(mediaType, innerType, processedModels) - }; + return new Object[] {resolvePropertyToExample(mediaType, innerType, processedModels)}; } } else if (property instanceof DateProperty) { return "2000-01-23"; } else if (property instanceof DateTimeProperty) { return "2000-01-23T04:56:07.000+00:00"; - } else if (property instanceof DecimalProperty) { + } else if (property instanceof DecimalProperty) { return new BigDecimal(1.3579); } else if (property instanceof DoubleProperty) { return 3.149; } else if (property instanceof FileProperty) { - return ""; // TODO + return ""; // TODO } else if (property instanceof FloatProperty) { return 1.23f; } else if (property instanceof IntegerProperty) { return 123; } else if (property instanceof LongProperty) { return 123456789L; - // Properties that are not Integer or Long may still be BaseInteger + // Properties that are not Integer or Long may still be BaseInteger } else if (property instanceof BaseIntegerProperty) { return 123; } else if (property instanceof MapProperty) { Map mp = new HashMap(); if (property.getName() != null) { mp.put(property.getName(), - resolvePropertyToExample(mediaType, ((MapProperty) property).getAdditionalProperties(), processedModels)); + resolvePropertyToExample(mediaType, + ((MapProperty) property).getAdditionalProperties(), processedModels)); } else { mp.put("key", - resolvePropertyToExample(mediaType, ((MapProperty) property).getAdditionalProperties(), processedModels)); + resolvePropertyToExample(mediaType, + ((MapProperty) property).getAdditionalProperties(), processedModels)); } return mp; } else if (property instanceof ObjectProperty) { @@ -131,13 +137,14 @@ protected Object resolvePropertyToExample(String mediaType, Property property, S return resolveModelToExample(simpleName, mediaType, model, processedModels); } } else if (property instanceof UUIDProperty) { - return "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; + return "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; } return ""; } - public Object resolveModelToExample(String name, String mediaType, Model model, Set processedModels) { + public Object resolveModelToExample(String name, String mediaType, Model model, + Set processedModels) { if (processedModels.contains(name)) { return ""; } @@ -149,11 +156,12 @@ public Object resolveModelToExample(String name, String mediaType, Model model, if (impl.getProperties() != null) { for (String propertyName : impl.getProperties().keySet()) { Property property = impl.getProperties().get(propertyName); - values.put(propertyName, resolvePropertyToExample(mediaType, property, processedModels)); + values.put(propertyName, + resolvePropertyToExample(mediaType, property, processedModels)); } } return values; } return ""; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java index c59449be439..c4a037f4632 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java @@ -45,7 +45,7 @@ public class XmlExampleGenerator { public XmlExampleGenerator(Map examples) { this.examples = examples; if (examples == null) { - this.examples = new HashMap(); + this.examples = new HashMap(); } } @@ -87,10 +87,11 @@ protected String modelImplToXml(ModelImpl model, int indent, Collection } } // TODO: map objects will not enter this block - if(model.getProperties() != null) { + if (model.getProperties() != null) { for (String pName : model.getProperties().keySet()) { Property p = model.getProperties().get(pName); - if (p != null && p.getXml() != null && p.getXml().getAttribute() != null && p.getXml().getAttribute()) { + if (p != null && p.getXml() != null && p.getXml().getAttribute() != null + && p.getXml().getAttribute()) { attributes.put(pName, p); } else { elements.put(pName, p); @@ -134,7 +135,8 @@ protected String toXml(String name, Property property, int indent, Collection getInclusionRules() { return ImmutableList.copyOf(inclusionRules); } /** - * Allows a consumer to manually inspect all "exclusion rules". That is, patterns in the ignore file which represent - * files and directories to be excluded, unless explicitly overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules. + * Allows a consumer to manually inspect all "exclusion rules". That is, patterns in the ignore + * file which represent files and directories to be excluded, unless explicitly overridden by + * {@link CodegenIgnoreProcessor#getInclusionRules()} rules. * - * NOTE: Existence in this list doesn't mean a file is excluded. The rule can be overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules. + * NOTE: Existence in this list doesn't mean a file is excluded. The rule can be overridden by + * {@link CodegenIgnoreProcessor#getInclusionRules()} rules. * - * @return A {@link ImmutableList#copyOf(Collection)} of rules which define exclusions by patterns in the ignore file. + * @return A {@link ImmutableList#copyOf(Collection)} of rules which define exclusions by + * patterns in the ignore file. */ public List getExclusionRules() { return ImmutableList.copyOf(exclusionRules); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/DirectoryRule.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/DirectoryRule.java index 235d34d3f96..68483d1f4e8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/DirectoryRule.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/DirectoryRule.java @@ -14,7 +14,8 @@ public class DirectoryRule extends FileRule { StringBuilder sb = new StringBuilder(); sb.append("glob:"); sb.append(pattern); - if(!pattern.endsWith("/")) sb.append("/"); + if (!pattern.endsWith("/")) + sb.append("/"); directoryMatcher = FileSystems.getDefault().getPathMatcher(sb.toString()); sb.append("**"); contentsMatcher = FileSystems.getDefault().getPathMatcher(sb.toString()); @@ -22,6 +23,7 @@ public class DirectoryRule extends FileRule { @Override public Boolean matches(String relativePath) { - return contentsMatcher.matches(FileSystems.getDefault().getPath(relativePath)) || directoryMatcher.matches(FileSystems.getDefault().getPath(relativePath)); + return contentsMatcher.matches(FileSystems.getDefault().getPath(relativePath)) + || directoryMatcher.matches(FileSystems.getDefault().getPath(relativePath)); } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/EverythingRule.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/EverythingRule.java index f942cb222ce..b051dffb4fb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/EverythingRule.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/EverythingRule.java @@ -16,5 +16,7 @@ public Boolean matches(String relativePath) { } @Override - protected Operation getExcludeOperation(){ return Operation.EXCLUDE_AND_TERMINATE; } + protected Operation getExcludeOperation() { + return Operation.EXCLUDE_AND_TERMINATE; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/FileRule.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/FileRule.java index a97513dc1e7..de3d32c40be 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/FileRule.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/FileRule.java @@ -10,7 +10,7 @@ public class FileRule extends Rule { FileRule(List syntax, String definition) { super(syntax, definition); - matcher = FileSystems.getDefault().getPathMatcher("glob:"+this.getPattern()); + matcher = FileSystems.getDefault().getPathMatcher("glob:" + this.getPattern()); } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/IgnoreLineParser.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/IgnoreLineParser.java index 2d3fbdd2994..b8c691148c1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/IgnoreLineParser.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/IgnoreLineParser.java @@ -5,16 +5,9 @@ public class IgnoreLineParser { enum Token { - MATCH_ALL("**"), - MATCH_ANY("*"), - ESCAPED_EXCLAMATION("\\!"), - ESCAPED_SPACE("\\ "), - PATH_DELIM("/"), - NEGATE("!"), - TEXT(null), - DIRECTORY_MARKER("/"), - ROOTED_MARKER("/"), - COMMENT(null); + MATCH_ALL("**"), MATCH_ANY("*"), ESCAPED_EXCLAMATION("\\!"), ESCAPED_SPACE("\\ "), PATH_DELIM( + "/"), NEGATE("!"), TEXT(null), DIRECTORY_MARKER("/"), ROOTED_MARKER("/"), COMMENT( + null); private String pattern; @@ -27,8 +20,10 @@ public String getPattern() { } } - // NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore - // see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt + // NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for + // .gitignore + // see: + // https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt static List parse(String text) throws ParserException { List parts = new ArrayList<>(); StringBuilder sb = new StringBuilder(); @@ -43,7 +38,7 @@ static List parse(String text) throws ParserException { if (i == 0) { if ("#".equals(current)) { - //: A line starting with # serves as a comment. + // : A line starting with # serves as a comment. parts.add(new Part(Token.COMMENT, text)); i = totalLength; // rather than early return continue; @@ -55,9 +50,10 @@ static List parse(String text) throws ParserException { continue; } } else if ("\\".equals(current) && "#".equals(next)) { - //: Put a backslash ("`\`") in front of the first hash for patterns - //: that begin with a hash. - // NOTE: Just push forward and drop the escape character. Falls through to TEXT token. + // : Put a backslash ("`\`") in front of the first hash for patterns + // : that begin with a hash. + // NOTE: Just push forward and drop the escape character. Falls through to TEXT + // token. current = next; next = null; i++; @@ -68,8 +64,8 @@ static List parse(String text) throws ParserException { if (Token.MATCH_ANY.pattern.equals(next)) { // peek ahead for invalid pattern. Slightly inefficient, but acceptable. - if ((i+2 < totalLength - 1) && - String.valueOf(characters[i+2]).equals(Token.MATCH_ANY.pattern)) { + if ((i + 2 < totalLength - 1) + && String.valueOf(characters[i + 2]).equals(Token.MATCH_ANY.pattern)) { // It doesn't matter where we are in the pattern, *** is invalid. throw new ParserException("The pattern *** is invalid."); } @@ -80,7 +76,8 @@ static List parse(String text) throws ParserException { } else { if (sb.length() > 0) { - // A MATCH_ANY may commonly follow a filename or some other character. Dump that to results before the MATCH_ANY. + // A MATCH_ANY may commonly follow a filename or some other character. Dump + // that to results before the MATCH_ANY. parts.add(new Part(Token.TEXT, sb.toString())); sb.delete(0, sb.length()); } @@ -113,8 +110,9 @@ static List parse(String text) throws ParserException { } parts.add(new Part(Token.PATH_DELIM)); - if(Token.PATH_DELIM.pattern.equals(next)) { - // ignore doubled path delims. NOTE: doesn't do full lookahead, so /// will result in // + if (Token.PATH_DELIM.pattern.equals(next)) { + // ignore doubled path delims. NOTE: doesn't do full lookahead, so /// will + // result in // i++; } continue; @@ -132,7 +130,7 @@ static List parse(String text) throws ParserException { if (sb.length() > 0) { // NOTE: All spaces escaped spaces are a special token, ESCAPED_SPACE - //: Trailing spaces are ignored unless they are quoted with backslash ("`\`") + // : Trailing spaces are ignored unless they are quoted with backslash ("`\`") parts.add(new Part(Token.TEXT, sb.toString().trim())); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/ParserException.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/ParserException.java index 03e02d8fd70..1cc5226ad69 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/ParserException.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/ParserException.java @@ -2,12 +2,11 @@ public class ParserException extends Exception { /** - * Constructs a new exception with the specified detail message. The - * cause is not initialized, and may subsequently be initialized by - * a call to {@link #initCause}. + * Constructs a new exception with the specified detail message. The cause is not initialized, + * and may subsequently be initialized by a call to {@link #initCause}. * - * @param message the detail message. The detail message is saved for - * later retrieval by the {@link #getMessage()} method. + * @param message the detail message. The detail message is saved for later retrieval by the + * {@link #getMessage()} method. */ public ParserException(String message) { super(message); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Part.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Part.java index 71379922175..a571e640831 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Part.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Part.java @@ -21,4 +21,4 @@ public IgnoreLineParser.Token getToken() { public String getValue() { return value; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/RootedFileRule.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/RootedFileRule.java index 6c445b6299a..4b47565e971 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/RootedFileRule.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/RootedFileRule.java @@ -4,8 +4,8 @@ import java.util.regex.Pattern; /** - * A special case rule which matches files only if they're located - * in the same directory as the .swagger-codegen-ignore file. + * A special case rule which matches files only if they're located in the same directory as the + * .swagger-codegen-ignore file. */ public class RootedFileRule extends Rule { private String definedFilename = null; @@ -19,34 +19,43 @@ public class RootedFileRule extends Rule { definedExtension = getExtensionPart(definition, separatorIndex); } - private String getFilenamePart(final String input, int stopIndex){ - return input.substring('/' == input.charAt(0) ? 1 : 0, stopIndex > 0 ? stopIndex : input.length()); + private String getFilenamePart(final String input, int stopIndex) { + return input.substring('/' == input.charAt(0) ? 1 : 0, + stopIndex > 0 ? stopIndex : input.length()); } private String getExtensionPart(final String input, int stopIndex) { - return input.substring(stopIndex > 0 ? stopIndex+1: input.length(), input.length()); + return input.substring(stopIndex > 0 ? stopIndex + 1 : input.length(), input.length()); } @Override public Boolean matches(String relativePath) { - // NOTE: Windows-style separator isn't supported, so File.pathSeparator would be incorrect here. - // NOTE: lastIndexOf rather than contains because /file.txt is acceptable while path/file.txt is not. - // relativePath will be passed by CodegenIgnoreProcessor and is relative to .codegen-ignore. + // NOTE: Windows-style separator isn't supported, so File.pathSeparator would be incorrect + // here. + // NOTE: lastIndexOf rather than contains because /file.txt is acceptable while + // path/file.txt is not. + // relativePath will be passed by CodegenIgnoreProcessor and is relative to .codegen-ignore. boolean isSingleFile = relativePath.lastIndexOf("/") <= 0; - if(isSingleFile) { + if (isSingleFile) { int separatorIndex = relativePath.lastIndexOf("."); final String filename = getFilenamePart(relativePath, separatorIndex); final String extension = getExtensionPart(relativePath, separatorIndex); - boolean extensionMatches = definedExtension.equals(extension) || definedExtension.equals(IgnoreLineParser.Token.MATCH_ANY.getPattern()); + boolean extensionMatches = + definedExtension.equals(extension) + || definedExtension.equals(IgnoreLineParser.Token.MATCH_ANY + .getPattern()); - if(extensionMatches && definedFilename.contains(IgnoreLineParser.Token.MATCH_ANY.getPattern())) { + if (extensionMatches + && definedFilename.contains(IgnoreLineParser.Token.MATCH_ANY.getPattern())) { // TODO: Evaluate any other escape requirements here. - Pattern regex = Pattern.compile( - definedFilename - .replaceAll(Pattern.quote("."), "\\\\Q.\\\\E") - .replaceAll(Pattern.quote("*"), ".*?") // non-greedy match on 0+ any character - ); + Pattern regex = + Pattern.compile(definedFilename.replaceAll(Pattern.quote("."), + "\\\\Q.\\\\E").replaceAll(Pattern.quote("*"), ".*?") // non-greedy + // match on 0+ + // any + // character + ); return regex.matcher(filename).matches(); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java index 2d2394302f8..a426caa98de 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java @@ -4,7 +4,9 @@ public abstract class Rule { - public enum Operation {EXCLUDE, INCLUDE, NOOP, EXCLUDE_AND_TERMINATE} + public enum Operation { + EXCLUDE, INCLUDE, NOOP, EXCLUDE_AND_TERMINATE + } // The original rule private final String definition; @@ -23,7 +25,8 @@ public String getDefinition() { } protected String getPattern() { - if(syntax == null) return this.definition; + if (syntax == null) + return this.definition; StringBuilder sb = new StringBuilder(); for (Part current : syntax) { @@ -47,20 +50,22 @@ protected String getPattern() { } /** - * Whether or not the rule should be negated. !foo means foo should be removed from previous matches. - * Example: **\/*.bak excludes all backup. Adding !/test.bak will include test.bak in the project root. + * Whether or not the rule should be negated. !foo means foo should be removed from previous + * matches. Example: **\/*.bak excludes all backup. Adding !/test.bak will include test.bak in + * the project root. *

* NOTE: It is not possible to re-include a file if a parent directory of that file is excluded. * * @return {@code true} if the rule is negated (inverse), otherwise {@code false} (normal). */ public Boolean getNegated() { - return this.syntax != null && this.syntax.size() > 0 && this.syntax.get(0).getToken() == IgnoreLineParser.Token.NEGATE; + return this.syntax != null && this.syntax.size() > 0 + && this.syntax.get(0).getToken() == IgnoreLineParser.Token.NEGATE; } public Operation evaluate(String relativePath) { if (Boolean.TRUE.equals(matches(relativePath))) { - if(Boolean.TRUE.equals(this.getNegated())) { + if (Boolean.TRUE.equals(this.getNegated())) { return this.getIncludeOperation(); } return this.getExcludeOperation(); @@ -68,12 +73,19 @@ public Operation evaluate(String relativePath) { return Operation.NOOP; } - protected Operation getIncludeOperation(){ return Operation.INCLUDE; } - protected Operation getExcludeOperation(){ return Operation.EXCLUDE; } + protected Operation getIncludeOperation() { + return Operation.INCLUDE; + } + + protected Operation getExcludeOperation() { + return Operation.EXCLUDE; + } public static Rule create(String definition) { - // NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore - // see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt + // NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for + // .gitignore + // see: + // https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt Rule rule = null; if (definition.equals(".")) { return new InvalidRule(null, definition, "Pattern '.' is invalid."); @@ -100,67 +112,69 @@ public static Rule create(String definition) { } else { IgnoreLineParser.Token head = result.get(0).getToken(); - //: An optional prefix "`!`" which negates the pattern; any - //: matching file excluded by a previous pattern will become - //: included again. It is not possible to re-include a file if a parent - //: directory of that file is excluded. Git doesn't list excluded - //: directories for performance reasons, so any patterns on contained - //: files have no effect, no matter where they are defined. - //: Put a backslash ("`\`") in front of the first "`!`" for patterns - //: that begin with a literal "`!`", for example, "`\!important!.txt`". + // : An optional prefix "`!`" which negates the pattern; any + // : matching file excluded by a previous pattern will become + // : included again. It is not possible to re-include a file if a parent + // : directory of that file is excluded. Git doesn't list excluded + // : directories for performance reasons, so any patterns on contained + // : files have no effect, no matter where they are defined. + // : Put a backslash ("`\`") in front of the first "`!`" for patterns + // : that begin with a literal "`!`", for example, "`\!important!.txt`". // see this.getNegated(); - //: If the pattern ends with a slash, it is removed for the - //: purpose of the following description, but it would only find - //: a match with a directory. In other words, `foo/` will match a - //: directory `foo` and paths underneath it, but will not match a - //: regular file or a symbolic link `foo` (this is consistent - //: with the way how pathspec works in general in Git). - directoryOnly = IgnoreLineParser.Token.DIRECTORY_MARKER.equals(result.get(result.size() - 1).getToken()); + // : If the pattern ends with a slash, it is removed for the + // : purpose of the following description, but it would only find + // : a match with a directory. In other words, `foo/` will match a + // : directory `foo` and paths underneath it, but will not match a + // : regular file or a symbolic link `foo` (this is consistent + // : with the way how pathspec works in general in Git). + directoryOnly = + IgnoreLineParser.Token.DIRECTORY_MARKER.equals(result + .get(result.size() - 1).getToken()); if (directoryOnly) { rule = new DirectoryRule(result, definition); } else if (IgnoreLineParser.Token.PATH_DELIM.equals(head)) { - //: A leading slash matches the beginning of the pathname. - //: For example, "/{asterisk}.c" matches "cat-file.c" but not - //: "mozilla-sha1/sha1.c". + // : A leading slash matches the beginning of the pathname. + // : For example, "/{asterisk}.c" matches "cat-file.c" but not + // : "mozilla-sha1/sha1.c". rule = new RootedFileRule(result, definition); } else { // case 1 - //: If the pattern does not contain a slash '/', Git treats it as - //: a shell glob pattern and checks for a match against the - //: pathname relative to the location of the `.gitignore` file - //: (relative to the toplevel of the work tree if not from a - //: `.gitignore` file). + // : If the pattern does not contain a slash '/', Git treats it as + // : a shell glob pattern and checks for a match against the + // : pathname relative to the location of the `.gitignore` file + // : (relative to the toplevel of the work tree if not from a + // : `.gitignore` file). // case 2 - //: Otherwise, Git treats the pattern as a shell glob suitable - //: for consumption by fnmatch(3) with the FNM_PATHNAME flag: - //: wildcards in the pattern will not match a / in the pathname. - //: For example, "Documentation/{asterisk}.html" matches - //: "Documentation/git.html" but not "Documentation/ppc/ppc.html" - //: or "tools/perf/Documentation/perf.html". + // : Otherwise, Git treats the pattern as a shell glob suitable + // : for consumption by fnmatch(3) with the FNM_PATHNAME flag: + // : wildcards in the pattern will not match a / in the pathname. + // : For example, "Documentation/{asterisk}.html" matches + // : "Documentation/git.html" but not "Documentation/ppc/ppc.html" + // : or "tools/perf/Documentation/perf.html". // case 3 - //: Two consecutive asterisks ("`**`") in patterns matched against - //: full pathname may have special meaning: - //: - //: - A leading "`**`" followed by a slash means match in all - //: directories. For example, "`**/foo`" matches file or directory - //: "`foo`" anywhere, the same as pattern "`foo`". "`**/foo/bar`" - //: matches file or directory "`bar`" anywhere that is directly - //: under directory "`foo`". - //: - //: - A trailing "`/**`" matches everything inside. For example, - //: "`abc/**`" matches all files inside directory "`abc`", relative - //: to the location of the `.gitignore` file, with infinite depth. - //: - //: - A slash followed by two consecutive asterisks then a slash - //: matches zero or more directories. For example, "`a/**/b`" - //: matches "`a/b`", "`a/x/b`", "`a/x/y/b`" and so on. - //: - //: - Other consecutive asterisks are considered invalid. + // : Two consecutive asterisks ("`**`") in patterns matched against + // : full pathname may have special meaning: + // : + // : - A leading "`**`" followed by a slash means match in all + // : directories. For example, "`**/foo`" matches file or directory + // : "`foo`" anywhere, the same as pattern "`foo`". "`**/foo/bar`" + // : matches file or directory "`bar`" anywhere that is directly + // : under directory "`foo`". + // : + // : - A trailing "`/**`" matches everything inside. For example, + // : "`abc/**`" matches all files inside directory "`abc`", relative + // : to the location of the `.gitignore` file, with infinite depth. + // : + // : - A slash followed by two consecutive asterisks then a slash + // : matches zero or more directories. For example, "`a/**/b`" + // : matches "`a/b`", "`a/x/b`", "`a/x/y/b`" and so on. + // : + // : - Other consecutive asterisks are considered invalid. rule = new FileRule(result, definition); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index e9259a4b3f4..a9a680a71b6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -32,7 +32,8 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co protected String sourceFolder = "src"; // TODO: Add option for test folder output location. Nice to allow e.g. ./test instead of ./src. - // This would require updating relative paths (e.g. path to main project file in test project file) + // This would require updating relative paths (e.g. path to main project file in test project + // file) protected String testFolder = sourceFolder; protected Set collectionTypes; @@ -49,69 +50,54 @@ public AbstractCSharpCodegen() { outputFolder = "generated-code" + File.separator + this.getName(); embeddedTemplateDir = templateDir = this.getName(); - collectionTypes = new HashSet( - Arrays.asList( - "IList", "List", - "ICollection", "Collection", - "IEnumerable") - ); - - mapTypes = new HashSet( - Arrays.asList("IDictionary") - ); - - setReservedWordsLowerCase( - Arrays.asList( - // set "client" as a reserved word to avoid conflicts with IO.Swagger.Client - // this is a workaround and can be removed if c# api client is updated to use - // fully qualified name - "client", "parameter", - // local variable names in API methods (endpoints) - "localVarPath", "localVarPathParams", "localVarQueryParams", "localVarHeaderParams", - "localVarFormParams", "localVarFileParams", "localVarStatusCode", "localVarResponse", - "localVarPostBody", "localVarHttpHeaderAccepts", "localVarHttpHeaderAccept", - "localVarHttpContentTypes", "localVarHttpContentType", - "localVarStatusCode", - // C# reserved words - "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", - "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", - "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", - "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", - "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", - "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", - "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", - "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", - "virtual", "void", "volatile", "while") - ); - - // TODO: Either include fully qualified names here or handle in DefaultCodegen via lastIndexOf(".") search - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "string", - "bool?", - "double?", - "decimal?", - "int?", - "long?", - "float?", - "byte[]", - "ICollection", - "Collection", - "List", - "Dictionary", - "DateTime?", - "DateTimeOffset?", - "String", - "Boolean", - "Double", - "Int32", - "Int64", - "Float", - "Guid?", - "System.IO.Stream", // not really a primitive, we include it to avoid model import - "Object") - ); + collectionTypes = + new HashSet(Arrays.asList("IList", "List", "ICollection", "Collection", + "IEnumerable")); + + mapTypes = new HashSet(Arrays.asList("IDictionary")); + + setReservedWordsLowerCase(Arrays.asList( + // set "client" as a reserved word to avoid conflicts with IO.Swagger.Client + // this is a workaround and can be removed if c# api client is updated to use + // fully qualified name + "client", + "parameter", + // local variable names in API methods (endpoints) + "localVarPath", "localVarPathParams", + "localVarQueryParams", + "localVarHeaderParams", + "localVarFormParams", + "localVarFileParams", + "localVarStatusCode", + "localVarResponse", + "localVarPostBody", + "localVarHttpHeaderAccepts", + "localVarHttpHeaderAccept", + "localVarHttpContentTypes", + "localVarHttpContentType", + "localVarStatusCode", + // C# reserved words + "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", + "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", + "double", "else", "enum", "event", "explicit", "extern", "false", "finally", + "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", + "interface", "internal", "is", "lock", "long", "namespace", "new", "null", + "object", "operator", "out", "override", "params", "private", "protected", + "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", + "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", + "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", + "virtual", "void", "volatile", "while")); + + // TODO: Either include fully qualified names here or handle in DefaultCodegen via + // lastIndexOf(".") search + languageSpecificPrimitives = + new HashSet(Arrays.asList("String", "string", "bool?", "double?", + "decimal?", "int?", "long?", "float?", "byte[]", "ICollection", + "Collection", "List", "Dictionary", "DateTime?", "DateTimeOffset?", + "String", "Boolean", "Double", "Int32", "Int64", "Float", "Guid?", + "System.IO.Stream", // not really a primitive, we include it to avoid model + // import + "Object")); instantiationTypes.put("array", "List"); instantiationTypes.put("list", "List"); @@ -163,20 +149,24 @@ public void setOptionalMethodArgumentFlag(boolean flag) { protected void addOption(String key, String description, String defaultValue) { CliOption option = new CliOption(key, description); - if (defaultValue != null) option.defaultValue(defaultValue); + if (defaultValue != null) + option.defaultValue(defaultValue); cliOptions.add(option); } protected void addSwitch(String key, String description, Boolean defaultValue) { CliOption option = CliOption.newBoolean(key, description); - if (defaultValue != null) option.defaultValue(defaultValue.toString()); + if (defaultValue != null) + option.defaultValue(defaultValue.toString()); cliOptions.add(option); } public void useDateTimeOffset(boolean flag) { this.useDateTimeOffsetFlag = flag; - if (flag) typeMapping.put("datetime", "DateTimeOffset?"); - else typeMapping.put("datetime", "DateTime?"); + if (flag) + typeMapping.put("datetime", "DateTimeOffset?"); + else + typeMapping.put("datetime", "DateTime?"); } @Override @@ -203,71 +193,81 @@ public void processOpts() { } else { additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); } - + // {{packageTitle}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_TITLE)) { setPackageTitle((String) additionalProperties.get(CodegenConstants.PACKAGE_TITLE)); } else { additionalProperties.put(CodegenConstants.PACKAGE_TITLE, packageTitle); } - + // {{packageProductName}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_PRODUCTNAME)) { - setPackageProductName((String) additionalProperties.get(CodegenConstants.PACKAGE_PRODUCTNAME)); + setPackageProductName((String) additionalProperties + .get(CodegenConstants.PACKAGE_PRODUCTNAME)); } else { additionalProperties.put(CodegenConstants.PACKAGE_PRODUCTNAME, packageProductName); } // {{packageDescription}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_DESCRIPTION)) { - setPackageDescription((String) additionalProperties.get(CodegenConstants.PACKAGE_DESCRIPTION)); + setPackageDescription((String) additionalProperties + .get(CodegenConstants.PACKAGE_DESCRIPTION)); } else { additionalProperties.put(CodegenConstants.PACKAGE_DESCRIPTION, packageDescription); } - + // {{packageCompany}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_COMPANY)) { setPackageCompany((String) additionalProperties.get(CodegenConstants.PACKAGE_COMPANY)); } else { additionalProperties.put(CodegenConstants.PACKAGE_COMPANY, packageCompany); } - + // {{packageCopyright}} if (additionalProperties.containsKey(CodegenConstants.PACKAGE_COPYRIGHT)) { - setPackageCopyright((String) additionalProperties.get(CodegenConstants.PACKAGE_COPYRIGHT)); + setPackageCopyright((String) additionalProperties + .get(CodegenConstants.PACKAGE_COPYRIGHT)); } else { additionalProperties.put(CodegenConstants.PACKAGE_COPYRIGHT, packageCopyright); } - + // {{useDateTimeOffset}} if (additionalProperties.containsKey(CodegenConstants.USE_DATETIME_OFFSET)) { - useDateTimeOffset(Boolean.valueOf(additionalProperties.get(CodegenConstants.USE_DATETIME_OFFSET).toString())); + useDateTimeOffset(Boolean.valueOf(additionalProperties.get( + CodegenConstants.USE_DATETIME_OFFSET).toString())); } additionalProperties.put(CodegenConstants.USE_DATETIME_OFFSET, useDateTimeOffsetFlag); if (additionalProperties.containsKey(CodegenConstants.USE_COLLECTION)) { - setUseCollection(Boolean.valueOf(additionalProperties.get(CodegenConstants.USE_COLLECTION).toString())); + setUseCollection(Boolean.valueOf(additionalProperties.get( + CodegenConstants.USE_COLLECTION).toString())); } if (additionalProperties.containsKey(CodegenConstants.RETURN_ICOLLECTION)) { - setReturnICollection(Boolean.valueOf(additionalProperties.get(CodegenConstants.RETURN_ICOLLECTION).toString())); + setReturnICollection(Boolean.valueOf(additionalProperties.get( + CodegenConstants.RETURN_ICOLLECTION).toString())); } if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES)) { - setOptionalEmitDefaultValue(Boolean.valueOf(additionalProperties.get(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES).toString())); + setOptionalEmitDefaultValue(Boolean.valueOf(additionalProperties.get( + CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES).toString())); } if (additionalProperties.containsKey(CodegenConstants.INTERFACE_PREFIX)) { - String useInterfacePrefix = additionalProperties.get(CodegenConstants.INTERFACE_PREFIX).toString(); - if("false".equals(useInterfacePrefix.toLowerCase())) { + String useInterfacePrefix = + additionalProperties.get(CodegenConstants.INTERFACE_PREFIX).toString(); + if ("false".equals(useInterfacePrefix.toLowerCase())) { setInterfacePrefix(""); - } else if(!"true".equals(useInterfacePrefix.toLowerCase())) { - // NOTE: if user passes "true" explicitly, we use the default I- prefix. The other supported case here is a custom prefix. + } else if (!"true".equals(useInterfacePrefix.toLowerCase())) { + // NOTE: if user passes "true" explicitly, we use the default I- prefix. The other + // supported case here is a custom prefix. setInterfacePrefix(sanitizeName(useInterfacePrefix)); } } - // This either updates additionalProperties with the above fixes, or sets the default if the option was not specified. + // This either updates additionalProperties with the above fixes, or sets the default if the + // option was not specified. additionalProperties.put(CodegenConstants.INTERFACE_PREFIX, interfacePrefix); } @@ -312,13 +312,14 @@ public Map postProcessOperations(Map objs) { if (this.collectionTypes.contains(typeMapping)) { operation.isListContainer = true; operation.returnContainer = operation.returnType; - if (this.returnICollection && ( - typeMapping.startsWith("List") || - typeMapping.startsWith("Collection"))) { + if (this.returnICollection + && (typeMapping.startsWith("List") || typeMapping + .startsWith("Collection"))) { // NOTE: ICollection works for both List and Collection int genericStart = typeMapping.indexOf("<"); if (genericStart > 0) { - operation.returnType = "ICollection" + typeMapping.substring(genericStart); + operation.returnType = + "ICollection" + typeMapping.substring(genericStart); } } } else { @@ -341,12 +342,14 @@ protected void processOperation(CodegenOperation operation) { @Override public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + apiPackage(); + return outputFolder + File.separator + sourceFolder + File.separator + packageName + + File.separator + apiPackage(); } @Override public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + modelPackage(); + return outputFolder + File.separator + sourceFolder + File.separator + packageName + + File.separator + modelPackage(); } @Override @@ -357,14 +360,16 @@ public String toModelFilename(String name) { @Override public String toOperationId(String operationId) { - // throw exception if method name is empty (should not occur as an auto-generated method name will be used) + // throw exception if method name is empty (should not occur as an auto-generated method + // name will be used) if (StringUtils.isEmpty(operationId)) { throw new RuntimeException("Empty method name (operationId) not allowed"); } // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } @@ -416,11 +421,11 @@ public String toParamName(String name) { } return name; - } + } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -484,13 +489,13 @@ public String toDefaultValue(Property p) { if (p instanceof StringProperty) { StringProperty dp = (StringProperty) p; if (dp.getDefault() != null) { - String _default = dp.getDefault(); - if (dp.getEnum() == null) { - return "\"" + _default + "\""; - } else { - // convert to enum var name later in postProcessModels - return _default; - } + String _default = dp.getDefault(); + if (dp.getEnum() == null) { + return "\"" + _default + "\""; + } else { + // convert to enum var name later in postProcessModels + return _default; + } } } else if (p instanceof BooleanProperty) { BooleanProperty dp = (BooleanProperty) p; @@ -570,13 +575,16 @@ public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -612,27 +620,27 @@ public void setPackageName(String packageName) { public void setPackageVersion(String packageVersion) { this.packageVersion = packageVersion; } - + public void setPackageTitle(String packageTitle) { - this.packageTitle = packageTitle; - } - + this.packageTitle = packageTitle; + } + public void setPackageProductName(String packageProductName) { - this.packageProductName = packageProductName; - } + this.packageProductName = packageProductName; + } + + public void setPackageDescription(String packageDescription) { + this.packageDescription = packageDescription; + } - public void setPackageDescription(String packageDescription) { - this.packageDescription = packageDescription; - } - public void setPackageCompany(String packageCompany) { - this.packageCompany = packageCompany; - } - + this.packageCompany = packageCompany; + } + public void setPackageCopyright(String packageCopyright) { - this.packageCopyright = packageCopyright; - } - + this.packageCopyright = packageCopyright; + } + public void setSourceFolder(String sourceFolder) { this.sourceFolder = sourceFolder; } 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 index 8f97b524d7b..8d6cd7b214c 100644 --- 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 @@ -59,7 +59,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code 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 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"; @@ -75,7 +76,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code protected boolean hideGenerationTimestamp = false; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; - protected boolean supportJava6= false; + protected boolean supportJava6 = false; public AbstractJavaCodegen() { super(); @@ -86,65 +87,83 @@ public AbstractJavaCodegen() { modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); - setReservedWordsLowerCase( - Arrays.asList( + setReservedWordsLowerCase(Arrays.asList( // used as internal variables, can collide with parameter names - "localVarPath", "localVarQueryParams", "localVarHeaderParams", "localVarFormParams", - "localVarPostBody", "localVarAccepts", "localVarAccept", "localVarContentTypes", - "localVarContentType", "localVarAuthNames", "localReturnType", - "ApiClient", "ApiException", "ApiResponse", "Configuration", "StringUtil", + "localVarPath", "localVarQueryParams", "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") - ); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Object", - "byte[]") - ); + "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")); + + 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.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.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(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")); CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use"); Map dateOptions = new HashMap(); @@ -163,48 +182,59 @@ public void processOpts() { super.processOpts(); if (additionalProperties.containsKey(SUPPORT_JAVA6)) { - this.setSupportJava6(Boolean.valueOf(additionalProperties.get(SUPPORT_JAVA6).toString())); + 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)); + 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)); + 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); + 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)); + 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); + 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 + // 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 + // 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 + // 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)); + this.setArtifactVersion((String) additionalProperties + .get(CodegenConstants.ARTIFACT_VERSION)); } else { - //not set, use to be passed to template + // not set, use to be passed to template additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); } @@ -215,21 +245,25 @@ public void processOpts() { } if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_DESCRIPTION)) { - this.setArtifactDescription((String) additionalProperties.get(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)); + 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)); + this.setScmDeveloperConnection((String) additionalProperties + .get(CodegenConstants.SCM_DEVELOPER_CONNECTION)); } else { - additionalProperties.put(CodegenConstants.SCM_DEVELOPER_CONNECTION, scmDeveloperConnection); + additionalProperties.put(CodegenConstants.SCM_DEVELOPER_CONNECTION, + scmDeveloperConnection); } if (additionalProperties.containsKey(CodegenConstants.SCM_URL)) { @@ -239,27 +273,33 @@ public void processOpts() { } if (additionalProperties.containsKey(CodegenConstants.DEVELOPER_NAME)) { - this.setDeveloperName((String) additionalProperties.get(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)); + 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)); + this.setDeveloperOrganization((String) additionalProperties + .get(CodegenConstants.DEVELOPER_ORGANIZATION)); } else { - additionalProperties.put(CodegenConstants.DEVELOPER_ORGANIZATION, developerOrganization); + additionalProperties + .put(CodegenConstants.DEVELOPER_ORGANIZATION, developerOrganization); } if (additionalProperties.containsKey(CodegenConstants.DEVELOPER_ORGANIZATION_URL)) { - this.setDeveloperOrganizationUrl((String) additionalProperties.get(CodegenConstants.DEVELOPER_ORGANIZATION_URL)); + this.setDeveloperOrganizationUrl((String) additionalProperties + .get(CodegenConstants.DEVELOPER_ORGANIZATION_URL)); } else { - additionalProperties.put(CodegenConstants.DEVELOPER_ORGANIZATION_URL, developerOrganizationUrl); + additionalProperties.put(CodegenConstants.DEVELOPER_ORGANIZATION_URL, + developerOrganizationUrl); } if (additionalProperties.containsKey(CodegenConstants.LICENSE_NAME)) { @@ -279,26 +319,31 @@ public void processOpts() { } if (additionalProperties.containsKey(CodegenConstants.LOCAL_VARIABLE_PREFIX)) { - this.setLocalVariablePrefix((String) additionalProperties.get(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())); + 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())); + 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 + // 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())); + this.setFullJavaUtil(Boolean.valueOf(additionalProperties.get(FULL_JAVA_UTIL) + .toString())); } if (fullJavaUtil) { @@ -333,8 +378,10 @@ public void processOpts() { 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"); + 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"); @@ -349,14 +396,15 @@ public void processOpts() { 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"); + importMapping.put("com.fasterxml.jackson.annotation.JsonProperty", + "com.fasterxml.jackson.annotation.JsonCreator"); - if(additionalProperties.containsKey(DATE_LIBRARY)) { + if (additionalProperties.containsKey(DATE_LIBRARY)) { setDateLibrary(additionalProperties.get("dateLibrary").toString()); additionalProperties.put(dateLibrary, "true"); } - if("joda".equals(dateLibrary)) { + if ("joda".equals(dateLibrary)) { typeMapping.put("date", "LocalDate"); typeMapping.put("DateTime", "DateTime"); @@ -380,7 +428,8 @@ public void processOpts() { 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 + // 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)) { @@ -400,7 +449,7 @@ private void sanitizeConfig() { @Override public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -449,14 +498,15 @@ public String toApiTestFilename(String 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'. + 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 ("_".equals(name)) { + name = "_u"; } // if it's all uppper case, do nothing @@ -464,7 +514,7 @@ public String toVarName(String name) { return name; } - if(startsWithTwoUppercaseLetters(name)){ + if (startsWithTwoUppercaseLetters(name)) { name = name.substring(0, 2).toLowerCase() + name.substring(2); } @@ -482,8 +532,9 @@ public String toVarName(String name) { private boolean startsWithTwoUppercaseLetters(String name) { boolean startsWithTwoUppercaseLetters = false; - if(name.length() > 1) { - startsWithTwoUppercaseLetters = name.substring(0, 2).equals(name.substring(0, 2).toUpperCase()); + if (name.length() > 1) { + startsWithTwoUppercaseLetters = + name.substring(0, 2).equals(name.substring(0, 2).toUpperCase()); } return startsWithTwoUppercaseLetters; } @@ -521,14 +572,18 @@ public String toModelName(final String name) { // 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); + 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); + 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; } @@ -547,7 +602,8 @@ public String getTypeDeclaration(Property p) { 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"); + 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; } @@ -556,7 +612,8 @@ public String getTypeDeclaration(Property p) { 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"); + 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; } @@ -600,9 +657,9 @@ public String toDefaultValue(Property p) { } else if (p instanceof LongProperty) { LongProperty dp = (LongProperty) p; if (dp.getDefault() != null) { - return dp.getDefault().toString()+"l"; + return dp.getDefault().toString() + "l"; } - return "null"; + return "null"; } else if (p instanceof DoubleProperty) { DoubleProperty dp = (DoubleProperty) p; if (dp.getDefault() != null) { @@ -728,7 +785,8 @@ public String toOperationId(String operationId) { // 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); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + newOperationId); return newOperationId; } @@ -738,7 +796,7 @@ public String toOperationId(String operationId) { @Override public CodegenModel fromModel(String name, Model model, Map allDefinitions) { CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); - if(codegenModel.description != null) { + if (codegenModel.description != null) { codegenModel.imports.add("ApiModel"); } if (codegenModel.discriminator != null && additionalProperties.containsKey("jackson")) { @@ -747,18 +805,21 @@ public CodegenModel fromModel(String name, Model model, Map allDe } 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); + 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 (serializeBigDecimalAsString) { if (property.baseType.equals("BigDecimal")) { // we serialize BigDecimal as `string` to avoid precision loss - property.vendorExtensions.put("extraAnnotation", "@JsonSerialize(using = ToStringSerializer.class)"); + property.vendorExtensions.put("extraAnnotation", + "@JsonSerialize(using = ToStringSerializer.class)"); // this requires some more imports to be added for this model... model.imports.add("ToStringSerializer"); @@ -767,12 +828,12 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert } if ("array".equals(property.containerType)) { - model.imports.add("ArrayList"); + model.imports.add("ArrayList"); } else if ("map".equals(property.containerType)) { - model.imports.add("HashMap"); + model.imports.add("HashMap"); } - if(!BooleanUtils.toBoolean(model.isEnum)) { + if (!BooleanUtils.toBoolean(model.isEnum)) { // needed by all pojos, but not enums model.imports.add("ApiModelProperty"); model.imports.add("ApiModel"); @@ -780,12 +841,13 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert } @Override - public void postProcessParameter(CodegenParameter parameter) { } + 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"); + List> recursiveImports = + (List>) objs.get("imports"); if (recursiveImports == null) return objs; @@ -795,7 +857,7 @@ public Map postProcessModels(Map objs) { // 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(); + Map newImportMap = new HashMap(); newImportMap.put("import", importMapping.get(_import)); listIterator.add(newImportMap); } @@ -813,7 +875,7 @@ public Map postProcessOperations(Map objs) { for (Iterator> itr = imports.iterator(); itr.hasNext();) { String _import = itr.next().get("import"); if (pattern.matcher(_import).matches()) { - itr.remove(); + itr.remove(); } } return objs; @@ -821,12 +883,12 @@ public Map postProcessOperations(Map objs) { @Override public void preprocessSwagger(Swagger swagger) { - if (swagger == null || swagger.getPaths() == null){ + if (swagger == null || swagger.getPaths() == null) { return; } for (String pathname : swagger.getPaths().keySet()) { Path path = swagger.getPath(pathname); - if (path.getOperations() == null){ + if (path.getOperations() == null) { continue; } for (Operation operation : path.getOperations()) { @@ -836,9 +898,12 @@ public void preprocessSwagger(Swagger swagger) { hasFormParameters = true; } } - String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json"; - String contentType = operation.getConsumes() == null || operation.getConsumes().isEmpty() - ? defaultContentType : operation.getConsumes().get(0); + String defaultContentType = + hasFormParameters ? "application/x-www-form-urlencoded" + : "application/json"; + String contentType = + operation.getConsumes() == null || operation.getConsumes().isEmpty() ? defaultContentType + : operation.getConsumes().get(0); String accepts = getAccept(operation); operation.setVendorExtension("x-contentType", contentType); operation.setVendorExtension("x-accepts", accepts); @@ -876,15 +941,16 @@ private static String getAccept(Operation operation) { 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 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) { @@ -903,8 +969,8 @@ public String toEnumVarName(String value, String datatype) { } // number - if ("Integer".equals(datatype) || "Long".equals(datatype) || - "Float".equals(datatype) || "Double".equals(datatype)) { + 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_"); @@ -923,8 +989,8 @@ public String toEnumVarName(String value, String datatype) { @Override public String toEnumValue(String value, String datatype) { - if ("Integer".equals(datatype) || "Long".equals(datatype) || - "Float".equals(datatype) || "Double".equals(datatype)) { + if ("Integer".equals(datatype) || "Long".equals(datatype) || "Float".equals(datatype) + || "Double".equals(datatype)) { return value; } else { return "\"" + escapeText(value) + "\""; @@ -932,13 +998,16 @@ public String toEnumValue(String value, String datatype) { } @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + 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) { + 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 @@ -946,7 +1015,7 @@ private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, Code // 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) { + if (!parentCodegenModel.hasEnums) { return codegenModel; } @@ -974,10 +1043,10 @@ private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, Code } } - if(removedChildEnum) { + 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) { + for (CodegenProperty codegenProperty : codegenProperties) { count += 1; codegenProperty.hasMore = (count < numVars) ? true : false; } @@ -987,9 +1056,10 @@ private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, Code } 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.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)) { + if (Strings.isNullOrEmpty(packageName)) { return "invalidPackageName"; } return packageName; @@ -1076,7 +1146,7 @@ public void setSerializableModel(Boolean serializableModel) { } private String sanitizePath(String p) { - //prefer replace a ", instead of a fuLL URL encode for readability + // prefer replace a ", instead of a fuLL URL encode for readability return p.replaceAll("\"", "%22"); } @@ -1111,7 +1181,7 @@ private String deriveInvokerPackageName(String input) { StringBuilder sb = new StringBuilder(); String delim = ""; - for (String p : Arrays.copyOf(parts, parts.length-1)) { + for (String p : Arrays.copyOf(parts, parts.length - 1)) { sb.append(delim).append(p); delim = "."; } @@ -1132,7 +1202,7 @@ public boolean convertPropertyToBoolean(String propertyKey) { booleanValue = Boolean.valueOf(additionalProperties.get(propertyKey).toString()); } - return booleanValue; + return booleanValue; } public void writePropertyBack(String propertyKey, boolean value) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java index 3dc349edb70..6c89da8ec2a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java @@ -11,28 +11,28 @@ import java.util.*; -public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen implements BeanValidationFeatures { +public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen implements + BeanValidationFeatures { /** - * Name of the sub-directory in "src/main/resource" where to find the - * Mustache template for the JAX-RS Codegen. + * Name of the sub-directory in "src/main/resource" where to find the Mustache template for the + * JAX-RS Codegen. */ protected static final String JAXRS_TEMPLATE_DIRECTORY_NAME = "JavaJaxRS"; protected String implFolder = "src/main/java"; protected String testResourcesFolder = "src/test/resources"; protected String title = "Swagger Server"; - protected boolean useBeanValidation = true; + protected boolean useBeanValidation = true; static Logger LOGGER = LoggerFactory.getLogger(AbstractJavaJAXRSServerCodegen.class); - public AbstractJavaJAXRSServerCodegen() - { + public AbstractJavaJAXRSServerCodegen() { super(); sourceFolder = "src/gen/java"; invokerPackage = "io.swagger.api"; artifactId = "swagger-jaxrs-server"; - dateLibrary = "legacy"; //TODO: add joda support to all jax-rs + dateLibrary = "legacy"; // TODO: add joda support to all jax-rs apiPackage = "io.swagger.api"; modelPackage = "io.swagger.model"; @@ -41,10 +41,12 @@ public AbstractJavaJAXRSServerCodegen() // java inflector uses the jackson lib additionalProperties.put("jackson", "true"); - cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC)); + cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, + CodegenConstants.IMPL_FOLDER_DESC)); cliOptions.add(new CliOption("title", "a title describing the application")); - cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, + "Use BeanValidation API annotations")); } @@ -54,8 +56,7 @@ public AbstractJavaJAXRSServerCodegen() // =============== @Override - public CodegenType getTag() - { + public CodegenType getTag() { return CodegenType.SERVER; } @@ -67,48 +68,48 @@ public void processOpts() { implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); } - if (additionalProperties.containsKey(USE_BEANVALIDATION)) { - this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION)); - } + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { + this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION)); + } - if (useBeanValidation) { - writePropertyBack(USE_BEANVALIDATION, useBeanValidation); - } + if (useBeanValidation) { + writePropertyBack(USE_BEANVALIDATION, useBeanValidation); + } } @Override public void preprocessSwagger(Swagger swagger) { - if ( "/".equals(swagger.getBasePath()) ) { + if ("/".equals(swagger.getBasePath())) { swagger.setBasePath(""); } String host = swagger.getHost(); String port = "8080"; // Default value for a JEE Server - if ( host != null ) { + if (host != null) { String[] parts = host.split(":"); - if ( parts.length > 1 ) { + if (parts.length > 1) { port = parts[1]; } } this.additionalProperties.put("serverPort", port); - if ( swagger.getPaths() != null ) { - for ( String pathname : swagger.getPaths().keySet() ) { + if (swagger.getPaths() != null) { + for (String pathname : swagger.getPaths().keySet()) { Path path = swagger.getPath(pathname); - if ( path.getOperations() != null ) { - for ( Operation operation : path.getOperations() ) { - if ( operation.getTags() != null ) { + if (path.getOperations() != null) { + for (Operation operation : path.getOperations()) { + if (operation.getTags() != null) { List> tags = new ArrayList>(); - for ( String tag : operation.getTags() ) { + for (String tag : operation.getTags()) { Map value = new HashMap(); value.put("tag", tag); value.put("hasMore", "true"); tags.add(value); } - if ( tags.size() > 0 ) { + if (tags.size() > 0) { tags.get(tags.size() - 1).remove("hasMore"); } - if ( operation.getTags().size() > 0 ) { + if (operation.getTags().size() > 0) { String tag = operation.getTags().get(0); operation.setTags(Arrays.asList(tag)); } @@ -124,60 +125,62 @@ public void preprocessSwagger(Swagger swagger) { public Map postProcessOperations(Map objs) { @SuppressWarnings("unchecked") Map operations = (Map) objs.get("operations"); - if ( operations != null ) { + if (operations != null) { @SuppressWarnings("unchecked") List ops = (List) operations.get("operation"); - for ( CodegenOperation operation : ops ) { + for (CodegenOperation operation : ops) { boolean isMultipartPost = false; List> consumes = operation.consumes; - if(consumes != null) { - for(Map consume : consumes) { + if (consumes != null) { + for (Map consume : consumes) { String mt = consume.get("mediaType"); - if(mt != null) { - if(mt.startsWith("multipart/form-data")) { + if (mt != null) { + if (mt.startsWith("multipart/form-data")) { isMultipartPost = true; } } } } - for(CodegenParameter parameter : operation.allParams) { - if(isMultipartPost) { + for (CodegenParameter parameter : operation.allParams) { + if (isMultipartPost) { parameter.vendorExtensions.put("x-multipart", "true"); } } List responses = operation.responses; - if ( responses != null ) { - for ( CodegenResponse resp : responses ) { - if ( "0".equals(resp.code) ) { + if (responses != null) { + for (CodegenResponse resp : responses) { + if ("0".equals(resp.code)) { resp.code = "200"; } } } - if ( operation.returnType == null ) { + if (operation.returnType == null) { operation.returnType = "void"; - // set vendorExtensions.x-java-is-response-void to true as returnType is set to "void" + // set vendorExtensions.x-java-is-response-void to true as returnType is set to + // "void" operation.vendorExtensions.put("x-java-is-response-void", true); - } else if ( operation.returnType.startsWith("List") ) { + } else if (operation.returnType.startsWith("List")) { String rt = operation.returnType; int end = rt.lastIndexOf(">"); - if ( end > 0 ) { + if (end > 0) { operation.returnType = rt.substring("List<".length(), end).trim(); operation.returnContainer = "List"; } - } else if ( operation.returnType.startsWith("Map") ) { + } else if (operation.returnType.startsWith("Map")) { String rt = operation.returnType; int end = rt.lastIndexOf(">"); - if ( end > 0 ) { - operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim(); + if (end > 0) { + operation.returnType = + rt.substring("Map<".length(), end).split(",")[1].trim(); operation.returnContainer = "Map"; } - } else if ( operation.returnType.startsWith("Set") ) { + } else if (operation.returnType.startsWith("Set")) { String rt = operation.returnType; int end = rt.lastIndexOf(">"); - if ( end > 0 ) { + if (end > 0) { operation.returnType = rt.substring("Set<".length(), end).trim(); operation.returnContainer = "Set"; } @@ -190,7 +193,7 @@ public Map postProcessOperations(Map objs) { @Override public String toApiName(final String name) { String computed = name; - if ( computed.length() == 0 ) { + if (computed.length() == 0) { return "DefaultApi"; } computed = sanitizeName(computed); @@ -201,15 +204,19 @@ public String toApiName(final String name) { public String apiFilename(String templateName, String tag) { String result = super.apiFilename(templateName, tag); - if ( templateName.endsWith("Impl.mustache") ) { + if (templateName.endsWith("Impl.mustache")) { int ix = result.lastIndexOf('/'); - result = result.substring(0, ix) + "/impl" + result.substring(ix, result.length() - 5) + "ServiceImpl.java"; + result = + result.substring(0, ix) + "/impl" + result.substring(ix, result.length() - 5) + + "ServiceImpl.java"; result = result.replace(apiFileFolder(), implFileFolder(implFolder)); - } else if ( templateName.endsWith("Factory.mustache") ) { + } else if (templateName.endsWith("Factory.mustache")) { int ix = result.lastIndexOf('/'); - result = result.substring(0, ix) + "/factories" + result.substring(ix, result.length() - 5) + "ServiceFactory.java"; + result = + result.substring(0, ix) + "/factories" + + result.substring(ix, result.length() - 5) + "ServiceFactory.java"; result = result.replace(apiFileFolder(), implFileFolder(implFolder)); - } else if ( templateName.endsWith("Service.mustache") ) { + } else if (templateName.endsWith("Service.mustache")) { int ix = result.lastIndexOf('.'); result = result.substring(0, ix) + "Service.java"; } @@ -220,8 +227,8 @@ private String implFileFolder(String output) { return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/'); } - public void setUseBeanValidation(boolean useBeanValidation) { - this.useBeanValidation = useBeanValidation; - } + public void setUseBeanValidation(boolean useBeanValidation) { + this.useBeanValidation = useBeanValidation; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java index 8d9c3e6c7fc..4826c1ac1e6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java @@ -31,7 +31,8 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg public static final String VARIABLE_NAMING_CONVENTION = "variableNamingConvention"; public static final String PACKAGE_PATH = "packagePath"; public static final String SRC_BASE_PATH = "srcBasePath"; - // composerVendorName/composerProjectName has be replaced by gitUserId/gitRepoId. prepare to remove these. + // composerVendorName/composerProjectName has be replaced by gitUserId/gitRepoId. prepare to + // remove these. // public static final String COMPOSER_VENDOR_NAME = "composerVendorName"; // public static final String COMPOSER_PROJECT_NAME = "composerProjectName"; // protected String composerVendorName = null; @@ -44,7 +45,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg protected String docsBasePath = "docs"; protected String apiDirName = "Api"; protected String modelDirName = "Model"; - protected String variableNamingConvention= "snake_case"; + protected String variableNamingConvention = "snake_case"; protected String apiDocPath = docsBasePath + "/" + apiDirName; protected String modelDocPath = docsBasePath + "/" + modelDirName; @@ -60,33 +61,30 @@ public AbstractPhpCodegen() { apiPackage = invokerPackage + "\\" + apiDirName; modelPackage = invokerPackage + "\\" + modelDirName; - setReservedWordsLowerCase( - Arrays.asList( - // local variables used in api methods (endpoints) - "resourcePath", "httpBody", "queryParams", "headerParams", - "formParams", "_header_accept", "_tempBody", - - // PHP reserved words - "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor") - ); + setReservedWordsLowerCase(Arrays.asList( + // local variables used in api methods (endpoints) + "resourcePath", + "httpBody", + "queryParams", + "headerParams", + "formParams", + "_header_accept", + "_tempBody", + + // PHP reserved words + "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", + "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", + "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", + "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", + "function", "global", "goto", "if", "implements", "include", "include_once", + "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", + "print", "private", "protected", "public", "require", "require_once", "return", + "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor")); // ref: http://php.net/manual/en/language.types.intro.php - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "bool", - "boolean", - "int", - "integer", - "double", - "float", - "string", - "object", - "DateTime", - "mixed", - "number", - "void", - "byte") - ); + languageSpecificPrimitives = + new HashSet(Arrays.asList("bool", "boolean", "int", "integer", "double", + "float", "string", "object", "DateTime", "mixed", "number", "void", "byte")); instantiationTypes.put("array", "array"); instantiationTypes.put("map", "map"); @@ -117,18 +115,28 @@ public AbstractPhpCodegen() { typeMapping.put("ByteArray", "string"); typeMapping.put("UUID", "string"); - cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); - cliOptions.add(new CliOption(VARIABLE_NAMING_CONVENTION, "naming convention of variable name, e.g. camelCase.") - .defaultValue("snake_case")); - cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, "The main namespace to use for all classes. e.g. Yay\\Pets")); - cliOptions.add(new CliOption(PACKAGE_PATH, "The main package name for classes. e.g. GeneratedPetstore")); - cliOptions.add(new CliOption(SRC_BASE_PATH, "The directory under packagePath to serve as source root.")); - // cliOptions.add(new CliOption(COMPOSER_VENDOR_NAME, "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. yaypets. IMPORTANT NOTE (2016/03): composerVendorName will be deprecated and replaced by gitUserId in the next swagger-codegen release")); - cliOptions.add(new CliOption(CodegenConstants.GIT_USER_ID, CodegenConstants.GIT_USER_ID_DESC)); - // cliOptions.add(new CliOption(COMPOSER_PROJECT_NAME, "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client. IMPORTANT NOTE (2016/03): composerProjectName will be deprecated and replaced by gitRepoId in the next swagger-codegen release")); - cliOptions.add(new CliOption(CodegenConstants.GIT_REPO_ID, CodegenConstants.GIT_REPO_ID_DESC)); - cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "The version to use in the composer package version field. e.g. 1.2.3")); + 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(VARIABLE_NAMING_CONVENTION, + "naming convention of variable name, e.g. camelCase.").defaultValue("snake_case")); + cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, + "The main namespace to use for all classes. e.g. Yay\\Pets")); + cliOptions.add(new CliOption(PACKAGE_PATH, + "The main package name for classes. e.g. GeneratedPetstore")); + cliOptions.add(new CliOption(SRC_BASE_PATH, + "The directory under packagePath to serve as source root.")); + // cliOptions.add(new CliOption(COMPOSER_VENDOR_NAME, + // "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. yaypets. IMPORTANT NOTE (2016/03): composerVendorName will be deprecated and replaced by gitUserId in the next swagger-codegen release")); + cliOptions.add(new CliOption(CodegenConstants.GIT_USER_ID, + CodegenConstants.GIT_USER_ID_DESC)); + // cliOptions.add(new CliOption(COMPOSER_PROJECT_NAME, + // "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client. IMPORTANT NOTE (2016/03): composerProjectName will be deprecated and replaced by gitRepoId in the next swagger-codegen release")); + cliOptions.add(new CliOption(CodegenConstants.GIT_REPO_ID, + CodegenConstants.GIT_REPO_ID_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, + "The version to use in the composer package version field. e.g. 1.2.3")); } @Override @@ -148,7 +156,8 @@ public void processOpts() { } if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { - this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); + this.setInvokerPackage((String) additionalProperties + .get(CodegenConstants.INVOKER_PACKAGE)); } else { additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); } @@ -162,9 +171,9 @@ public void processOpts() { } // if (additionalProperties.containsKey(COMPOSER_PROJECT_NAME)) { - // this.setComposerProjectName((String) additionalProperties.get(COMPOSER_PROJECT_NAME)); + // this.setComposerProjectName((String) additionalProperties.get(COMPOSER_PROJECT_NAME)); // } else { - // additionalProperties.put(COMPOSER_PROJECT_NAME, composerProjectName); + // additionalProperties.put(COMPOSER_PROJECT_NAME, composerProjectName); // } if (additionalProperties.containsKey(CodegenConstants.GIT_USER_ID)) { @@ -174,9 +183,9 @@ public void processOpts() { } // if (additionalProperties.containsKey(COMPOSER_VENDOR_NAME)) { - // this.setComposerVendorName((String) additionalProperties.get(COMPOSER_VENDOR_NAME)); + // this.setComposerVendorName((String) additionalProperties.get(COMPOSER_VENDOR_NAME)); // } else { - // additionalProperties.put(COMPOSER_VENDOR_NAME, composerVendorName); + // additionalProperties.put(COMPOSER_VENDOR_NAME, composerVendorName); // } if (additionalProperties.containsKey(CodegenConstants.GIT_REPO_ID)) { @@ -186,13 +195,15 @@ public void processOpts() { } if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) { - this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION)); + this.setArtifactVersion((String) additionalProperties + .get(CodegenConstants.ARTIFACT_VERSION)); } else { additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); } if (additionalProperties.containsKey(VARIABLE_NAMING_CONVENTION)) { - this.setParameterNamingConvention((String) additionalProperties.get(VARIABLE_NAMING_CONVENTION)); + this.setParameterNamingConvention((String) additionalProperties + .get(VARIABLE_NAMING_CONVENTION)); } additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); @@ -223,9 +234,18 @@ public String toPackagePath(String packageName, String basePath) { } public String toSrcPath(String packageName, String basePath) { - packageName = packageName.replace(invokerPackage, ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + packageName = packageName.replace(invokerPackage, ""); // FIXME: a parameter should not be + // assigned. Also declare the methods + // parameters as 'final'. if (basePath != null && basePath.length() > 0) { - basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar; // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar; // FIXME: a + // parameter + // should not be + // assigned. Also + // declare the + // methods + // parameters as + // 'final'. } String regFirstPathSeparator; @@ -243,17 +263,17 @@ public String toSrcPath(String packageName, String basePath) { } return (basePath - // Replace period, backslash, forward slash with file separator in package name - + packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement(File.separator)) - // Trim prefix file separators from package path + // Replace period, backslash, forward slash with file separator in package name + + packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement(File.separator)) + // Trim prefix file separators from package path .replaceAll(regFirstPathSeparator, "")) - // Trim trailing file separators from the overall path - .replaceAll(regLastPathSeparator+ "$", ""); + // Trim trailing file separators from the overall path + .replaceAll(regLastPathSeparator + "$", ""); } - @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + @Override + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -311,8 +331,8 @@ public String getTypeDeclaration(Property p) { return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; } else if (p instanceof RefProperty) { String type = super.getTypeDeclaration(p); - return (!languageSpecificPrimitives.contains(type)) - ? "\\" + modelPackage + "\\" + type : type; + return (!languageSpecificPrimitives.contains(type)) ? "\\" + modelPackage + "\\" + type + : type; } return super.getTypeDeclaration(p); } @@ -366,26 +386,27 @@ public void setParameterNamingConvention(String variableNamingConvention) { } // public void setComposerVendorName(String composerVendorName) { - // this.composerVendorName = composerVendorName; + // this.composerVendorName = composerVendorName; // } // public void setComposerProjectName(String composerProjectName) { - // this.composerProjectName = composerProjectName; + // this.composerProjectName = composerProjectName; // } @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'. + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. if ("camelCase".equals(variableNamingConvention)) { - // return the name in camelCase style - // phone_number => phoneNumber - name = camelize(name, true); + // return the name in camelCase style + // phone_number => phoneNumber + name = camelize(name, true); } else { // default to snake case - // return the name in underscore style - // PhoneNumber => phone_number - name = underscore(name); + // return the name in underscore style + // PhoneNumber => phone_number + name = underscore(name); } // parameter name starting with number won't compile @@ -409,20 +430,25 @@ public String toModelName(String name) { name = name.replaceAll("\\]", ""); // Note: backslash ("\\") is allowed for e.g. "\\DateTime" - name = name.replaceAll("[^\\w\\\\]+", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = name.replaceAll("[^\\w\\\\]+", "_"); // FIXME: a parameter should not be assigned. + // Also declare the methods parameters as + // 'final'. // remove dollar sign name = name.replaceAll("$", ""); // model name cannot use reserved keyword if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -457,7 +483,8 @@ public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + camelize(sanitizeName("call_" + operationId), true)); operationId = "call_" + operationId; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java index cd9a5fd3432..85b3c5d4288 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java @@ -30,23 +30,15 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen { public AbstractScalaCodegen() { super(); - languageSpecificPrimitives.addAll(Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Int", - "Long", - "Float", - "Object", - "Any", - "List", - "Seq", - "Map")); - - 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.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); + languageSpecificPrimitives.addAll(Arrays.asList("String", "boolean", "Boolean", "Double", + "Int", "Long", "Float", "Object", "Any", "List", "Seq", "Map")); + + 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.SOURCE_FOLDER, + CodegenConstants.SOURCE_FOLDER_DESC)); } @Override @@ -67,8 +59,8 @@ public String getSourceFolder() { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -76,12 +68,14 @@ public String escapeReservedWord(String name) { @Override public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + return outputFolder + "/" + sourceFolder + "/" + + apiPackage().replace('.', File.separatorChar); } @Override public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + return outputFolder + "/" + sourceFolder + "/" + + modelPackage().replace('.', File.separatorChar); } @Override @@ -93,7 +87,7 @@ public String getTypeDeclaration(Property p) { } else if (p instanceof MapProperty) { MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); - + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; } return super.getTypeDeclaration(p); @@ -168,7 +162,8 @@ public Map postProcessModels(Map objs) { Iterator> iterator = imports.iterator(); while (iterator.hasNext()) { String _import = iterator.next().get("import"); - if (_import.startsWith(prefix)) iterator.remove(); + if (_import.startsWith(prefix)) + iterator.remove(); } return objs; } @@ -184,4 +179,4 @@ public String escapeUnsafeCharacters(String input) { return input.replace("*/", "*_/").replace("/*", "/_*"); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java index 888e76279dc..d2bd9127969 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -22,9 +22,10 @@ import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; -public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig { +public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements + CodegenConfig { - protected String modelPropertyNaming= "camelCase"; + protected String modelPropertyNaming = "camelCase"; protected Boolean supportsES6 = true; protected HashSet languageGenericTypes; @@ -38,31 +39,29 @@ public AbstractTypeScriptClientCodegen() { supportsInheritance = true; setReservedWordsLowerCase(Arrays.asList( // local variable names used in API methods (endpoints) - "varLocalPath", "queryParameters", "headerParams", "formParams", "useFormData", "varLocalDeferred", + "varLocalPath", + "queryParameters", + "headerParams", + "formParams", + "useFormData", + "varLocalDeferred", "requestOptions", // Typescript reserved words - "abstract", "await", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "let", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "transient", "true", "try", "typeof", "var", "void", "volatile", "while", "with", "yield")); - - languageSpecificPrimitives = new HashSet(Arrays.asList( - "string", - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Object", - "Array", - "Date", - "number", - "any", - "Error" - )); - - languageGenericTypes = new HashSet(Arrays.asList( - "Array" - )); + "abstract", "await", "boolean", "break", "byte", "case", "catch", "char", "class", + "const", "continue", "debugger", "default", "delete", "do", "double", "else", + "enum", "export", "extends", "false", "final", "finally", "float", "for", + "function", "goto", "if", "implements", "import", "in", "instanceof", "int", + "interface", "let", "long", "native", "new", "null", "package", "private", + "protected", "public", "return", "short", "static", "super", "switch", + "synchronized", "this", "throw", "transient", "true", "try", "typeof", "var", + "void", "volatile", "while", "with", "yield")); + + languageSpecificPrimitives = + new HashSet(Arrays.asList("string", "String", "boolean", "Boolean", + "Double", "Integer", "Long", "Float", "Object", "Array", "Date", "number", + "any", "Error")); + + languageGenericTypes = new HashSet(Arrays.asList("Array")); instantiationTypes.put("array", "Array"); @@ -83,14 +82,16 @@ public AbstractTypeScriptClientCodegen() { typeMapping.put("integer", "number"); typeMapping.put("Map", "any"); typeMapping.put("DateTime", "Date"); - //TODO binary should be mapped to byte array + // TODO binary should be mapped to byte array // mapped to String as a workaround typeMapping.put("binary", "string"); typeMapping.put("ByteArray", "string"); typeMapping.put("UUID", "string"); - cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase")); - cliOptions.add(new CliOption(CodegenConstants.SUPPORTS_ES6, CodegenConstants.SUPPORTS_ES6_DESC).defaultValue("false")); + cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, + CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase")); + cliOptions.add(new CliOption(CodegenConstants.SUPPORTS_ES6, + CodegenConstants.SUPPORTS_ES6_DESC).defaultValue("false")); } @@ -99,11 +100,13 @@ public void processOpts() { super.processOpts(); if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) { - setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); + setModelPropertyNaming((String) additionalProperties + .get(CodegenConstants.MODEL_PROPERTY_NAMING)); } if (additionalProperties.containsKey(CodegenConstants.SUPPORTS_ES6)) { - setSupportsES6(Boolean.valueOf(additionalProperties.get(CodegenConstants.SUPPORTS_ES6).toString())); + setSupportsES6(Boolean.valueOf(additionalProperties.get(CodegenConstants.SUPPORTS_ES6) + .toString())); additionalProperties.put("supportsES6", getSupportsES6()); } } @@ -114,8 +117,8 @@ public CodegenType getTag() { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -134,7 +137,8 @@ public String modelFileFolder() { @Override public String toParamName(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare + // the methods parameters as 'final'. // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) @@ -159,7 +163,8 @@ public String toVarName(String name) { @Override public String toModelName(String name) { - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. if (!StringUtils.isEmpty(modelNamePrefix)) { name = modelNamePrefix + "_" + name; @@ -172,20 +177,26 @@ public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { String modelName = camelize("model_" + name); - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + modelName); return modelName; } // model name starts with number if (name.matches("^\\d.*")) { - String modelName = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + String modelName = camelize("model_" + name); // e.g. 200Response => Model200Response + // (after camelize) + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + modelName); return modelName; } if (languageSpecificPrimitives.contains(name)) { String modelName = camelize("model_" + name); - LOGGER.warn(name + " (model name matches existing language type) cannot be used as a model name. Renamed to " + modelName); + LOGGER.warn(name + + " (model name matches existing language type) cannot be used as a model name. Renamed to " + + modelName); return modelName; } // camelize the model name @@ -208,7 +219,7 @@ public String getTypeDeclaration(Property p) { } else if (p instanceof MapProperty) { MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); - return "{ [key: string]: "+ getTypeDeclaration(inner) + "; }"; + return "{ [key: string]: " + getTypeDeclaration(inner) + "; }"; } else if (p instanceof FileProperty) { return "any"; } @@ -245,13 +256,12 @@ public String toOperationId(String operationId) { } public void setModelPropertyNaming(String naming) { - if ("original".equals(naming) || "camelCase".equals(naming) || - "PascalCase".equals(naming) || "snake_case".equals(naming)) { + if ("original".equals(naming) || "camelCase".equals(naming) || "PascalCase".equals(naming) + || "snake_case".equals(naming)) { this.modelPropertyNaming = naming; } else { - throw new IllegalArgumentException("Invalid model property naming '" + - naming + "'. Must be 'original', 'camelCase', " + - "'PascalCase' or 'snake_case'"); + throw new IllegalArgumentException("Invalid model property naming '" + naming + + "'. Must be 'original', 'camelCase', " + "'PascalCase' or 'snake_case'"); } } @@ -261,13 +271,17 @@ public String getModelPropertyNaming() { public String getNameUsingModelPropertyNaming(String name) { switch (CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.valueOf(getModelPropertyNaming())) { - case original: return name; - case camelCase: return camelize(name, true); - case PascalCase: return camelize(name); - case snake_case: return underscore(name); - default: throw new IllegalArgumentException("Invalid model property naming '" + - name + "'. Must be 'original', 'camelCase', " + - "'PascalCase' or 'snake_case'"); + case original: + return name; + case camelCase: + return camelize(name, true); + case PascalCase: + return camelize(name); + case snake_case: + return underscore(name); + default: + throw new IllegalArgumentException("Invalid model property naming '" + name + + "'. Must be 'original', 'camelCase', " + "'PascalCase' or 'snake_case'"); } } @@ -345,10 +359,12 @@ public Map postProcessModels(Map objs) { for (CodegenProperty var : cm.vars) { // name enum with model name, e.g. StatuEnum => Pet.StatusEnum if (Boolean.TRUE.equals(var.isEnum)) { - var.datatypeWithEnum = var.datatypeWithEnum.replace(var.enumName, cm.classname + "." + var.enumName); + var.datatypeWithEnum = + var.datatypeWithEnum.replace(var.enumName, cm.classname + "." + + var.enumName); } } - } + } return objs; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java index d77763a126d..8c8533f4f96 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java @@ -54,10 +54,10 @@ public class AkkaScalaClientCodegen extends AbstractScalaCodegen implements Code protected boolean renderJavadoc = true; protected boolean removeOAuthSecurities = true; /** - * If set to true, only the default response (the one with le lowest 2XX code) will be considered as a success, and all - * others as ApiErrors. - * If set to false, all responses defined in the model will be considered as a success upon reception. Only http errors, - * unmarshalling problems and any other RuntimeException will be considered as ApiErrors. + * If set to true, only the default response (the one with le lowest 2XX code) will be + * considered as a success, and all others as ApiErrors. If set to false, all responses defined + * in the model will be considered as a success upon reception. Only http errors, unmarshalling + * problems and any other RuntimeException will be considered as ApiErrors. */ protected boolean onlyOneSuccess = true; @@ -74,14 +74,11 @@ public AkkaScalaClientCodegen() { modelPackage = mainPackage + ".model"; invokerPackage = mainPackage + ".core"; - setReservedWordsLowerCase( - Arrays.asList( - "abstract", "case", "catch", "class", "def", "do", "else", "extends", - "false", "final", "finally", "for", "forSome", "if", "implicit", - "import", "lazy", "match", "new", "null", "object", "override", "package", - "private", "protected", "return", "sealed", "super", "this", "throw", - "trait", "try", "true", "type", "val", "var", "while", "with", "yield") - ); + setReservedWordsLowerCase(Arrays.asList("abstract", "case", "catch", "class", "def", "do", + "else", "extends", "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", "trait", + "try", "true", "type", "val", "var", "while", "with", "yield")); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.GROUP_ID, groupId); @@ -99,14 +96,22 @@ public AkkaScalaClientCodegen() { additionalProperties.put("onlyOneSuccess", onlyOneSuccess); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - supportingFiles.add(new SupportingFile("reference.mustache", resourcesFolder, "reference.conf")); - final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); - supportingFiles.add(new SupportingFile("apiRequest.mustache", invokerFolder, "ApiRequest.scala")); - supportingFiles.add(new SupportingFile("apiInvoker.mustache", invokerFolder, "ApiInvoker.scala")); - supportingFiles.add(new SupportingFile("requests.mustache", invokerFolder, "requests.scala")); - supportingFiles.add(new SupportingFile("apiSettings.mustache", invokerFolder, "ApiSettings.scala")); - final String apiFolder = (sourceFolder + File.separator + apiPackage).replace(".", File.separator); - supportingFiles.add(new SupportingFile("enumsSerializers.mustache", apiFolder, "EnumsSerializers.scala")); + supportingFiles.add(new SupportingFile("reference.mustache", resourcesFolder, + "reference.conf")); + final String invokerFolder = + (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); + supportingFiles.add(new SupportingFile("apiRequest.mustache", invokerFolder, + "ApiRequest.scala")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", invokerFolder, + "ApiInvoker.scala")); + supportingFiles + .add(new SupportingFile("requests.mustache", invokerFolder, "requests.scala")); + supportingFiles.add(new SupportingFile("apiSettings.mustache", invokerFolder, + "ApiSettings.scala")); + final String apiFolder = + (sourceFolder + File.separator + apiPackage).replace(".", File.separator); + supportingFiles.add(new SupportingFile("enumsSerializers.mustache", apiFolder, + "EnumsSerializers.scala")); importMapping.remove("Seq"); importMapping.remove("List"); @@ -154,9 +159,9 @@ public String getHelp() { @Override public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); - } + } return "`" + name + "`"; } @@ -165,7 +170,8 @@ public Map postProcessOperations(Map objs) { if (registerNonStandardStatusCodes) { try { @SuppressWarnings("unchecked") - Map> opsMap = (Map>) objs.get("operations"); + Map> opsMap = + (Map>) objs.get("operations"); HashSet unknownCodes = new HashSet(); for (CodegenOperation operation : opsMap.get("operation")) { for (CodegenResponse response : operation.responses) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index ba96eb2e6e9..121a9741efc 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -47,58 +47,68 @@ public AndroidClientCodegen() { apiPackage = "io.swagger.client.api"; modelPackage = "io.swagger.client.model"; - setReservedWordsLowerCase( - Arrays.asList( - // local variable names used in API methods (endpoints) - "localVarPostBody", "localVarPath", "localVarQueryParams", "localVarHeaderParams", - "localVarFormParams", "localVarContentTypes", "localVarContentType", - "localVarResponse", "localVarBuilder", "authNames", "basePath", "apiInvoker", - - // due to namespace collusion - "Object", - - // android 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") - ); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "byte[]", - "Object") - ); + setReservedWordsLowerCase(Arrays.asList( + // local variable names used in API methods (endpoints) + "localVarPostBody", + "localVarPath", + "localVarQueryParams", + "localVarHeaderParams", + "localVarFormParams", + "localVarContentTypes", + "localVarContentType", + "localVarResponse", + "localVarBuilder", + "authNames", + "basePath", + "apiInvoker", + + // due to namespace collusion + "Object", + + // android 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")); + + languageSpecificPrimitives = + new HashSet(Arrays.asList("String", "boolean", "Boolean", "Double", + "Integer", "Long", "Float", "byte[]", "Object")); 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, "groupId for use in the generated build.gradle and pom.xml")); - cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, "artifactId for use in the generated build.gradle and pom.xml")); - cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "artifact version for use in the generated build.gradle and pom.xml")); - cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); - cliOptions.add(CliOption.newBoolean(USE_ANDROID_MAVEN_GRADLE_PLUGIN, "A flag to toggle android-maven gradle plugin.") - .defaultValue(Boolean.TRUE.toString())); - - cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC)); + 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, + "groupId for use in the generated build.gradle and pom.xml")); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, + "artifactId for use in the generated build.gradle and pom.xml")); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, + "artifact version for use in the generated build.gradle and pom.xml")); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, + CodegenConstants.SOURCE_FOLDER_DESC)); + cliOptions.add(CliOption.newBoolean(USE_ANDROID_MAVEN_GRADLE_PLUGIN, + "A flag to toggle android-maven gradle plugin.").defaultValue( + Boolean.TRUE.toString())); + + cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZABLE_MODEL, + CodegenConstants.SERIALIZABLE_MODEL_DESC)); supportedLibraries.put("volley", "HTTP client: Volley 1.0.19 (default)"); - supportedLibraries.put("httpclient", "HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1. IMPORTANT: Android client using HttpClient is not actively maintained and will be depecreated in the next major release."); - CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); + supportedLibraries + .put("httpclient", + "HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1. IMPORTANT: Android client using HttpClient is not actively maintained and will be depecreated in the next major release."); + CliOption library = + new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); library.setEnum(supportedLibraries); cliOptions.add(library); } @@ -119,8 +129,8 @@ public String getHelp() { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -128,32 +138,34 @@ public String escapeReservedWord(String name) { @Override public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + return outputFolder + "/" + sourceFolder + "/" + + apiPackage().replace('.', File.separatorChar); } @Override public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + return outputFolder + "/" + sourceFolder + "/" + + modelPackage().replace('.', File.separatorChar); } @Override public String apiDocFileFolder() { - return (outputFolder + "/" + apiDocPath).replace( '/', File.separatorChar ); + return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); } @Override public String modelDocFileFolder() { - return ( outputFolder + "/" + modelDocPath ).replace( '/', File.separatorChar ); + return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); } @Override - public String toApiDocFilename( String name ) { - return toApiName( name ); + public String toApiDocFilename(String name) { + return toApiName(name); } @Override - public String toModelDocFilename( String name ) { - return toModelName( name ); + public String toModelDocFilename(String name) { + return toModelName(name); } @Override @@ -177,9 +189,9 @@ public String getSwaggerType(Property p) { String type = null; if (typeMapping.containsKey(swaggerType)) { type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type) || type.indexOf(".") >= 0 || - type.equals("Map") || type.equals("List") || - type.equals("File") || type.equals("Date")) { + if (languageSpecificPrimitives.contains(type) || type.indexOf(".") >= 0 + || type.equals("Map") || type.equals("List") || type.equals("File") + || type.equals("Date")) { return type; } } else { @@ -191,10 +203,12 @@ public String getSwaggerType(Property p) { @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'. + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare + // the methods parameters as 'final'. // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) { @@ -237,14 +251,18 @@ public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { String modelName = "Model" + name; - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + modelName); return modelName; } // model name starts with number if (name.matches("^\\d.*")) { - String modelName = "Model" + name; // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + String modelName = "Model" + name; // e.g. 200Response => Model200Response (after + // camelize) + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + modelName); return modelName; } @@ -333,7 +351,8 @@ public String toOperationId(String operationId) { // 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); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + newOperationId); return newOperationId; } @@ -345,30 +364,32 @@ public void processOpts() { super.processOpts(); if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { - this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); + this.setInvokerPackage((String) additionalProperties + .get(CodegenConstants.INVOKER_PACKAGE)); } else { - //not set, use default to be passed to template + // 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 + // 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 + // 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)); + this.setArtifactVersion((String) additionalProperties + .get(CodegenConstants.ARTIFACT_VERSION)); } else { - //not set, use to be passed to template + // not set, use to be passed to template additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); } @@ -388,15 +409,17 @@ public void processOpts() { } if (additionalProperties.containsKey(CodegenConstants.SERIALIZABLE_MODEL)) { - this.setSerializableModel(Boolean.valueOf(additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL).toString())); + this.setSerializableModel(Boolean.valueOf(additionalProperties.get( + CodegenConstants.SERIALIZABLE_MODEL).toString())); } - // need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string + // need to put back serializableModel (boolean) into additionalProperties as value in + // additionalProperties is string additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel); - //make api and model doc path available in mustache template - additionalProperties.put( "apiDocPath", apiDocPath ); - additionalProperties.put( "modelDocPath", modelDocPath ); + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); if (StringUtils.isEmpty(getLibrary())) { setLibrary("volley"); // set volley as the default library @@ -408,88 +431,115 @@ public void processOpts() { } else if ("httpclient".equals(getLibrary())) { addSupportingFilesForHttpClient(); } else { - throw new IllegalArgumentException("Invalid 'library' option specified: '" + getLibrary() + "'. Must be 'httpclient' or 'volley' (default)"); + throw new IllegalArgumentException("Invalid 'library' option specified: '" + + getLibrary() + "'. Must be 'httpclient' or 'volley' (default)"); } } private void addSupportingFilesForHttpClient() { // documentation files - modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); - apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); - supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); - supportingFiles.add(new SupportingFile("apiInvoker.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiInvoker.java")); + supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, + "AndroidManifest.xml")); + supportingFiles + .add(new SupportingFile("apiInvoker.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", + File.separator), "ApiInvoker.java")); supportingFiles.add(new SupportingFile("httpPatch.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "HttpPatch.java")); + (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), + "HttpPatch.java")); supportingFiles.add(new SupportingFile("jsonUtil.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "JsonUtil.java")); - supportingFiles.add(new SupportingFile("apiException.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiException.java")); + (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), + "JsonUtil.java")); + supportingFiles.add(new SupportingFile("apiException.mustache", (sourceFolder + + File.separator + invokerPackage).replace(".", File.separator), + "ApiException.java")); supportingFiles.add(new SupportingFile("Pair.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "Pair.java")); + (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), + "Pair.java")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); // gradle wrapper files - supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew" )); - supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat" )); - supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache", - gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties" )); - supportingFiles.add(new SupportingFile( "gradle-wrapper.jar", - gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar" )); + supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); + supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat")); + supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache", + gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties")); + supportingFiles.add(new SupportingFile("gradle-wrapper.jar", gradleWrapperPackage.replace( + ".", File.separator), "gradle-wrapper.jar")); } private void addSupportingFilesForVolley() { // documentation files - modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); - apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - // supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); + // supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", + // "settings.gradle")); supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); - supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); - supportingFiles.add(new SupportingFile("apiInvoker.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiInvoker.java")); + supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, + "AndroidManifest.xml")); + supportingFiles + .add(new SupportingFile("apiInvoker.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", + File.separator), "ApiInvoker.java")); supportingFiles.add(new SupportingFile("jsonUtil.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "JsonUtil.java")); - supportingFiles.add(new SupportingFile("apiException.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiException.java")); + (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), + "JsonUtil.java")); + supportingFiles.add(new SupportingFile("apiException.mustache", (sourceFolder + + File.separator + invokerPackage).replace(".", File.separator), + "ApiException.java")); supportingFiles.add(new SupportingFile("Pair.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "Pair.java")); - supportingFiles.add(new SupportingFile("request/getrequest.mustache", - (sourceFolder + File.separator + requestPackage).replace(".", File.separator), "GetRequest.java")); - supportingFiles.add(new SupportingFile("request/postrequest.mustache", - (sourceFolder + File.separator + requestPackage).replace(".", File.separator), "PostRequest.java")); - supportingFiles.add(new SupportingFile("request/putrequest.mustache", - (sourceFolder + File.separator + requestPackage).replace(".", File.separator), "PutRequest.java")); - supportingFiles.add(new SupportingFile("request/deleterequest.mustache", - (sourceFolder + File.separator + requestPackage).replace(".", File.separator), "DeleteRequest.java")); - supportingFiles.add(new SupportingFile("request/patchrequest.mustache", - (sourceFolder + File.separator + requestPackage).replace(".", File.separator), "PatchRequest.java")); - supportingFiles.add(new SupportingFile("auth/apikeyauth.mustache", - (sourceFolder + File.separator + authPackage).replace(".", File.separator), "ApiKeyAuth.java")); - supportingFiles.add(new SupportingFile("auth/httpbasicauth.mustache", - (sourceFolder + File.separator + authPackage).replace(".", File.separator), "HttpBasicAuth.java")); - supportingFiles.add(new SupportingFile("auth/authentication.mustache", - (sourceFolder + File.separator + authPackage).replace(".", File.separator), "Authentication.java")); + (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), + "Pair.java")); + supportingFiles + .add(new SupportingFile("request/getrequest.mustache", (sourceFolder + + File.separator + requestPackage).replace(".", File.separator), + "GetRequest.java")); + supportingFiles + .add(new SupportingFile("request/postrequest.mustache", (sourceFolder + + File.separator + requestPackage).replace(".", File.separator), + "PostRequest.java")); + supportingFiles + .add(new SupportingFile("request/putrequest.mustache", (sourceFolder + + File.separator + requestPackage).replace(".", File.separator), + "PutRequest.java")); + supportingFiles.add(new SupportingFile("request/deleterequest.mustache", (sourceFolder + + File.separator + requestPackage).replace(".", File.separator), + "DeleteRequest.java")); + supportingFiles.add(new SupportingFile("request/patchrequest.mustache", (sourceFolder + + File.separator + requestPackage).replace(".", File.separator), + "PatchRequest.java")); + supportingFiles.add(new SupportingFile("auth/apikeyauth.mustache", (sourceFolder + + File.separator + authPackage).replace(".", File.separator), "ApiKeyAuth.java")); + supportingFiles + .add(new SupportingFile("auth/httpbasicauth.mustache", (sourceFolder + + File.separator + authPackage).replace(".", File.separator), + "HttpBasicAuth.java")); + supportingFiles + .add(new SupportingFile("auth/authentication.mustache", (sourceFolder + + File.separator + authPackage).replace(".", File.separator), + "Authentication.java")); // gradle wrapper files - supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew" )); - supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat" )); - supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache", - gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties" )); - supportingFiles.add(new SupportingFile( "gradle-wrapper.jar", - gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar" )); + supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); + supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat")); + supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache", + gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties")); + supportingFiles.add(new SupportingFile("gradle-wrapper.jar", gradleWrapperPackage.replace( + ".", File.separator), "gradle-wrapper.jar")); } public Boolean getUseAndroidMavenGradlePlugin() { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNetCoreServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNetCoreServerCodegen.java index 576211f2c43..ece24aa44d4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNetCoreServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNetCoreServerCodegen.java @@ -29,40 +29,29 @@ public AspNetCoreServerCodegen() { apiTemplateFiles.put("controller.mustache", ".cs"); // contextually reserved words - setReservedWordsLowerCase( - Arrays.asList("var", "async", "await", "dynamic", "yield") - ); + setReservedWordsLowerCase(Arrays.asList("var", "async", "await", "dynamic", "yield")); cliOptions.clear(); // CLI options - addOption(CodegenConstants.PACKAGE_NAME, - "C# package name (convention: Title.Case).", + addOption(CodegenConstants.PACKAGE_NAME, "C# package name (convention: Title.Case).", this.packageName); - addOption(CodegenConstants.PACKAGE_VERSION, - "C# package version.", - this.packageVersion); + addOption(CodegenConstants.PACKAGE_VERSION, "C# package version.", this.packageVersion); - addOption(CodegenConstants.SOURCE_FOLDER, - CodegenConstants.SOURCE_FOLDER_DESC, - sourceFolder); + addOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC, sourceFolder); // CLI Switches addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, - CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC, - this.sortParamsByRequiredFlag); + CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC, this.sortParamsByRequiredFlag); - addSwitch(CodegenConstants.USE_DATETIME_OFFSET, - CodegenConstants.USE_DATETIME_OFFSET_DESC, + addSwitch(CodegenConstants.USE_DATETIME_OFFSET, CodegenConstants.USE_DATETIME_OFFSET_DESC, this.useDateTimeOffsetFlag); - addSwitch(CodegenConstants.USE_COLLECTION, - CodegenConstants.USE_COLLECTION_DESC, + addSwitch(CodegenConstants.USE_COLLECTION, CodegenConstants.USE_COLLECTION_DESC, this.useCollection); - addSwitch(CodegenConstants.RETURN_ICOLLECTION, - CodegenConstants.RETURN_ICOLLECTION_DESC, + addSwitch(CodegenConstants.RETURN_ICOLLECTION, CodegenConstants.RETURN_ICOLLECTION_DESC, this.returnICollection); } @@ -100,30 +89,38 @@ public void processOpts() { supportingFiles.add(new SupportingFile("Solution.mustache", "", this.packageName + ".sln")); supportingFiles.add(new SupportingFile("Dockerfile.mustache", packageFolder, "Dockerfile")); supportingFiles.add(new SupportingFile("gitignore", packageFolder, ".gitignore")); - supportingFiles.add(new SupportingFile("appsettings.json", packageFolder, "appsettings.json")); + supportingFiles.add(new SupportingFile("appsettings.json", packageFolder, + "appsettings.json")); - supportingFiles.add(new SupportingFile("project.json.mustache", packageFolder, "project.json")); + supportingFiles.add(new SupportingFile("project.json.mustache", packageFolder, + "project.json")); supportingFiles.add(new SupportingFile("Startup.mustache", packageFolder, "Startup.cs")); supportingFiles.add(new SupportingFile("Program.mustache", packageFolder, "Program.cs")); supportingFiles.add(new SupportingFile("web.config", packageFolder, "web.config")); - supportingFiles.add(new SupportingFile("Project.xproj.mustache", packageFolder, this.packageName + ".xproj")); + supportingFiles.add(new SupportingFile("Project.xproj.mustache", packageFolder, + this.packageName + ".xproj")); - supportingFiles.add(new SupportingFile("Properties" + File.separator + "launchSettings.json", packageFolder + File.separator + "Properties", "launchSettings.json")); + supportingFiles.add(new SupportingFile("Properties" + File.separator + + "launchSettings.json", packageFolder + File.separator + "Properties", + "launchSettings.json")); - supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "README.md", packageFolder + File.separator + "wwwroot", "README.md")); - supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "index.html", packageFolder + File.separator + "wwwroot", "index.html")); - supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "web.config", packageFolder + File.separator + "wwwroot", "web.config")); + supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "README.md", + packageFolder + File.separator + "wwwroot", "README.md")); + supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "index.html", + packageFolder + File.separator + "wwwroot", "index.html")); + supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "web.config", + packageFolder + File.separator + "wwwroot", "web.config")); } @Override public void setSourceFolder(final String sourceFolder) { - if(sourceFolder == null) { + if (sourceFolder == null) { LOGGER.warn("No sourceFolder specified, using default"); - this.sourceFolder = "src" + File.separator + this.packageName; - } else if(!sourceFolder.equals("src") && !sourceFolder.startsWith("src")) { + this.sourceFolder = "src" + File.separator + this.packageName; + } else if (!sourceFolder.equals("src") && !sourceFolder.startsWith("src")) { LOGGER.warn("ASP.NET Core requires source code exists under src. Adjusting."); - this.sourceFolder = "src" + File.separator + sourceFolder; + this.sourceFolder = "src" + File.separator + sourceFolder; } else { this.sourceFolder = sourceFolder; } @@ -131,12 +128,14 @@ public void setSourceFolder(final String sourceFolder) { @Override public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + "Controllers"; + return outputFolder + File.separator + sourceFolder + File.separator + packageName + + File.separator + "Controllers"; } @Override public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + "Models"; + return outputFolder + File.separator + sourceFolder + File.separator + packageName + + File.separator + "Models"; } @Override @@ -148,11 +147,14 @@ protected void processOperation(CodegenOperation operation) { String original = operation.path; operation.path = operation.path.replace("?", "/"); if (!original.equals(operation.path)) { - LOGGER.warn("Normalized " + original + " to " + operation.path + ". Please verify generated source."); + LOGGER.warn("Normalized " + original + " to " + operation.path + + ". Please verify generated source."); } } // Converts, for example, PUT to HttpPut for controller attributes - operation.httpMethod = "Http" + operation.httpMethod.substring(0, 1) + operation.httpMethod.substring(1).toLowerCase(); + operation.httpMethod = + "Http" + operation.httpMethod.substring(0, 1) + + operation.httpMethod.substring(1).toLowerCase(); } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java index ea8ae308081..8d0ebf0cdc8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java @@ -28,19 +28,20 @@ public AsyncScalaClientCodegen() { apiPackage = "io.swagger.client.api"; modelPackage = "io.swagger.client.model"; - setReservedWordsLowerCase( - Arrays.asList( - // local variable names used in API methods (endpoints) - "config", "path", "contentTypes", "contentType", "queryParams", "headerParams", - "formParams", "postBody", "resFuture", "client", "reader", + setReservedWordsLowerCase(Arrays.asList( + // local variable names used in API methods (endpoints) + "config", "path", "contentTypes", "contentType", "queryParams", "headerParams", + "formParams", "postBody", + "resFuture", + "client", + "reader", - // scala reserved words - "abstract", "case", "catch", "class", "def", "do", "else", "extends", - "false", "final", "finally", "for", "forSome", "if", "implicit", - "import", "lazy", "match", "new", "null", "object", "override", "package", - "private", "protected", "return", "sealed", "super", "this", "throw", - "trait", "try", "true", "type", "val", "var", "while", "with", "yield") - ); + // scala reserved words + "abstract", "case", "catch", "class", "def", "do", "else", "extends", "false", + "final", "finally", "for", "forSome", "if", "implicit", "import", "lazy", "match", + "new", "null", "object", "override", "package", "private", "protected", "return", + "sealed", "super", "this", "throw", "trait", "try", "true", "type", "val", "var", + "while", "with", "yield")); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.GROUP_ID, groupId); @@ -53,7 +54,8 @@ public AsyncScalaClientCodegen() { supportingFiles.add(new SupportingFile("sbt.mustache", "", "build.sbt")); supportingFiles.add(new SupportingFile("client.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), clientName + ".scala")); + (sourceFolder + File.separator + invokerPackage).replace(".", + java.io.File.separator), clientName + ".scala")); importMapping.remove("List"); importMapping.remove("Set"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/BashClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/BashClientCodegen.java index 49cd8352866..5c4738c177f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/BashClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/BashClientCodegen.java @@ -27,636 +27,579 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String apiVersion = "1.0.0"; - - protected String curlOptions; - protected boolean processMarkdown = false; - protected String scriptName = "client.sh"; - protected boolean generateBashCompletion = false; - protected boolean generateZshCompletion = false; - protected String hostEnvironmentVariable; - protected String basicAuthEnvironmentVariable; - protected String apiKeyAuthEnvironmentVariable; - - - public static final String CURL_OPTIONS = "curlOptions"; - public static final String PROCESS_MARKDOWN = "processMarkdown"; - public static final String SCRIPT_NAME = "scriptName"; - public static final String - GENERATE_BASH_COMPLETION = "generateBashCompletion"; - public static final String - GENERATE_ZSH_COMPLETION = "generateZshCompletion"; - public static final String - HOST_ENVIRONMENT_VARIABLE_NAME = "hostEnvironmentVariable"; - public static final String - BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME = "basicAuthEnvironmentVariable"; - public static final String - APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME = "apiKeyAuthEnvironmentVariable"; - - /** - * Configures the type of generator. - * - * @return the CodegenType for this generator - * @see io.swagger.codegen.CodegenType - */ - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - /** - * Configures a friendly name for the generator. This will be used by - * the generator to select the library with the -l flag. - * - * @return the friendly name for the generator - */ - public String getName() { - return "bash"; - } - - /** - * Returns human-friendly help for the generator. Provide the consumer with - * help tips, parameters here - * - * @return A string value for the help message - */ - public String getHelp() { - return "Generates a Bash client script based on cURL."; - } - - public BashClientCodegen() { - super(); + protected String apiVersion = "1.0.0"; + + protected String curlOptions; + protected boolean processMarkdown = false; + protected String scriptName = "client.sh"; + protected boolean generateBashCompletion = false; + protected boolean generateZshCompletion = false; + protected String hostEnvironmentVariable; + protected String basicAuthEnvironmentVariable; + protected String apiKeyAuthEnvironmentVariable; + + + public static final String CURL_OPTIONS = "curlOptions"; + public static final String PROCESS_MARKDOWN = "processMarkdown"; + public static final String SCRIPT_NAME = "scriptName"; + public static final String GENERATE_BASH_COMPLETION = "generateBashCompletion"; + public static final String GENERATE_ZSH_COMPLETION = "generateZshCompletion"; + public static final String HOST_ENVIRONMENT_VARIABLE_NAME = "hostEnvironmentVariable"; + public static final String BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME = + "basicAuthEnvironmentVariable"; + public static final String APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME = + "apiKeyAuthEnvironmentVariable"; /** - * Set the output folder here + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType */ - outputFolder = "generated-code/bash"; + public CodegenType getTag() { + return CodegenType.CLIENT; + } /** - * No model files. + * Configures a friendly name for the generator. This will be used by the generator to select + * the library with the -l flag. + * + * @return the friendly name for the generator */ - modelTemplateFiles.clear(); - + public String getName() { + return "bash"; + } /** - * No API files. + * Returns human-friendly help for the generator. Provide the consumer with help tips, + * parameters here + * + * @return A string value for the help message */ - apiTemplateFiles.clear(); + public String getHelp() { + return "Generates a Bash client script based on cURL."; + } + public BashClientCodegen() { + super(); - /** - * Templates location for client script and bash completion template. - */ - embeddedTemplateDir = templateDir = "bash"; + /** + * Set the output folder here + */ + outputFolder = "generated-code/bash"; + + /** + * No model files. + */ + modelTemplateFiles.clear(); + + + /** + * No API files. + */ + apiTemplateFiles.clear(); + + + /** + * Templates location for client script and bash completion template. + */ + embeddedTemplateDir = templateDir = "bash"; + + + /** + * Allow the user to force the script to always include certain cURL comamnds + */ + cliOptions.add(CliOption.newString(CURL_OPTIONS, "Default cURL options")); + cliOptions.add(CliOption.newBoolean(PROCESS_MARKDOWN, + "Convert all Markdown Markup into terminal formatting")); + cliOptions.add(CliOption.newString(SCRIPT_NAME, + "The name of the script that will be generated " + "(e.g. petstore-cli)")); + cliOptions.add(CliOption.newBoolean(GENERATE_BASH_COMPLETION, + "Whether to generate the Bash completion script")); + cliOptions.add(CliOption.newBoolean(GENERATE_ZSH_COMPLETION, + "Whether to generate the Zsh completion script")); + cliOptions.add(CliOption.newString(HOST_ENVIRONMENT_VARIABLE_NAME, + "Name of environment variable where host can be defined " + + "(e.g. PETSTORE_HOST='http://petstore.swagger.io:8080')")); + cliOptions.add(CliOption.newString(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME, + "Name of environment variable where username and password " + + "can be defined (e.g. PETSTORE_CREDS='username:password')")); + cliOptions.add(CliOption.newBoolean(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME, + "Name of environment variable where API key " + + "can be defined (e.g. PETSTORE_APIKEY='kjhasdGASDa5asdASD')")); + + /** + * Bash reserved words. + */ + reservedWords = + new HashSet(Arrays.asList("case", "do", "done", "elif", "else", "esac", + "fi", "for", "function", "if", "in", "select", "then", "time", "until", + "while")); + + typeMapping.clear(); + typeMapping.put("array", "array"); + typeMapping.put("map", "map"); + typeMapping.put("List", "array"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("string", "string"); + typeMapping.put("int", "integer"); + typeMapping.put("float", "float"); + typeMapping.put("number", "integer"); + typeMapping.put("DateTime", "string"); + typeMapping.put("long", "integer"); + typeMapping.put("short", "integer"); + typeMapping.put("char", "string"); + typeMapping.put("double", "float"); + typeMapping.put("object", "map"); + typeMapping.put("integer", "integer"); + typeMapping.put("ByteArray", "string"); + typeMapping.put("binary", "binary"); + + /** + * Additional Properties. These values can be passed to the templates and are available in + * models, apis, and supporting files. + */ + additionalProperties.put("apiVersion", apiVersion); + + /** + * Language Specific Primitives. These types will not trigger imports by the client + * generator + */ + languageSpecificPrimitives = new HashSet(); + } + + + @Override + public void processOpts() { + super.processOpts(); + String curlopts = ""; + + if (additionalProperties.containsKey(CURL_OPTIONS)) { + setCurlOptions(additionalProperties.get(CURL_OPTIONS).toString()); + additionalProperties.put("x-codegen-curl-options", curlopts); + } + + if (additionalProperties.containsKey(PROCESS_MARKDOWN)) { + setProcessMarkdown(Boolean.parseBoolean(additionalProperties.get(PROCESS_MARKDOWN) + .toString())); + } + + if (additionalProperties.containsKey(GENERATE_BASH_COMPLETION)) { + setGenerateBashCompletion(Boolean.parseBoolean(additionalProperties.get( + GENERATE_BASH_COMPLETION).toString())); + } + + if (additionalProperties.containsKey(GENERATE_ZSH_COMPLETION)) { + setGenerateZshCompletion(Boolean.parseBoolean(additionalProperties.get( + GENERATE_ZSH_COMPLETION).toString())); + } + + if (additionalProperties.containsKey(SCRIPT_NAME)) { + setScriptName(additionalProperties.get(SCRIPT_NAME).toString()); + } + additionalProperties.put("x-codegen-script-name", scriptName); + + if (additionalProperties.containsKey(HOST_ENVIRONMENT_VARIABLE_NAME)) { + setHostEnvironmentVariable(additionalProperties.get(HOST_ENVIRONMENT_VARIABLE_NAME) + .toString()); + additionalProperties.put("x-codegen-host-env", hostEnvironmentVariable); + } + + if (additionalProperties.containsKey(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME)) { + setBasicAuthEnvironmentVariable(additionalProperties.get( + BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME).toString()); + additionalProperties.put("x-codegen-basicauth-env", basicAuthEnvironmentVariable); + } + + if (additionalProperties.containsKey(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME)) { + setApiKeyAuthEnvironmentVariable(additionalProperties.get( + APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME).toString()); + additionalProperties.put("x-codegen-apikey-env", apiKeyAuthEnvironmentVariable); + } + + supportingFiles.add(new SupportingFile("client.mustache", "", scriptName)); + supportingFiles.add(new SupportingFile("bash-completion.mustache", "", scriptName + + ".bash-completion")); + supportingFiles.add(new SupportingFile("zsh-completion.mustache", "", "_" + scriptName)); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("Dockerfile.mustache", "", "Dockerfile")); + } + + public void setCurlOptions(String curlOptions) { + this.curlOptions = curlOptions; + } + + public void setProcessMarkdown(boolean processMarkdown) { + this.processMarkdown = processMarkdown; + } + + public void setScriptName(String scriptName) { + this.scriptName = scriptName; + } + + public void setGenerateBashCompletion(boolean generateBashCompletion) { + this.generateBashCompletion = generateBashCompletion; + } + + public void setGenerateZshCompletion(boolean generateZshCompletion) { + this.generateZshCompletion = generateZshCompletion; + } + + public void setHostEnvironmentVariable(String hostEnvironmentVariable) { + this.hostEnvironmentVariable = hostEnvironmentVariable; + } + + public void setBasicAuthEnvironmentVariable(String basicAuthEnvironmentVariable) { + this.basicAuthEnvironmentVariable = basicAuthEnvironmentVariable; + } + + public void setApiKeyAuthEnvironmentVariable(String apiKeyAuthEnvironmentVariable) { + this.apiKeyAuthEnvironmentVariable = apiKeyAuthEnvironmentVariable; + } /** - * Allow the user to force the script to always include certain cURL - * comamnds + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping those terms + * here. This logic is only called if a variable matches the reseved words. + * + * @return the escaped term */ - cliOptions.add(CliOption.newString(CURL_OPTIONS, "Default cURL options")); - cliOptions.add(CliOption.newBoolean(PROCESS_MARKDOWN, - "Convert all Markdown Markup into terminal formatting")); - cliOptions.add(CliOption.newString(SCRIPT_NAME, - "The name of the script that will be generated "+ - "(e.g. petstore-cli)")); - cliOptions.add(CliOption.newBoolean(GENERATE_BASH_COMPLETION, - "Whether to generate the Bash completion script")); - cliOptions.add(CliOption.newBoolean(GENERATE_ZSH_COMPLETION, - "Whether to generate the Zsh completion script")); - cliOptions.add(CliOption.newString(HOST_ENVIRONMENT_VARIABLE_NAME, - "Name of environment variable where host can be defined "+ - "(e.g. PETSTORE_HOST='http://petstore.swagger.io:8080')")); - cliOptions.add(CliOption.newString(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME, - "Name of environment variable where username and password " - + - "can be defined (e.g. PETSTORE_CREDS='username:password')")); - cliOptions.add(CliOption.newBoolean(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME, - "Name of environment variable where API key " - + - "can be defined (e.g. PETSTORE_APIKEY='kjhasdGASDa5asdASD')")); + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } /** - * Bash reserved words. + * Location to write model files. You can use the modelPackage() as defined when the class is + * instantiated. */ - reservedWords = new HashSet ( - Arrays.asList( - "case", - "do", - "done", - "elif", - "else", - "esac", - "fi", - "for", - "function", - "if", - "in", - "select", - "then", - "time", - "until", - "while") - ); - - typeMapping.clear(); - typeMapping.put("array", "array"); - typeMapping.put("map", "map"); - typeMapping.put("List", "array"); - typeMapping.put("boolean", "boolean"); - typeMapping.put("string", "string"); - typeMapping.put("int", "integer"); - typeMapping.put("float", "float"); - typeMapping.put("number", "integer"); - typeMapping.put("DateTime", "string"); - typeMapping.put("long", "integer"); - typeMapping.put("short", "integer"); - typeMapping.put("char", "string"); - typeMapping.put("double", "float"); - typeMapping.put("object", "map"); - typeMapping.put("integer", "integer"); - typeMapping.put("ByteArray", "string"); - typeMapping.put("binary", "binary"); + public String modelFileFolder() { + return outputFolder; + } /** - * Additional Properties. These values can be passed to the templates and - * are available in models, apis, and supporting files. + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated. */ - additionalProperties.put("apiVersion", apiVersion); + @Override + public String apiFileFolder() { + return outputFolder; + } + /** - * Language Specific Primitives. These types will not trigger imports by - * the client generator + * Optional - type declaration. This is a String which is used by the templates to instantiate + * your types. There is typically special handling for different property types + * + * @return a string value used as the `dataType` field for model templates, `returnType` for api + * templates */ - languageSpecificPrimitives = new HashSet(); - } - - - @Override - public void processOpts() { - super.processOpts(); - String curlopts = ""; - - if (additionalProperties.containsKey(CURL_OPTIONS)) { - setCurlOptions(additionalProperties.get(CURL_OPTIONS).toString()); - additionalProperties.put("x-codegen-curl-options", curlopts); - } - - if (additionalProperties.containsKey(PROCESS_MARKDOWN)) { - setProcessMarkdown( - Boolean.parseBoolean( - additionalProperties.get(PROCESS_MARKDOWN).toString())); - } - - if (additionalProperties.containsKey(GENERATE_BASH_COMPLETION)) { - setGenerateBashCompletion( - Boolean.parseBoolean( - additionalProperties.get(GENERATE_BASH_COMPLETION).toString())); - } - - if (additionalProperties.containsKey(GENERATE_ZSH_COMPLETION)) { - setGenerateZshCompletion( - Boolean.parseBoolean( - additionalProperties.get(GENERATE_ZSH_COMPLETION).toString())); - } - - if (additionalProperties.containsKey(SCRIPT_NAME)) { - setScriptName(additionalProperties.get(SCRIPT_NAME).toString()); - } - additionalProperties.put("x-codegen-script-name", scriptName); - - if (additionalProperties.containsKey(HOST_ENVIRONMENT_VARIABLE_NAME)) { - setHostEnvironmentVariable( - additionalProperties.get(HOST_ENVIRONMENT_VARIABLE_NAME).toString()); - additionalProperties.put("x-codegen-host-env", hostEnvironmentVariable); - } - - if (additionalProperties.containsKey(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME)) { - setBasicAuthEnvironmentVariable( - additionalProperties.get(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME).toString()); - additionalProperties.put("x-codegen-basicauth-env", basicAuthEnvironmentVariable); - } - - if (additionalProperties.containsKey(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME)) { - setApiKeyAuthEnvironmentVariable( - additionalProperties.get(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME).toString()); - additionalProperties.put("x-codegen-apikey-env", apiKeyAuthEnvironmentVariable); - } - - supportingFiles.add(new SupportingFile( - "client.mustache", "", scriptName)); - supportingFiles.add(new SupportingFile( - "bash-completion.mustache", "", scriptName+".bash-completion")); - supportingFiles.add(new SupportingFile( - "zsh-completion.mustache", "", "_"+scriptName)); - supportingFiles.add(new SupportingFile( - "README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile( - "Dockerfile.mustache", "", "Dockerfile")); - } - - public void setCurlOptions(String curlOptions) { - this.curlOptions = curlOptions; - } - - public void setProcessMarkdown(boolean processMarkdown) { - this.processMarkdown = processMarkdown; - } - - public void setScriptName(String scriptName) { - this.scriptName = scriptName; - } - - public void setGenerateBashCompletion(boolean generateBashCompletion) { - this.generateBashCompletion = generateBashCompletion; - } - - public void setGenerateZshCompletion(boolean generateZshCompletion) { - this.generateZshCompletion = generateZshCompletion; - } - - public void setHostEnvironmentVariable(String hostEnvironmentVariable) { - this.hostEnvironmentVariable = hostEnvironmentVariable; - } - - public void setBasicAuthEnvironmentVariable(String - basicAuthEnvironmentVariable) { - this.basicAuthEnvironmentVariable = basicAuthEnvironmentVariable; - } - - public void setApiKeyAuthEnvironmentVariable(String - apiKeyAuthEnvironmentVariable) { - this.apiKeyAuthEnvironmentVariable = apiKeyAuthEnvironmentVariable; - } - - - /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle - * escaping those terms here. This logic is only called if a variable - * matches the reseved words. - * - * @return the escaped term - */ - @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name - } - - /** - * Location to write model files. You can use the modelPackage() as defined - * when the class is instantiated. - */ - public String modelFileFolder() { - return outputFolder; - } - - /** - * Location to write api files. You can use the apiPackage() as defined when - * the class is instantiated. - */ - @Override - public String apiFileFolder() { - return outputFolder; - } - - - /** - * Optional - type declaration. This is a String which is used by the - * templates to instantiate your types. There is typically special handling - * for different property types - * - * @return a string value used as the `dataType` field for model templates, - * `returnType` for api templates - */ - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); } - return super.getTypeDeclaration(p); - } - - /** - * Optional - swagger type conversion. This is used to map swagger types in - * a `Property` into either language specific types via `typeMapping` or into - * complex models if there is not a mapping. - * - * @return a string value of the type or complex model for this property - * @see io.swagger.models.properties.Property - */ - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) - return type; + + /** + * Optional - swagger type conversion. This is used to map swagger types in a `Property` into + * either language specific types via `typeMapping` or into complex models if there is not a + * mapping. + * + * @return a string value of the type or complex model for this property + * @see io.swagger.models.properties.Property + */ + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) + return type; + } else + type = swaggerType; + return toModelName(type); } - else - type = swaggerType; - return toModelName(type); - } - /** - * Convert Swagger Parameter object to Codegen Parameter object - * - * @param param Swagger parameter object - * @param imports set of imports for library/package/module - * @return Codegen Parameter object - */ - @Override - public CodegenParameter fromParameter(Parameter param, Set imports) { + /** + * Convert Swagger Parameter object to Codegen Parameter object + * + * @param param Swagger parameter object + * @param imports set of imports for library/package/module + * @return Codegen Parameter object + */ + @Override + public CodegenParameter fromParameter(Parameter param, Set imports) { - CodegenParameter p = super.fromParameter(param, imports); + CodegenParameter p = super.fromParameter(param, imports); - if(param instanceof BodyParameter) { + if (param instanceof BodyParameter) { - Model model = ((BodyParameter)param).getSchema(); + Model model = ((BodyParameter) param).getSchema(); - } - else if(param instanceof SerializableParameter) { + } else if (param instanceof SerializableParameter) { - /** - * Currently it's not possible to specify in the codegen other collection - * formats than 'multi' - */ - SerializableParameter sparam = (SerializableParameter)param; + /** + * Currently it's not possible to specify in the codegen other collection formats than + * 'multi' + */ + SerializableParameter sparam = (SerializableParameter) param; - if( sparam.getCollectionFormat() != null - && !sparam.getCollectionFormat().isEmpty()) { + if (sparam.getCollectionFormat() != null && !sparam.getCollectionFormat().isEmpty()) { - String collectionFormat = sparam.getCollectionFormat(); + String collectionFormat = sparam.getCollectionFormat(); - if(sparam.isExclusiveMaximum()!=null && sparam.isExclusiveMaximum()) { - p.vendorExtensions.put("x-codegen-collection-max-items", - sparam.getMaxItems()); - } + if (sparam.isExclusiveMaximum() != null && sparam.isExclusiveMaximum()) { + p.vendorExtensions.put("x-codegen-collection-max-items", sparam.getMaxItems()); + } - if(sparam.isExclusiveMinimum()!=null && sparam.isExclusiveMinimum()) { - p.vendorExtensions.put("x-codegen-collection-min-items", - sparam.getMinItems()); - } + if (sparam.isExclusiveMinimum() != null && sparam.isExclusiveMinimum()) { + p.vendorExtensions.put("x-codegen-collection-min-items", sparam.getMinItems()); + } - if( (collectionFormat.equals("multi")) - && (param.getIn().equals("query")) ) { + if ((collectionFormat.equals("multi")) && (param.getIn().equals("query"))) { - /** - * 'multi' is only supported for query parameters - */ - p.vendorExtensions.put("x-codegen-collection-multi", true); + /** + * 'multi' is only supported for query parameters + */ + p.vendorExtensions.put("x-codegen-collection-multi", true); + + } else if (collectionFormat.equals("csv")) { + p.vendorExtensions.put("x-codegen-collection-csv", true); + } else if (collectionFormat.equals("ssv")) { + p.vendorExtensions.put("x-codegen-collection-ssv", true); + } else if (collectionFormat.equals("tsv")) { + p.vendorExtensions.put("x-codegen-collection-tsv", true); + } else if (collectionFormat.equals("pipes")) { + p.vendorExtensions.put("x-codegen-collection-pipes", true); + } else { + /** Unsupported collection format */ + } + + } - } - else if(collectionFormat.equals("csv")) { - p.vendorExtensions.put("x-codegen-collection-csv", true); - } - else if(collectionFormat.equals("ssv")) { - p.vendorExtensions.put("x-codegen-collection-ssv", true); - } - else if(collectionFormat.equals("tsv")) { - p.vendorExtensions.put("x-codegen-collection-tsv", true); - } - else if(collectionFormat.equals("pipes")) { - p.vendorExtensions.put("x-codegen-collection-pipes", true); - } - else { - /** Unsupported collection format */ } - } + return p; } - return p; - - } - - /** - * Override with any special text escaping logic - */ - @SuppressWarnings("static-method") - public String escapeText(String input) { - if (input == null) { - return input; - } - - /** - * Trim the input text always. - */ - String result = input.trim(); - - /** - * remove standalone '\' - * - * replace " with \" - * outter unescape to retain the original multi-byte characters - */ - result = escapeUnsafeCharacters( - StringEscapeUtils.unescapeJava( - StringEscapeUtils.escapeJava(result).replace("\\/", "/")) - .replace("\\", "\\\\") - .replace("\"", "\\\"")); - - if(this.processMarkdown) { + /** + * Override with any special text escaping logic + */ + @SuppressWarnings("static-method") + public String escapeText(String input) { + if (input == null) { + return input; + } /** - * Convert markdown strong **Bold text** and __Bold text__ - * to bash bold control sequences (tput bold) + * Trim the input text always. */ - result = result.replaceAll("(?m)(^|\\s)\\*{2}([\\w\\d ]+)\\*{2}($|\\s)", - "\\$\\(tput bold\\) $2 \\$\\(tput sgr0\\)"); + String result = input.trim(); - result = result.replaceAll("(?m)(^|\\s)_{2}([\\w\\d ]+)_{2}($|\\s)", - "\\$\\(tput bold\\) $2 \\$\\(tput sgr0\\)"); /** - * Convert markdown *Italics text* and _Italics text_ to bash dim - * control sequences (tput dim) + * remove standalone '\' + * + * replace " with \" outter unescape to retain the original multi-byte characters */ - result = result.replaceAll("(?m)(^|\\s)\\*{1}([\\w\\d ]+)\\*{1}($|\\s)", - "\\$\\(tput dim\\) $2 \\$\\(tput sgr0\\)"); + result = + escapeUnsafeCharacters(StringEscapeUtils + .unescapeJava(StringEscapeUtils.escapeJava(result).replace("\\/", "/")) + .replace("\\", "\\\\").replace("\"", "\\\"")); - result = result.replaceAll("(?m)(^|\\s)_{1}([\\w\\d ]+)_{1}($|\\s)", - "\\$\\(tput dim\\) $2 \\$\\(tput sgr0\\)"); + if (this.processMarkdown) { + /** + * Convert markdown strong **Bold text** and __Bold text__ to bash bold control + * sequences (tput bold) + */ + result = + result.replaceAll("(?m)(^|\\s)\\*{2}([\\w\\d ]+)\\*{2}($|\\s)", + "\\$\\(tput bold\\) $2 \\$\\(tput sgr0\\)"); - /** - * Convert all markdown section 1 level headers with bold - */ - result = result.replaceAll("(?m)^\\#\\s+(.+)$", - "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" - +"$1\\$\\(tput sgr0\\)"); + result = + result.replaceAll("(?m)(^|\\s)_{2}([\\w\\d ]+)_{2}($|\\s)", + "\\$\\(tput bold\\) $2 \\$\\(tput sgr0\\)"); + /** + * Convert markdown *Italics text* and _Italics text_ to bash dim control sequences + * (tput dim) + */ + result = + result.replaceAll("(?m)(^|\\s)\\*{1}([\\w\\d ]+)\\*{1}($|\\s)", + "\\$\\(tput dim\\) $2 \\$\\(tput sgr0\\)"); - /** - * Convert all markdown section 2 level headers with bold - */ - result = result.replaceAll("(?m)^\\#\\#\\s+(.+)$", - "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" - +"$1\\$\\(tput sgr0\\)"); + result = + result.replaceAll("(?m)(^|\\s)_{1}([\\w\\d ]+)_{1}($|\\s)", + "\\$\\(tput dim\\) $2 \\$\\(tput sgr0\\)"); - /** - * Convert all markdown section 3 level headers with bold - */ - result = result.replaceAll("(?m)^\\#\\#\\#\\s+(.+)$", - "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" - +"$1\\$\\(tput sgr0\\)"); - /** - * Convert all markdown code blocks into --- delimited sections - */ - result = result.replaceAll("(?m)\\s*```.*$", - "\n---"); + /** + * Convert all markdown section 1 level headers with bold + */ + result = + result.replaceAll("(?m)^\\#\\s+(.+)$", + "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" + "$1\\$\\(tput sgr0\\)"); - result = result.replaceAll("(?m)\\s*\\'\\'\\'.*$", - "\n---"); + /** + * Convert all markdown section 2 level headers with bold + */ + result = + result.replaceAll("(?m)^\\#\\#\\s+(.+)$", + "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" + "$1\\$\\(tput sgr0\\)"); - /** - * Remove any trailing new line at the end of the string - */ - result = result.replaceAll("\\s+$", ""); - } - - return result; - } - - @Override - public String escapeQuotationMark(String input) { - return input; - } - - /** - * Override with any special text escaping logic to handle unsafe - * characters so as to avoid code injection. - * - * @param input String to be cleaned up - * @return string with unsafe characters removed or escaped - */ - public String escapeUnsafeCharacters(String input) { + /** + * Convert all markdown section 3 level headers with bold + */ + result = + result.replaceAll("(?m)^\\#\\#\\#\\s+(.+)$", + "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" + "$1\\$\\(tput sgr0\\)"); + + /** + * Convert all markdown code blocks into --- delimited sections + */ + result = result.replaceAll("(?m)\\s*```.*$", "\n---"); + + result = result.replaceAll("(?m)\\s*\\'\\'\\'.*$", "\n---"); + + /** + * Remove any trailing new line at the end of the string + */ + result = result.replaceAll("\\s+$", ""); + } + + return result; + } + + @Override + public String escapeQuotationMark(String input) { + return input; + } /** - * Replace backticks with normal single quotes. + * Override with any special text escaping logic to handle unsafe characters so as to avoid code + * injection. + * + * @param input String to be cleaned up + * @return string with unsafe characters removed or escaped */ - String result = input.replaceAll("`", "'"); + public String escapeUnsafeCharacters(String input) { - return result; - } + /** + * Replace backticks with normal single quotes. + */ + String result = input.replaceAll("`", "'"); + return result; + } - @Override - public CodegenOperation fromOperation(String path, String httpMethod, - Operation operation, - Map definitions, - Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, - definitions, swagger); + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, + Map definitions, Swagger swagger) { - /** - * Check if the operation has a Bash codegen specific description - * for help - */ - if(op.vendorExtensions.containsKey("x-bash-codegen-description")) { - String bash_description - = (String)op.vendorExtensions.get("x-bash-codegen-description"); + CodegenOperation op = + super.fromOperation(path, httpMethod, operation, definitions, swagger); - op.vendorExtensions.put("x-bash-codegen-description", - escapeText(bash_description)); - } + /** + * Check if the operation has a Bash codegen specific description for help + */ + if (op.vendorExtensions.containsKey("x-bash-codegen-description")) { + String bash_description = + (String) op.vendorExtensions.get("x-bash-codegen-description"); + + op.vendorExtensions.put("x-bash-codegen-description", escapeText(bash_description)); + } - /** - * Check if operation has an 'x-code-samples' vendor extension with - * Shell example - */ - if(op.vendorExtensions.containsKey("x-code-samples")) { + /** + * Check if operation has an 'x-code-samples' vendor extension with Shell example + */ + if (op.vendorExtensions.containsKey("x-code-samples")) { - List codesamples = (List)op.vendorExtensions.get("x-code-samples"); + List codesamples = (List) op.vendorExtensions.get("x-code-samples"); - for (Object codesample : codesamples) { - ObjectNode codesample_object = (ObjectNode)codesample; + for (Object codesample : codesamples) { + ObjectNode codesample_object = (ObjectNode) codesample; - if((codesample_object.get("lang").asText()).equals("Shell")) { + if ((codesample_object.get("lang").asText()).equals("Shell")) { - op.vendorExtensions.put("x-bash-codegen-sample", - escapeUnsafeCharacters( - codesample_object.get("source").asText())); + op.vendorExtensions.put("x-bash-codegen-sample", + escapeUnsafeCharacters(codesample_object.get("source").asText())); - } + } + } } - } - - for (CodegenParameter p : op.bodyParams) { - if(p.dataType != null && definitions.get(p.dataType) != null) { - /** - * If the operation produces Json and has nonempty example - * try to reformat it. - */ - if(operation.getConsumes() != null - && operation.getConsumes().contains("application/json") - && definitions.get(p.dataType).getExample() != null) { - - ObjectMapper mapper = new ObjectMapper(); - try { - p.vendorExtensions.put( - "x-codegen-body-example", - mapper.writerWithDefaultPrettyPrinter().writeValueAsString( - definitions.get(p.dataType).getExample())); - } - catch(JsonProcessingException e) { - e.printStackTrace(); - } - } - else { - /** - * Otherwise present whatever is provided as example - */ - p.vendorExtensions.put( - "x-codegen-body-example", - definitions.get(p.dataType).getExample()); - } + + for (CodegenParameter p : op.bodyParams) { + if (p.dataType != null && definitions.get(p.dataType) != null) { + /** + * If the operation produces Json and has nonempty example try to reformat it. + */ + if (operation.getConsumes() != null + && operation.getConsumes().contains("application/json") + && definitions.get(p.dataType).getExample() != null) { + + ObjectMapper mapper = new ObjectMapper(); + try { + p.vendorExtensions.put( + "x-codegen-body-example", + mapper.writerWithDefaultPrettyPrinter().writeValueAsString( + definitions.get(p.dataType).getExample())); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + } else { + /** + * Otherwise present whatever is provided as example + */ + p.vendorExtensions.put("x-codegen-body-example", definitions.get(p.dataType) + .getExample()); + } + } } - } - return op; + return op; - } + } - /** - * Preprocess original properties from the Swagger definition where necessary. - * - * @param swagger [description] - */ - @Override - public void preprocessSwagger(Swagger swagger) { - super.preprocessSwagger(swagger); + /** + * Preprocess original properties from the Swagger definition where necessary. + * + * @param swagger [description] + */ + @Override + public void preprocessSwagger(Swagger swagger) { + super.preprocessSwagger(swagger); - if ("/".equals(swagger.getBasePath())) { - swagger.setBasePath(""); - } + if ("/".equals(swagger.getBasePath())) { + swagger.setBasePath(""); + } - if(swagger.getInfo() != null - && swagger.getInfo().getVendorExtensions()!=null) { - String bash_codegen_app_description - = (String)swagger.getInfo().getVendorExtensions() - .get("x-bash-codegen-description"); + if (swagger.getInfo() != null && swagger.getInfo().getVendorExtensions() != null) { + String bash_codegen_app_description = + (String) swagger.getInfo().getVendorExtensions() + .get("x-bash-codegen-description"); - if(bash_codegen_app_description != null) { + if (bash_codegen_app_description != null) { - bash_codegen_app_description - = escapeText(bash_codegen_app_description); + bash_codegen_app_description = escapeText(bash_codegen_app_description); - additionalProperties.put("x-bash-codegen-app-description", - bash_codegen_app_description); + additionalProperties.put("x-bash-codegen-app-description", + bash_codegen_app_description); + } } - } - } + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index 1d85e7b8ae3..592d868a002 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -62,58 +62,45 @@ public CSharpClientCodegen() { cliOptions.clear(); // CLI options - addOption(CodegenConstants.PACKAGE_NAME, - "C# package name (convention: Title.Case).", + addOption(CodegenConstants.PACKAGE_NAME, "C# package name (convention: Title.Case).", this.packageName); - addOption(CodegenConstants.PACKAGE_VERSION, - "C# package version.", - this.packageVersion); + addOption(CodegenConstants.PACKAGE_VERSION, "C# package version.", this.packageVersion); - addOption(CodegenConstants.SOURCE_FOLDER, - CodegenConstants.SOURCE_FOLDER_DESC, - sourceFolder); + addOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC, sourceFolder); addOption(CodegenConstants.OPTIONAL_PROJECT_GUID, - CodegenConstants.OPTIONAL_PROJECT_GUID_DESC, - null); + CodegenConstants.OPTIONAL_PROJECT_GUID_DESC, null); - addOption(CodegenConstants.INTERFACE_PREFIX, - CodegenConstants.INTERFACE_PREFIX_DESC, + addOption(CodegenConstants.INTERFACE_PREFIX, CodegenConstants.INTERFACE_PREFIX_DESC, interfacePrefix); - CliOption framework = new CliOption( - CodegenConstants.DOTNET_FRAMEWORK, - CodegenConstants.DOTNET_FRAMEWORK_DESC - ); - frameworks = new ImmutableMap.Builder() - .put(NET35, ".NET Framework 3.5 compatible") - .put(NET45, ".NET Framework 4.5+ compatible") - .put(UWP, "Universal Windows Platform - beta support") - .build(); + CliOption framework = + new CliOption(CodegenConstants.DOTNET_FRAMEWORK, + CodegenConstants.DOTNET_FRAMEWORK_DESC); + frameworks = + new ImmutableMap.Builder() + .put(NET35, ".NET Framework 3.5 compatible") + .put(NET45, ".NET Framework 4.5+ compatible") + .put(UWP, "Universal Windows Platform - beta support").build(); framework.defaultValue(this.targetFramework); framework.setEnum(frameworks); cliOptions.add(framework); // CLI Switches addSwitch(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC, - this.hideGenerationTimestamp); + CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC, this.hideGenerationTimestamp); addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, - CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC, - this.sortParamsByRequiredFlag); + CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC, this.sortParamsByRequiredFlag); - addSwitch(CodegenConstants.USE_DATETIME_OFFSET, - CodegenConstants.USE_DATETIME_OFFSET_DESC, + addSwitch(CodegenConstants.USE_DATETIME_OFFSET, CodegenConstants.USE_DATETIME_OFFSET_DESC, this.useDateTimeOffsetFlag); - addSwitch(CodegenConstants.USE_COLLECTION, - CodegenConstants.USE_COLLECTION_DESC, + addSwitch(CodegenConstants.USE_COLLECTION, CodegenConstants.USE_COLLECTION_DESC, this.useCollection); - addSwitch(CodegenConstants.RETURN_ICOLLECTION, - CodegenConstants.RETURN_ICOLLECTION_DESC, + addSwitch(CodegenConstants.RETURN_ICOLLECTION, CodegenConstants.RETURN_ICOLLECTION_DESC, this.returnICollection); addSwitch(CodegenConstants.OPTIONAL_METHOD_ARGUMENT, @@ -121,32 +108,28 @@ public CSharpClientCodegen() { this.optionalMethodArgumentFlag); addSwitch(CodegenConstants.OPTIONAL_ASSEMBLY_INFO, - CodegenConstants.OPTIONAL_ASSEMBLY_INFO_DESC, - this.optionalAssemblyInfoFlag); + CodegenConstants.OPTIONAL_ASSEMBLY_INFO_DESC, this.optionalAssemblyInfoFlag); addSwitch(CodegenConstants.OPTIONAL_PROJECT_FILE, - CodegenConstants.OPTIONAL_PROJECT_FILE_DESC, - this.optionalProjectFileFlag); + CodegenConstants.OPTIONAL_PROJECT_FILE_DESC, this.optionalProjectFileFlag); addSwitch(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, - CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES_DESC, - this.optionalEmitDefaultValue); + CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES_DESC, this.optionalEmitDefaultValue); addSwitch(CodegenConstants.GENERATE_PROPERTY_CHANGED, - CodegenConstants.PACKAGE_DESCRIPTION_DESC, - this.generatePropertyChanged); + CodegenConstants.PACKAGE_DESCRIPTION_DESC, this.generatePropertyChanged); - // NOTE: This will reduce visibility of all public members in templates. Users can use InternalsVisibleTo + // NOTE: This will reduce visibility of all public members in templates. Users can use + // InternalsVisibleTo // https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx - // to expose to shared code if the generated code is not embedded into another project. Otherwise, users of codegen + // to expose to shared code if the generated code is not embedded into another project. + // Otherwise, users of codegen // should rely on default public visibility. - addSwitch(CodegenConstants.NON_PUBLIC_API, - CodegenConstants.NON_PUBLIC_API_DESC, + addSwitch(CodegenConstants.NON_PUBLIC_API, CodegenConstants.NON_PUBLIC_API_DESC, this.nonPublicApi); addSwitch(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, - CodegenConstants.ALLOW_UNICODE_IDENTIFIERS_DESC, - this.allowUnicodeIdentifiers); + CodegenConstants.ALLOW_UNICODE_IDENTIFIERS_DESC, this.allowUnicodeIdentifiers); regexModifiers = new HashMap(); regexModifiers.put('i', "IgnoreCase"); @@ -161,23 +144,28 @@ public void processOpts() { // default HIDE_GENERATION_TIMESTAMP to true if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.TRUE.toString()); + } else { + additionalProperties.put( + CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get( + CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } - if(isEmpty(apiPackage)) { + if (isEmpty(apiPackage)) { apiPackage = "Api"; } - if(isEmpty(modelPackage)) { + if (isEmpty(modelPackage)) { modelPackage = "Model"; } clientPackage = "Client"; Boolean excludeTests = false; - if(additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) { - excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString()); + if (additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) { + excludeTests = + Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS) + .toString()); } additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); @@ -199,10 +187,10 @@ public void processOpts() { if (NET35.equals(this.targetFramework)) { setTargetFrameworkNuget("net35"); setSupportsAsync(Boolean.FALSE); - if(additionalProperties.containsKey("supportsAsync")){ + if (additionalProperties.containsKey("supportsAsync")) { additionalProperties.remove("supportsAsync"); } - } else if (UWP.equals(this.targetFramework)){ + } else if (UWP.equals(this.targetFramework)) { setTargetFrameworkNuget("uwp"); setSupportsAsync(Boolean.TRUE); setSupportsUWP(Boolean.TRUE); @@ -215,14 +203,16 @@ public void processOpts() { additionalProperties.put("supportsAsync", this.supportsAsync); } - if(additionalProperties.containsKey(CodegenConstants.GENERATE_PROPERTY_CHANGED)) { - if(NET35.equals(targetFramework)) { - LOGGER.warn(CodegenConstants.GENERATE_PROPERTY_CHANGED + " is only supported by generated code for .NET 4+."); + if (additionalProperties.containsKey(CodegenConstants.GENERATE_PROPERTY_CHANGED)) { + if (NET35.equals(targetFramework)) { + LOGGER.warn(CodegenConstants.GENERATE_PROPERTY_CHANGED + + " is only supported by generated code for .NET 4+."); } else { - setGeneratePropertyChanged(Boolean.valueOf(additionalProperties.get(CodegenConstants.GENERATE_PROPERTY_CHANGED).toString())); + setGeneratePropertyChanged(Boolean.valueOf(additionalProperties.get( + CodegenConstants.GENERATE_PROPERTY_CHANGED).toString())); } - if(Boolean.FALSE.equals(this.generatePropertyChanged)) { + if (Boolean.FALSE.equals(this.generatePropertyChanged)) { additionalProperties.remove(CodegenConstants.GENERATE_PROPERTY_CHANGED); } } @@ -230,28 +220,30 @@ public void processOpts() { additionalProperties.put("targetFrameworkNuget", this.targetFrameworkNuget); if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_FILE)) { - setOptionalProjectFileFlag(Boolean.valueOf( - additionalProperties.get(CodegenConstants.OPTIONAL_PROJECT_FILE).toString())); + setOptionalProjectFileFlag(Boolean.valueOf(additionalProperties.get( + CodegenConstants.OPTIONAL_PROJECT_FILE).toString())); } if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_GUID)) { - setPackageGuid((String) additionalProperties.get(CodegenConstants.OPTIONAL_PROJECT_GUID)); + setPackageGuid((String) additionalProperties + .get(CodegenConstants.OPTIONAL_PROJECT_GUID)); } additionalProperties.put("packageGuid", packageGuid); if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_METHOD_ARGUMENT)) { - setOptionalMethodArgumentFlag(Boolean.valueOf(additionalProperties - .get(CodegenConstants.OPTIONAL_METHOD_ARGUMENT).toString())); + setOptionalMethodArgumentFlag(Boolean.valueOf(additionalProperties.get( + CodegenConstants.OPTIONAL_METHOD_ARGUMENT).toString())); } additionalProperties.put("optionalMethodArgument", optionalMethodArgumentFlag); if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_ASSEMBLY_INFO)) { - setOptionalAssemblyInfoFlag(Boolean.valueOf(additionalProperties - .get(CodegenConstants.OPTIONAL_ASSEMBLY_INFO).toString())); + setOptionalAssemblyInfoFlag(Boolean.valueOf(additionalProperties.get( + CodegenConstants.OPTIONAL_ASSEMBLY_INFO).toString())); } if (additionalProperties.containsKey(CodegenConstants.NON_PUBLIC_API)) { - setNonPublicApi(Boolean.valueOf(additionalProperties.get(CodegenConstants.NON_PUBLIC_API).toString())); + setNonPublicApi(Boolean.valueOf(additionalProperties.get( + CodegenConstants.NON_PUBLIC_API).toString())); } final String testPackageName = testPackageName(); @@ -261,49 +253,55 @@ public void processOpts() { additionalProperties.put("testPackageName", testPackageName); - //Compute the relative path to the bin directory where the external assemblies live - //This is necessary to properly generate the project file - int packageDepth = packageFolder.length() - packageFolder.replace(java.io.File.separator, "").length(); + // Compute the relative path to the bin directory where the external assemblies live + // This is necessary to properly generate the project file + int packageDepth = + packageFolder.length() - packageFolder.replace(java.io.File.separator, "").length(); String binRelativePath = "..\\"; for (int i = 0; i < packageDepth; i = i + 1) binRelativePath += "..\\"; binRelativePath += "vendor"; additionalProperties.put("binRelativePath", binRelativePath); - supportingFiles.add(new SupportingFile("IApiAccessor.mustache", - clientPackageDir, "IApiAccessor.cs")); - supportingFiles.add(new SupportingFile("Configuration.mustache", - clientPackageDir, "Configuration.cs")); - supportingFiles.add(new SupportingFile("ApiClient.mustache", - clientPackageDir, "ApiClient.cs")); - supportingFiles.add(new SupportingFile("ApiException.mustache", - clientPackageDir, "ApiException.cs")); - supportingFiles.add(new SupportingFile("ApiResponse.mustache", - clientPackageDir, "ApiResponse.cs")); - supportingFiles.add(new SupportingFile("ExceptionFactory.mustache", - clientPackageDir, "ExceptionFactory.cs")); + supportingFiles.add(new SupportingFile("IApiAccessor.mustache", clientPackageDir, + "IApiAccessor.cs")); + supportingFiles.add(new SupportingFile("Configuration.mustache", clientPackageDir, + "Configuration.cs")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", clientPackageDir, + "ApiClient.cs")); + supportingFiles.add(new SupportingFile("ApiException.mustache", clientPackageDir, + "ApiException.cs")); + supportingFiles.add(new SupportingFile("ApiResponse.mustache", clientPackageDir, + "ApiResponse.cs")); + supportingFiles.add(new SupportingFile("ExceptionFactory.mustache", clientPackageDir, + "ExceptionFactory.cs")); supportingFiles.add(new SupportingFile("compile.mustache", "", "build.bat")); supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "build.sh")); // copy package.config to nuget's standard location for project-level installs - supportingFiles.add(new SupportingFile("packages.config.mustache", packageFolder + File.separator, "packages.config")); + supportingFiles.add(new SupportingFile("packages.config.mustache", packageFolder + + File.separator, "packages.config")); // .travis.yml for travis-ci.org CI supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml")); - // Only write out test related files if excludeTests is unset or explicitly set to false (see start of this method) - if(Boolean.FALSE.equals(excludeTests)) { + // Only write out test related files if excludeTests is unset or explicitly set to false + // (see start of this method) + if (Boolean.FALSE.equals(excludeTests)) { // shell script to run the nunit test - supportingFiles.add(new SupportingFile("mono_nunit_test.mustache", "", "mono_nunit_test.sh")); + supportingFiles.add(new SupportingFile("mono_nunit_test.mustache", "", + "mono_nunit_test.sh")); modelTestTemplateFiles.put("model_test.mustache", ".cs"); apiTestTemplateFiles.put("api_test.mustache", ".cs"); - supportingFiles.add(new SupportingFile("packages_test.config.mustache", testPackageFolder + File.separator, "packages.config")); + supportingFiles.add(new SupportingFile("packages_test.config.mustache", + testPackageFolder + File.separator, "packages.config")); } - if(Boolean.TRUE.equals(generatePropertyChanged)) { - supportingFiles.add(new SupportingFile("FodyWeavers.xml", packageFolder, "FodyWeavers.xml")); + if (Boolean.TRUE.equals(generatePropertyChanged)) { + supportingFiles.add(new SupportingFile("FodyWeavers.xml", packageFolder, + "FodyWeavers.xml")); } supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); @@ -311,19 +309,24 @@ public void processOpts() { supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); // apache v2 license // UPDATE (20160612) no longer needed as the Apache v2 LICENSE is added globally - //supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE")); + // supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE")); if (optionalAssemblyInfoFlag) { - supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", packageFolder + File.separator + "Properties", "AssemblyInfo.cs")); + supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", packageFolder + + File.separator + "Properties", "AssemblyInfo.cs")); } if (optionalProjectFileFlag) { supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln")); - supportingFiles.add(new SupportingFile("Project.mustache", packageFolder, packageName + ".csproj")); - supportingFiles.add(new SupportingFile("nuspec.mustache", packageFolder, packageName + ".nuspec")); - - if(Boolean.FALSE.equals(excludeTests)) { - // NOTE: This exists here rather than previous excludeTests block because the test project is considered an optional project file. - supportingFiles.add(new SupportingFile("TestProject.mustache", testPackageFolder, testPackageName + ".csproj")); + supportingFiles.add(new SupportingFile("Project.mustache", packageFolder, packageName + + ".csproj")); + supportingFiles.add(new SupportingFile("nuspec.mustache", packageFolder, packageName + + ".nuspec")); + + if (Boolean.FALSE.equals(excludeTests)) { + // NOTE: This exists here rather than previous excludeTests block because the test + // project is considered an optional project file. + supportingFiles.add(new SupportingFile("TestProject.mustache", testPackageFolder, + testPackageName + ".csproj")); } } @@ -341,13 +344,15 @@ public Map postProcessOperations(Map objs) { for (CodegenOperation operation : ops) { if (operation.returnType != null) { operation.returnContainer = operation.returnType; - if (this.returnICollection && ( - operation.returnType.startsWith("List") || - operation.returnType.startsWith("Collection"))) { + if (this.returnICollection + && (operation.returnType.startsWith("List") || operation.returnType + .startsWith("Collection"))) { // NOTE: ICollection works for both List and Collection int genericStart = operation.returnType.indexOf("<"); if (genericStart > 0) { - operation.returnType = "ICollection" + operation.returnType.substring(genericStart); + operation.returnType = + "ICollection" + + operation.returnType.substring(genericStart); } } } @@ -380,9 +385,11 @@ public void setOptionalAssemblyInfoFlag(boolean flag) { @Override public CodegenModel fromModel(String name, Model model, Map allDefinitions) { CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); - if (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) { + if (allDefinitions != null && codegenModel != null && codegenModel.parent != null + && codegenModel.hasEnums) { final Model parentModel = allDefinitions.get(toModelName(codegenModel.parent)); - final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); + final CodegenModel parentCodegenModel = + super.fromModel(codegenModel.parent, parentModel); codegenModel = this.reconcileInlineEnums(codegenModel, parentCodegenModel); } @@ -399,7 +406,7 @@ public void setPackageGuid(String packageGuid) { @Override public Map postProcessModels(Map objMap) { - return super.postProcessModels(objMap); + return super.postProcessModels(objMap); } @Override @@ -423,13 +430,13 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert * See https://github.com/swagger-api/swagger-codegen/pull/2794 for Python's initial implementation from which this is copied. */ public void postProcessPattern(String pattern, Map vendorExtensions) { - if(pattern != null) { + if (pattern != null) { int i = pattern.lastIndexOf('/'); - //Must follow Perl /pattern/modifiers convention - if(pattern.charAt(0) != '/' || i < 2) { + // Must follow Perl /pattern/modifiers convention + if (pattern.charAt(0) != '/' || i < 2) { throw new IllegalArgumentException("Pattern must follow the Perl " - + "/pattern/modifiers convention. "+pattern+" is not valid."); + + "/pattern/modifiers convention. " + pattern + " is not valid."); } String regex = pattern.substring(1, i).replace("'", "\'"); @@ -438,8 +445,8 @@ public void postProcessPattern(String pattern, Map vendorExtensi // perl requires an explicit modifier to be culture specific and .NET is the reverse. modifiers.add("CultureInvariant"); - for(char c : pattern.substring(i).toCharArray()) { - if(regexModifiers.containsKey(c)) { + for (char c : pattern.substring(i).toCharArray()) { + if (regexModifiers.containsKey(c)) { String modifier = regexModifiers.get(c); modifiers.add(modifier); } else if (c == 'l') { @@ -453,7 +460,7 @@ public void postProcessPattern(String pattern, Map vendorExtensi } public void setTargetFramework(String dotnetFramework) { - if(!frameworks.containsKey(dotnetFramework)){ + if (!frameworks.containsKey(dotnetFramework)) { LOGGER.warn("Invalid .NET framework version, defaulting to " + this.targetFramework); } else { this.targetFramework = dotnetFramework; @@ -461,7 +468,8 @@ public void setTargetFramework(String dotnetFramework) { LOGGER.info("Generating code for .NET Framework " + this.targetFramework); } - private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { + private 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 @@ -485,7 +493,8 @@ private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenMode Iterator iterator = codegenProperties.iterator(); while (iterator.hasNext()) { CodegenProperty codegenProperty = iterator.next(); - if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) { + 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(); @@ -495,10 +504,11 @@ private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenMode } } - if(removedChildEnum) { - // If we removed an entry from this model's vars, we need to ensure hasMore is updated + 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) { + for (CodegenProperty codegenProperty : codegenProperties) { count += 1; codegenProperty.hasMore = (count < numVars) ? true : null; } @@ -511,8 +521,8 @@ private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenMode @Override public String toEnumValue(String value, String datatype) { - if ("int?".equalsIgnoreCase(datatype) || "long?".equalsIgnoreCase(datatype) || - "double?".equalsIgnoreCase(datatype) || "float?".equalsIgnoreCase(datatype)) { + if ("int?".equalsIgnoreCase(datatype) || "long?".equalsIgnoreCase(datatype) + || "double?".equalsIgnoreCase(datatype) || "float?".equalsIgnoreCase(datatype)) { return value; } else { return "\"" + escapeText(value) + "\""; @@ -531,8 +541,8 @@ public String toEnumVarName(String value, String datatype) { } // number - if ("int?".equals(datatype) || "long?".equals(datatype) || - "double?".equals(datatype) || "float?".equals(datatype)) { + if ("int?".equals(datatype) || "long?".equals(datatype) || "double?".equals(datatype) + || "float?".equals(datatype)) { String varName = "NUMBER_" + value; varName = varName.replaceAll("-", "MINUS_"); varName = varName.replaceAll("\\+", "PLUS_"); @@ -542,7 +552,7 @@ public String toEnumVarName(String value, String datatype) { // string String var = value.replaceAll("_", " "); - //var = WordUtils.capitalizeFully(var); + // var = WordUtils.capitalizeFully(var); var = camelize(var); var = var.replaceAll("\\W+", ""); @@ -566,15 +576,15 @@ public void setTargetFrameworkNuget(String targetFrameworkNuget) { this.targetFrameworkNuget = targetFrameworkNuget; } - public void setSupportsAsync(Boolean supportsAsync){ + public void setSupportsAsync(Boolean supportsAsync) { this.supportsAsync = supportsAsync; } - public void setSupportsUWP(Boolean supportsUWP){ + public void setSupportsUWP(Boolean supportsUWP) { this.supportsUWP = supportsUWP; } - public void setGeneratePropertyChanged(final Boolean generatePropertyChanged){ + public void setGeneratePropertyChanged(final Boolean generatePropertyChanged) { this.generatePropertyChanged = generatePropertyChanged; } @@ -603,11 +613,13 @@ public String modelDocFileFolder() { @Override public String apiTestFileFolder() { - return outputFolder + File.separator + testFolder + File.separator + testPackageName() + File.separator + apiPackage(); + return outputFolder + File.separator + testFolder + File.separator + testPackageName() + + File.separator + apiPackage(); } @Override public String modelTestFileFolder() { - return outputFolder + File.separator + testFolder + File.separator + testPackageName() + File.separator + modelPackage(); + return outputFolder + File.separator + testFolder + File.separator + testPackageName() + + File.separator + modelPackage(); } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java index 157488f15c9..19763e3f025 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java @@ -39,18 +39,26 @@ public ClojureClientCodegen() { apiTemplateFiles.put("api.mustache", ".clj"); embeddedTemplateDir = templateDir = "clojure"; - cliOptions.add(new CliOption(PROJECT_NAME, - "name of the project (Default: generated from info.title or \"swagger-clj-client\")")); - cliOptions.add(new CliOption(PROJECT_DESCRIPTION, - "description of the project (Default: using info.description or \"Client library of \")")); + cliOptions + .add(new CliOption(PROJECT_NAME, + "name of the project (Default: generated from info.title or \"swagger-clj-client\")")); + cliOptions + .add(new CliOption( + PROJECT_DESCRIPTION, + "description of the project (Default: using info.description or \"Client library of \")")); cliOptions.add(new CliOption(PROJECT_VERSION, "version of the project (Default: using info.version or \"1.0.0\")")); - cliOptions.add(new CliOption(PROJECT_URL, - "URL of the project (Default: using info.contact.url or not included in project.clj)")); - cliOptions.add(new CliOption(PROJECT_LICENSE_NAME, - "name of the license the project uses (Default: using info.license.name or not included in project.clj)")); - cliOptions.add(new CliOption(PROJECT_LICENSE_URL, - "URL of the license the project uses (Default: using info.license.url or not included in project.clj)")); + cliOptions + .add(new CliOption(PROJECT_URL, + "URL of the project (Default: using info.contact.url or not included in project.clj)")); + cliOptions + .add(new CliOption( + PROJECT_LICENSE_NAME, + "name of the license the project uses (Default: using info.license.name or not included in project.clj)")); + cliOptions + .add(new CliOption( + PROJECT_LICENSE_URL, + "URL of the license the project uses (Default: using info.license.url or not included in project.clj)")); cliOptions.add(new CliOption(BASE_NAMESPACE, "the base/top namespace (Default: generated from projectName)")); } @@ -89,7 +97,7 @@ public void preprocessSwagger(Swagger swagger) { if (swagger.getInfo() != null) { Info info = swagger.getInfo(); - if (projectName == null && info.getTitle() != null) { + if (projectName == null && info.getTitle() != null) { // when projectName is not specified, generate it from info.title projectName = dashize(info.getTitle()); } @@ -140,7 +148,8 @@ public void preprocessSwagger(Swagger swagger) { additionalProperties.put(BASE_NAMESPACE, baseNamespace); additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); - final String baseNamespaceFolder = sourceFolder + File.separator + namespaceToFolder(baseNamespace); + final String baseNamespaceFolder = + sourceFolder + File.separator + namespaceToFolder(baseNamespace); supportingFiles.add(new SupportingFile("project.mustache", "", "project.clj")); supportingFiles.add(new SupportingFile("core.mustache", baseNamespaceFolder, "core.clj")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); @@ -154,7 +163,8 @@ public String sanitizeTag(String tag) { @Override public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + namespaceToFolder(apiPackage); + return outputFolder + File.separator + sourceFolder + File.separator + + namespaceToFolder(apiPackage); } @Override @@ -184,7 +194,9 @@ public String toParamName(String name) { @Override public String toVarName(String name) { - name = name.replaceAll("[^a-zA-Z0-9_-]+", ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = name.replaceAll("[^a-zA-Z0-9_-]+", ""); // FIXME: a parameter should not be assigned. + // Also declare the methods parameters as + // 'final'. name = dashize(name); return name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ConfluenceWikiGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ConfluenceWikiGenerator.java index 972721bcfa1..4411a1118f6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ConfluenceWikiGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ConfluenceWikiGenerator.java @@ -26,15 +26,20 @@ public ConfluenceWikiGenerator() { cliOptions.add(new CliOption("appName", "short name of the application")); cliOptions.add(new CliOption("appDescription", "description of the application")); - cliOptions.add(new CliOption("infoUrl", "a URL where users can get more information about the application")); - cliOptions.add(new CliOption("infoEmail", "an email address to contact for inquiries about the application")); + cliOptions.add(new CliOption("infoUrl", + "a URL where users can get more information about the application")); + cliOptions.add(new CliOption("infoEmail", + "an email address to contact for inquiries about the application")); cliOptions.add(new CliOption("licenseInfo", "a short description of the license")); cliOptions.add(new CliOption("licenseUrl", "a URL pointing to the full license")); - cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.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_ID, + CodegenConstants.ARTIFACT_ID_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, + CodegenConstants.ARTIFACT_VERSION_DESC)); + additionalProperties.put("appName", "Swagger Sample"); additionalProperties.put("appDescription", "A sample swagger server"); additionalProperties.put("infoUrl", "https://helloreverb.com"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java index ea4c358c197..1b347ff75df 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java @@ -31,8 +31,8 @@ public CodegenType getTag() { } /** - * Configures a friendly name for the generator. This will be used by the - * generator to select the library with the -l flag. + * Configures a friendly name for the generator. This will be used by the generator to select + * the library with the -l flag. * * @return the friendly name for the generator */ @@ -41,8 +41,8 @@ public String getName() { } /** - * Returns human-friendly help for the generator. Provide the consumer with - * help tips, parameters here + * Returns human-friendly help for the generator. Provide the consumer with help tips, + * parameters here * * @return A string value for the help message */ @@ -67,14 +67,17 @@ public CppRestClientCodegen() { cliOptions.clear(); // CLI options - addOption(CodegenConstants.MODEL_PACKAGE, "C++ namespace for models (convention: name.space.model).", - this.modelPackage); - addOption(CodegenConstants.API_PACKAGE, "C++ namespace for apis (convention: name.space.api).", - this.apiPackage); + addOption(CodegenConstants.MODEL_PACKAGE, + "C++ namespace for models (convention: name.space.model).", this.modelPackage); + addOption(CodegenConstants.API_PACKAGE, + "C++ namespace for apis (convention: name.space.api).", this.apiPackage); addOption(CodegenConstants.PACKAGE_VERSION, "C++ package version.", this.packageVersion); - addOption(DECLSPEC, "C++ preprocessor to place before the class name for handling dllexport/dllimport.", + addOption( + DECLSPEC, + "C++ preprocessor to place before the class name for handling dllexport/dllimport.", this.declspec); - addOption(DEFAULT_INCLUDE, + addOption( + DEFAULT_INCLUDE, "The default include statement that should be placed in all headers for including things like the declspec (convention: #include \"Commons.h\" ", this.defaultInclude); @@ -84,22 +87,30 @@ public CppRestClientCodegen() { supportingFiles.add(new SupportingFile("modelbase-source.mustache", "", "ModelBase.cpp")); supportingFiles.add(new SupportingFile("apiclient-header.mustache", "", "ApiClient.h")); supportingFiles.add(new SupportingFile("apiclient-source.mustache", "", "ApiClient.cpp")); - supportingFiles.add(new SupportingFile("apiconfiguration-header.mustache", "", "ApiConfiguration.h")); - supportingFiles.add(new SupportingFile("apiconfiguration-source.mustache", "", "ApiConfiguration.cpp")); - supportingFiles.add(new SupportingFile("apiexception-header.mustache", "", "ApiException.h")); - supportingFiles.add(new SupportingFile("apiexception-source.mustache", "", "ApiException.cpp")); + supportingFiles.add(new SupportingFile("apiconfiguration-header.mustache", "", + "ApiConfiguration.h")); + supportingFiles.add(new SupportingFile("apiconfiguration-source.mustache", "", + "ApiConfiguration.cpp")); + supportingFiles + .add(new SupportingFile("apiexception-header.mustache", "", "ApiException.h")); + supportingFiles.add(new SupportingFile("apiexception-source.mustache", "", + "ApiException.cpp")); supportingFiles.add(new SupportingFile("ihttpbody-header.mustache", "", "IHttpBody.h")); supportingFiles.add(new SupportingFile("jsonbody-header.mustache", "", "JsonBody.h")); supportingFiles.add(new SupportingFile("jsonbody-source.mustache", "", "JsonBody.cpp")); supportingFiles.add(new SupportingFile("httpcontent-header.mustache", "", "HttpContent.h")); - supportingFiles.add(new SupportingFile("httpcontent-source.mustache", "", "HttpContent.cpp")); - supportingFiles.add(new SupportingFile("multipart-header.mustache", "", "MultipartFormData.h")); - supportingFiles.add(new SupportingFile("multipart-source.mustache", "", "MultipartFormData.cpp")); + supportingFiles + .add(new SupportingFile("httpcontent-source.mustache", "", "HttpContent.cpp")); + supportingFiles.add(new SupportingFile("multipart-header.mustache", "", + "MultipartFormData.h")); + supportingFiles.add(new SupportingFile("multipart-source.mustache", "", + "MultipartFormData.cpp")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - languageSpecificPrimitives = new HashSet( - Arrays.asList("int", "char", "bool", "long", "float", "double", "int32_t", "int64_t")); + languageSpecificPrimitives = + new HashSet(Arrays.asList("int", "char", "bool", "long", "float", "double", + "int32_t", "int64_t")); typeMapping = new HashMap(); typeMapping.put("date", "utility::datetime"); @@ -152,9 +163,8 @@ public void processOpts() { } /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle - * escaping those terms here. This logic is only called if a variable - * matches the reseved words + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping those terms + * here. This logic is only called if a variable matches the reseved words * * @return the escaped term */ @@ -164,16 +174,16 @@ public String escapeReservedWord(String name) { } /** - * Location to write model files. You can use the modelPackage() as defined - * when the class is instantiated + * Location to write model files. You can use the modelPackage() as defined when the class is + * instantiated */ public String modelFileFolder() { return outputFolder + "/model"; } /** - * Location to write api files. You can use the apiPackage() as defined when - * the class is instantiated + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated */ @Override public String apiFileFolder() { @@ -208,7 +218,8 @@ public CodegenModel fromModel(String name, Model model, Map allDe @Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + CodegenOperation op = + super.fromOperation(path, httpMethod, operation, definitions, swagger); if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { Response methodResponse = findMethodResponse(operation.getResponses()); @@ -217,8 +228,7 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation if (methodResponse.getSchema() != null) { CodegenProperty cm = fromProperty("response", methodResponse.getSchema()); op.vendorExtensions.put("x-codegen-response", cm); - if(cm.datatype == "HttpContent") - { + if (cm.datatype == "HttpContent") { op.vendorExtensions.put("x-codegen-response-ishttpcontent", true); } } @@ -250,12 +260,11 @@ public String toApiFilename(String name) { } /** - * Optional - type declaration. This is a String which is used by the - * templates to instantiate your types. There is typically special handling - * for different property types + * Optional - type declaration. This is a String which is used by the templates to instantiate + * your types. There is typically special handling for different property types * - * @return a string value used as the `dataType` field for model templates, - * `returnType` for api templates + * @return a string value used as the `dataType` field for model templates, `returnType` for api + * templates */ @Override public String getTypeDeclaration(Property p) { @@ -326,15 +335,16 @@ public void postProcessParameter(CodegenParameter parameter) { boolean isListContainer = parameter.isListContainer == Boolean.TRUE; boolean isString = parameter.isString == Boolean.TRUE; - if (!isPrimitiveType && !isListContainer && !isString && !parameter.dataType.startsWith("std::shared_ptr")) { + if (!isPrimitiveType && !isListContainer && !isString + && !parameter.dataType.startsWith("std::shared_ptr")) { parameter.dataType = "std::shared_ptr<" + parameter.dataType + ">"; } } /** - * Optional - swagger type conversion. This is used to map swagger types in - * a `Property` into either language specific types via `typeMapping` or - * into complex models if there is not a mapping. + * Optional - swagger type conversion. This is used to map swagger types in a `Property` into + * either language specific types via `typeMapping` or into complex models if there is not a + * mapping. * * @return a string value of the type or complex model for this property * @see io.swagger.models.properties.Property diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java index 82d5a76a609..a068734f3fa 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java @@ -22,8 +22,9 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege protected String packageName = "IO.Swagger"; protected String packageVersion = "1.0.0"; protected String clientPackage = "IO.Swagger.Client"; - protected String sourceFolder = "src" + File.separator + "main" + File.separator + "CsharpDotNet2"; - protected String apiDocPath = "docs/"; + protected String sourceFolder = "src" + File.separator + "main" + File.separator + + "CsharpDotNet2"; + protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; @@ -43,39 +44,37 @@ public CsharpDotNet2ClientCodegen() { modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); - setReservedWordsLowerCase( - Arrays.asList( - // local variable names in API methods (endpoints) - "path", "queryParams", "headerParams", "formParams", "fileParams", "postBody", - "authSettings", "response", "StatusCode", - // C# reserved word - "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while") - ); - - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "string", - "bool?", - "double?", - "int?", - "long?", - "float?", - "byte[]", - "List", - "Dictionary", - "DateTime?", - "String", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Guid?", - "System.IO.Stream", // not really a primitive, we include it to avoid model import - "Object") - ); + setReservedWordsLowerCase(Arrays.asList( + // local variable names in API methods (endpoints) + "path", + "queryParams", + "headerParams", + "formParams", + "fileParams", + "postBody", + "authSettings", + "response", + "StatusCode", + // C# reserved word + "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", + "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", + "double", "else", "enum", "event", "explicit", "extern", "false", "finally", + "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", + "interface", "internal", "is", "lock", "long", "namespace", "new", "null", + "object", "operator", "out", "override", "params", "private", "protected", + "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", + "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", + "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", + "virtual", "void", "volatile", "while")); + + + languageSpecificPrimitives = + new HashSet(Arrays.asList("String", "string", "bool?", "double?", "int?", + "long?", "float?", "byte[]", "List", "Dictionary", "DateTime?", "String", + "Boolean", "Double", "Integer", "Long", "Float", "Guid?", + "System.IO.Stream", // not really a primitive, we include it to avoid model + // import + "Object")); instantiationTypes.put("array", "List"); instantiationTypes.put("map", "Dictionary"); @@ -97,10 +96,12 @@ public CsharpDotNet2ClientCodegen() { typeMapping.put("uuid", "Guid?"); cliOptions.clear(); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name (convention: Camel.Case).") - .defaultValue("IO.Swagger")); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "C# package version.").defaultValue("1.0.0")); - cliOptions.add(new CliOption(CLIENT_PACKAGE, "C# client package name (convention: Camel.Case).") + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, + "C# package name (convention: Camel.Case).").defaultValue("IO.Swagger")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "C# package version.") + .defaultValue("1.0.0")); + cliOptions.add(new CliOption(CLIENT_PACKAGE, + "C# client package name (convention: Camel.Case).") .defaultValue("IO.Swagger.Client")); } @@ -132,13 +133,16 @@ public void processOpts() { additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); - supportingFiles.add(new SupportingFile("Configuration.mustache", - sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs")); - supportingFiles.add(new SupportingFile("ApiClient.mustache", - sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiClient.cs")); - supportingFiles.add(new SupportingFile("ApiException.mustache", - sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiException.cs")); - supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor", "packages.config")); + supportingFiles.add(new SupportingFile("Configuration.mustache", sourceFolder + + File.separator + clientPackage.replace(".", java.io.File.separator), + "Configuration.cs")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", sourceFolder + File.separator + + clientPackage.replace(".", java.io.File.separator), "ApiClient.cs")); + supportingFiles.add(new SupportingFile("ApiException.mustache", sourceFolder + + File.separator + clientPackage.replace(".", java.io.File.separator), + "ApiException.cs")); + supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor", + "packages.config")); supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); @@ -172,8 +176,8 @@ public String getHelp() { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -181,18 +185,21 @@ public String escapeReservedWord(String name) { @Override public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar); + return outputFolder + File.separator + sourceFolder + File.separator + + apiPackage().replace('.', File.separatorChar); } @Override public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar); + return outputFolder + File.separator + sourceFolder + File.separator + + modelPackage().replace('.', File.separatorChar); } @Override public String toVarName(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare + // the methods parameters as 'final'. // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) { @@ -247,13 +254,16 @@ public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -301,14 +311,16 @@ public String getSwaggerType(Property p) { @Override public String toOperationId(String operationId) { - // throw exception if method name is empty (should not occur as an auto-generated method name will be used) + // throw exception if method name is empty (should not occur as an auto-generated method + // name will be used) if (StringUtils.isEmpty(operationId)) { throw new RuntimeException("Empty method name (operationId) not allowed"); } // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java index d2a09a8ee3c..0deacce042f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java @@ -44,27 +44,16 @@ public DartClientCodegen() { modelDocTemplateFiles.put("object_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); - setReservedWordsLowerCase( - Arrays.asList( - "abstract", "as", "assert", "async", "async*", "await", - "break", "case", "catch", "class", "const", "continue", - "default", "deferred", "do", "dynamic", "else", "enum", - "export", "external", "extends", "factory", "false", "final", - "finally", "for", "get", "if", "implements", "import", "in", - "is", "library", "new", "null", "operator", "part", "rethrow", - "return", "set", "static", "super", "switch", "sync*", "this", - "throw", "true", "try", "typedef", "var", "void", "while", - "with", "yield", "yield*" ) - ); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "bool", - "int", - "num", - "double") - ); + setReservedWordsLowerCase(Arrays.asList("abstract", "as", "assert", "async", "async*", + "await", "break", "case", "catch", "class", "const", "continue", "default", + "deferred", "do", "dynamic", "else", "enum", "export", "external", "extends", + "factory", "false", "final", "finally", "for", "get", "if", "implements", "import", + "in", "is", "library", "new", "null", "operator", "part", "rethrow", "return", + "set", "static", "super", "switch", "sync*", "this", "throw", "true", "try", + "typedef", "var", "void", "while", "with", "yield", "yield*")); + + languageSpecificPrimitives = + new HashSet(Arrays.asList("String", "bool", "int", "num", "double")); instantiationTypes.put("array", "List"); instantiationTypes.put("map", "Map"); @@ -86,7 +75,7 @@ public DartClientCodegen() { typeMapping.put("Date", "DateTime"); typeMapping.put("date", "DateTime"); typeMapping.put("File", "MultipartFile"); - //TODO binary should be mapped to byte array + // TODO binary should be mapped to byte array // mapped to String as a workaround typeMapping.put("binary", "String"); @@ -94,7 +83,8 @@ public DartClientCodegen() { cliOptions.add(new CliOption(PUB_NAME, "Name in generated pubspec")); cliOptions.add(new CliOption(PUB_VERSION, "Version in generated pubspec")); cliOptions.add(new CliOption(PUB_DESCRIPTION, "Description in generated pubspec")); - cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, "source folder for generated code")); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, + "source folder for generated code")); } @Override @@ -117,31 +107,32 @@ public void processOpts() { super.processOpts(); if (additionalProperties.containsKey(BROWSER_CLIENT)) { - this.setBrowserClient(Boolean.parseBoolean((String) additionalProperties.get(BROWSER_CLIENT))); + this.setBrowserClient(Boolean.parseBoolean((String) additionalProperties + .get(BROWSER_CLIENT))); additionalProperties.put(BROWSER_CLIENT, browserClient); } else { - //not set, use to be passed to template + // not set, use to be passed to template additionalProperties.put(BROWSER_CLIENT, browserClient); } if (additionalProperties.containsKey(PUB_NAME)) { this.setPubName((String) additionalProperties.get(PUB_NAME)); } else { - //not set, use to be passed to template + // not set, use to be passed to template additionalProperties.put(PUB_NAME, pubName); } if (additionalProperties.containsKey(PUB_VERSION)) { this.setPubVersion((String) additionalProperties.get(PUB_VERSION)); } else { - //not set, use to be passed to template + // not set, use to be passed to template additionalProperties.put(PUB_VERSION, pubVersion); } if (additionalProperties.containsKey(PUB_DESCRIPTION)) { this.setPubDescription((String) additionalProperties.get(PUB_DESCRIPTION)); } else { - //not set, use to be passed to template + // not set, use to be passed to template additionalProperties.put(PUB_DESCRIPTION, pubDescription); } @@ -155,16 +146,23 @@ public void processOpts() { final String libFolder = sourceFolder + File.separator + "lib"; supportingFiles.add(new SupportingFile("pubspec.mustache", "", "pubspec.yaml")); - supportingFiles.add(new SupportingFile("analysis_options.mustache", "", ".analysis_options")); - supportingFiles.add(new SupportingFile("api_client.mustache", libFolder, "api_client.dart")); - supportingFiles.add(new SupportingFile("api_exception.mustache", libFolder, "api_exception.dart")); - supportingFiles.add(new SupportingFile("api_helper.mustache", libFolder, "api_helper.dart")); + supportingFiles + .add(new SupportingFile("analysis_options.mustache", "", ".analysis_options")); + supportingFiles + .add(new SupportingFile("api_client.mustache", libFolder, "api_client.dart")); + supportingFiles.add(new SupportingFile("api_exception.mustache", libFolder, + "api_exception.dart")); + supportingFiles + .add(new SupportingFile("api_helper.mustache", libFolder, "api_helper.dart")); supportingFiles.add(new SupportingFile("apilib.mustache", libFolder, "api.dart")); final String authFolder = sourceFolder + File.separator + "lib" + File.separator + "auth"; - supportingFiles.add(new SupportingFile("auth/authentication.mustache", authFolder, "authentication.dart")); - supportingFiles.add(new SupportingFile("auth/http_basic_auth.mustache", authFolder, "http_basic_auth.dart")); - supportingFiles.add(new SupportingFile("auth/api_key_auth.mustache", authFolder, "api_key_auth.dart")); + supportingFiles.add(new SupportingFile("auth/authentication.mustache", authFolder, + "authentication.dart")); + supportingFiles.add(new SupportingFile("auth/http_basic_auth.mustache", authFolder, + "http_basic_auth.dart")); + supportingFiles.add(new SupportingFile("auth/api_key_auth.mustache", authFolder, + "api_key_auth.dart")); supportingFiles.add(new SupportingFile("auth/oauth.mustache", authFolder, "oauth.dart")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); @@ -174,8 +172,8 @@ public void processOpts() { @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -183,12 +181,14 @@ public String escapeReservedWord(String name) { @Override public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + return outputFolder + "/" + sourceFolder + "/" + + apiPackage().replace('.', File.separatorChar); } @Override public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + return outputFolder + "/" + sourceFolder + "/" + + modelPackage().replace('.', File.separatorChar); } @Override @@ -204,7 +204,8 @@ public String modelDocFileFolder() { @Override public String toVarName(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare + // the methods parameters as 'final'. // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) { @@ -233,7 +234,8 @@ public String toParamName(String name) { public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + + camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } @@ -297,7 +299,8 @@ public String toOperationId(String operationId) { // 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); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + newOperationId); return newOperationId; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ElixirClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ElixirClientCodegen.java index 1a611e4d590..04fb602c2a7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ElixirClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ElixirClientCodegen.java @@ -20,10 +20,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig String supportedElixirVersion = "1.4"; List extraApplications = Arrays.asList(":logger"); - List deps = Arrays.asList( - "{:tesla, \"~> 0.5.0\"}", - "{:poison, \">= 1.0.0\"}" - ); + List deps = Arrays.asList("{:tesla, \"~> 0.5.0\"}", "{:poison, \">= 1.0.0\"}"); public ElixirClientCodegen() { @@ -33,76 +30,59 @@ public ElixirClientCodegen() { outputFolder = "generated-code/elixir"; /** - * Models. You can write model files using the modelTemplateFiles map. - * if you want to create one template for file, you can do so here. - * for multiple files for model, just put another entry in the `modelTemplateFiles` with - * a different extension + * Models. You can write model files using the modelTemplateFiles map. if you want to create + * one template for file, you can do so here. for multiple files for model, just put another + * entry in the `modelTemplateFiles` with a different extension */ - modelTemplateFiles.put( - "model.mustache", // the template to use - ".ex"); // the extension for each file to write + modelTemplateFiles.put("model.mustache", // the template to use + ".ex"); // the extension for each file to write /** - * Api classes. You can write classes for each Api file with the apiTemplateFiles map. - * as with models, add multiple entries with different extensions for multiple files per - * class + * Api classes. You can write classes for each Api file with the apiTemplateFiles map. as + * with models, add multiple entries with different extensions for multiple files per class */ - apiTemplateFiles.put( - "api.mustache", // the template to use - ".ex"); // the extension for each file to write + apiTemplateFiles.put("api.mustache", // the template to use + ".ex"); // the extension for each file to write /** - * Template Location. This is the location which templates will be read from. The generator + * Template Location. This is the location which templates will be read from. The generator * will use the resource stream to attempt to read the templates. */ templateDir = "elixir"; /** - * Reserved words. Override this with reserved words specific to your language + * Reserved words. Override this with reserved words specific to your language */ - reservedWords = new HashSet( - Arrays.asList( - "sample1", // replace with static values - "sample2") - ); + reservedWords = new HashSet(Arrays.asList("sample1", // replace with static values + "sample2")); /** - * Additional Properties. These values can be passed to the templates and - * are available in models, apis, and supporting files + * Additional Properties. These values can be passed to the templates and are available in + * models, apis, and supporting files */ additionalProperties.put("apiVersion", apiVersion); /** - * Supporting Files. You can write single files for the generator with the - * entire object tree available. If the input file has a suffix of `.mustache - * it will be processed by the template engine. Otherwise, it will be copied + * Supporting Files. You can write single files for the generator with the entire object + * tree available. If the input file has a suffix of `.mustache it will be processed by the + * template engine. Otherwise, it will be copied */ - supportingFiles.add(new SupportingFile("README.md.mustache", // the input template or file - "", // the destination folder, relative `outputFolder` - "README.md") // the output file - ); - supportingFiles.add(new SupportingFile("config.exs.mustache", - "config", - "config.exs") - ); - supportingFiles.add(new SupportingFile("mix.exs.mustache", - "", - "mix.exs") - ); - supportingFiles.add(new SupportingFile("test_helper.exs.mustache", - "test", - "test_helper.exs") - ); + supportingFiles.add(new SupportingFile("README.md.mustache", // the input template or file + "", // the destination folder, relative `outputFolder` + "README.md") // the output file + ); + supportingFiles.add(new SupportingFile("config.exs.mustache", "config", "config.exs")); + supportingFiles.add(new SupportingFile("mix.exs.mustache", "", "mix.exs")); + supportingFiles.add(new SupportingFile("test_helper.exs.mustache", "test", + "test_helper.exs")); /** - * Language Specific Primitives. These types will not trigger imports by - * the client generator + * Language Specific Primitives. These types will not trigger imports by the client + * generator */ - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "Type1", // replace these with your types - "Type2") - ); + languageSpecificPrimitives = new HashSet(Arrays.asList("Type1", // replace these + // with your types + "Type2")); } /** @@ -116,8 +96,8 @@ public CodegenType getTag() { } /** - * Configures a friendly name for the generator. This will be used by the generator - * to select the library with the -l flag. + * Configures a friendly name for the generator. This will be used by the generator to select + * the library with the -l flag. * * @return the friendly name for the generator */ @@ -126,8 +106,8 @@ public String getName() { } /** - * Returns human-friendly help for the generator. Provide the consumer with help - * tips, parameters here + * Returns human-friendly help for the generator. Provide the consumer with help tips, + * parameters here * * @return A string value for the help message */ @@ -157,7 +137,8 @@ public void execute(Template.Fragment fragment, Writer writer) throws IOExceptio @Override public Map postProcessOperations(Map objs) { - Map operations = (Map) super.postProcessOperations(objs).get("operations"); + Map operations = + (Map) super.postProcessOperations(objs).get("operations"); List os = (List) operations.get("operation"); List newOs = new ArrayList(); Pattern pattern = Pattern.compile("(.*)\\{([^\\}]+)\\}(.*)"); @@ -167,7 +148,8 @@ public Map postProcessOperations(Map objs) { StringBuffer buffer = new StringBuffer(); while (matcher.find()) { String pathTemplateName = matcher.group(2); - matcher.appendReplacement(buffer, "$1" + "#{" + underscore(pathTemplateName) + "}" + "$3"); + matcher.appendReplacement(buffer, "$1" + "#{" + underscore(pathTemplateName) + "}" + + "$3"); pathTemplateNames.add(pathTemplateName); } ExtendedCodegenOperation eco = new ExtendedCodegenOperation(o); @@ -212,31 +194,33 @@ String modulized(String words) { } /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping - * those terms here. This logic is only called if a variable matches the reseved words + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping those terms + * here. This logic is only called if a variable matches the reseved words * * @return the escaped term */ @Override public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name + return "_" + name; // add an underscore to the name } /** - * Location to write model files. You can use the modelPackage() as defined when the class is + * Location to write model files. You can use the modelPackage() as defined when the class is * instantiated */ public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + underscored((String) additionalProperties.get("appName")) + "/" + "model"; + return outputFolder + "/" + sourceFolder + "/" + + underscored((String) additionalProperties.get("appName")) + "/" + "model"; } /** - * Location to write api files. You can use the apiPackage() as defined when the class is + * Location to write api files. You can use the apiPackage() as defined when the class is * instantiated */ @Override public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + underscored((String) additionalProperties.get("appName")) + "/" + "api"; + return outputFolder + "/" + sourceFolder + "/" + + underscored((String) additionalProperties.get("appName")) + "/" + "api"; } @Override @@ -258,10 +242,11 @@ public String toModelFilename(String name) { } /** - * Optional - type declaration. This is a String which is used by the templates to instantiate your - * types. There is typically special handling for different property types + * Optional - type declaration. This is a String which is used by the templates to instantiate + * your types. There is typically special handling for different property types * - * @return a string value used as the `dataType` field for model templates, `returnType` for api templates + * @return a string value used as the `dataType` field for model templates, `returnType` for api + * templates */ @Override public String getTypeDeclaration(Property p) { @@ -278,8 +263,9 @@ public String getTypeDeclaration(Property p) { } /** - * Optional - swagger type conversion. This is used to map swagger types in a `Property` into - * either language specific types via `typeMapping` or into complex models if there is not a mapping. + * Optional - swagger type conversion. This is used to map swagger types in a `Property` into + * either language specific types via `typeMapping` or into complex models if there is not a + * mapping. * * @return a string value of the type or complex model for this property * @see io.swagger.models.properties.Property diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java index 5a78713b414..2a70c5b937d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java @@ -42,38 +42,31 @@ public ErlangServerCodegen() { }; /** - * Models. You can write model files using the modelTemplateFiles map. - * if you want to create one template for file, you can do so here. - * for multiple files for model, just put another entry in the `modelTemplateFiles` with - * a different extension + * Models. You can write model files using the modelTemplateFiles map. if you want to create + * one template for file, you can do so here. for multiple files for model, just put another + * entry in the `modelTemplateFiles` with a different extension */ modelTemplateFiles.clear(); /** - * Api classes. You can write classes for each Api file with the apiTemplateFiles map. - * as with models, add multiple entries with different extensions for multiple files per - * class + * Api classes. You can write classes for each Api file with the apiTemplateFiles map. as + * with models, add multiple entries with different extensions for multiple files per class */ - apiTemplateFiles.put( - "handler.mustache", // the template to use - ".erl"); // the extension for each file to write + apiTemplateFiles.put("handler.mustache", // the template to use + ".erl"); // the extension for each file to write /** - * Template Location. This is the location which templates will be read from. The generator + * Template Location. This is the location which templates will be read from. The generator * will use the resource stream to attempt to read the templates. */ embeddedTemplateDir = templateDir = "erlang-server"; /** - * Reserved words. Override this with reserved words specific to your language + * Reserved words. Override this with reserved words specific to your language */ - setReservedWordsLowerCase( - Arrays.asList( - "after","and","andalso","band","begin","bnot","bor","bsl","bsr","bxor","case", - "catch","cond","div","end","fun","if","let","not","of","or","orelse","receive", - "rem","try","when","xor" - ) - ); + setReservedWordsLowerCase(Arrays.asList("after", "and", "andalso", "band", "begin", "bnot", + "bor", "bsl", "bsr", "bxor", "case", "catch", "cond", "div", "end", "fun", "if", + "let", "not", "of", "or", "orelse", "receive", "rem", "try", "when", "xor")); instantiationTypes.clear(); @@ -102,29 +95,37 @@ public ErlangServerCodegen() { typeMapping.put("password", "binary"); cliOptions.clear(); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Erlang package name (convention: lowercase).") - .defaultValue(this.packageName)); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, + "Erlang package name (convention: lowercase).").defaultValue(this.packageName)); /** - * Additional Properties. These values can be passed to the templates and - * are available in models, apis, and supporting files + * Additional Properties. These values can be passed to the templates and are available in + * models, apis, and supporting files */ additionalProperties.put("apiVersion", apiVersion); additionalProperties.put("apiPath", apiPath); /** - * Supporting Files. You can write single files for the generator with the - * entire object tree available. If the input file has a suffix of `.mustache - * it will be processed by the template engine. Otherwise, it will be copied + * Supporting Files. You can write single files for the generator with the entire object + * tree available. If the input file has a suffix of `.mustache it will be processed by the + * template engine. Otherwise, it will be copied */ - supportingFiles.add(new SupportingFile("rebar.config.mustache","", "rebar.config")); - supportingFiles.add(new SupportingFile("app.src.mustache", "", "src" + File.separator + this.packageName + ".app.src")); - supportingFiles.add(new SupportingFile("router.mustache", "", toSourceFilePath("router", "erl"))); - supportingFiles.add(new SupportingFile("api.mustache", "", toSourceFilePath("api", "erl"))); - supportingFiles.add(new SupportingFile("server.mustache", "", toSourceFilePath("server", "erl"))); - supportingFiles.add(new SupportingFile("utils.mustache", "", toSourceFilePath("utils", "erl"))); - supportingFiles.add(new SupportingFile("auth.mustache", "", toSourceFilePath("auth", "erl"))); - supportingFiles.add(new SupportingFile("swagger.mustache", "", toPrivFilePath("swagger", "json"))); - supportingFiles.add(new SupportingFile("default_logic_handler.mustache", "", toSourceFilePath("default_logic_handler", "erl"))); - supportingFiles.add(new SupportingFile("logic_handler.mustache", "", toSourceFilePath("logic_handler", "erl"))); + supportingFiles.add(new SupportingFile("rebar.config.mustache", "", "rebar.config")); + supportingFiles.add(new SupportingFile("app.src.mustache", "", "src" + File.separator + + this.packageName + ".app.src")); + supportingFiles.add(new SupportingFile("router.mustache", "", toSourceFilePath("router", + "erl"))); + supportingFiles.add(new SupportingFile("api.mustache", "", toSourceFilePath("api", "erl"))); + supportingFiles.add(new SupportingFile("server.mustache", "", toSourceFilePath("server", + "erl"))); + supportingFiles.add(new SupportingFile("utils.mustache", "", toSourceFilePath("utils", + "erl"))); + supportingFiles + .add(new SupportingFile("auth.mustache", "", toSourceFilePath("auth", "erl"))); + supportingFiles.add(new SupportingFile("swagger.mustache", "", toPrivFilePath("swagger", + "json"))); + supportingFiles.add(new SupportingFile("default_logic_handler.mustache", "", + toSourceFilePath("default_logic_handler", "erl"))); + supportingFiles.add(new SupportingFile("logic_handler.mustache", "", toSourceFilePath( + "logic_handler", "erl"))); writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); } @@ -145,8 +146,8 @@ public CodegenType getTag() { } /** - * Configures a friendly name for the generator. This will be used by the generator - * to select the library with the -l flag. + * Configures a friendly name for the generator. This will be used by the generator to select + * the library with the -l flag. * * @return the friendly name for the generator */ @@ -156,15 +157,15 @@ public String getName() { } /** - * Returns human-friendly help for the generator. Provide the consumer with help - * tips, parameters here + * Returns human-friendly help for the generator. Provide the consumer with help tips, + * parameters here * * @return A string value for the help message */ @Override public String getHelp() { - return "Generates an Erlang server library (beta) using the Swagger Codegen project. By default, " + - "it will also generate service classes, which can be disabled with the `-Dnoservice` environment variable."; + return "Generates an Erlang server library (beta) using the Swagger Codegen project. By default, " + + "it will also generate service classes, which can be disabled with the `-Dnoservice` environment variable."; } @Override @@ -176,21 +177,21 @@ public String toApiName(String name) { } /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping - * those terms here. This logic is only called if a variable matches the reseved words + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping those terms + * here. This logic is only called if a variable matches the reseved words * * @return the escaped term */ @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; } /** - * Location to write api files. You can use the apiPackage() as defined when the class is + * Location to write api files. You can use the apiPackage() as defined when the class is * instantiated */ @Override @@ -207,7 +208,8 @@ public String toModelName(String name) { public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } @@ -233,8 +235,8 @@ public Map postProcessOperations(Map objs) { @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { + Swagger swagger = (Swagger) objs.get("swagger"); + if (swagger != null) { try { objs.put("swagger-json", Json.mapper().writeValueAsString(swagger)); } catch (JsonProcessingException e) { @@ -257,7 +259,7 @@ protected String toModuleName(String name) { } protected String toSourceFilePath(String name, String extension) { - return "src" + File.separator + toModuleName(name) + "." + extension; + return "src" + File.separator + toModuleName(name) + "." + extension; } protected String toIncludeFilePath(String name, String extension) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java index f807325c144..d097ac63df8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java @@ -32,46 +32,25 @@ public FinchServerCodegen() { apiPackage = packageName + ".apis"; modelPackage = packageName + ".models"; - setReservedWordsLowerCase( - Arrays.asList( - // Scala - "abstract", "case", "catch", "class", "def", - "do", "else", "extends", "false", "final", - "finally", "for", "forSome", "if", "implicit", - "import", "lazy", "match", "new", "null", - "object", "override", "package", "private", "protected", - "return", "sealed", "super", "this", "throw", - "trait", "try", "true", "type", "val", - "var", "while", "with", "yield", - // Scala-interop languages keywords - "abstract", "continue", "switch", "assert", - "default", "synchronized", "goto", - "break", "double", "implements", "byte", - "public", "throws", "enum", "instanceof", "transient", - "int", "short", "char", "interface", "static", - "void", "finally", "long", "strictfp", "volatile", "const", "float", - "native") - ); - - defaultIncludes = new HashSet( - Arrays.asList("double", - "Int", - "Long", - "Float", - "Double", - "char", - "float", - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "List", - "Set", - "Map") - ); + setReservedWordsLowerCase(Arrays.asList( + // Scala + "abstract", "case", "catch", "class", "def", "do", "else", "extends", "false", + "final", "finally", "for", "forSome", "if", "implicit", "import", "lazy", "match", + "new", "null", "object", "override", "package", "private", "protected", "return", + "sealed", "super", "this", "throw", "trait", "try", "true", "type", "val", "var", + "while", + "with", + "yield", + // Scala-interop languages keywords + "abstract", "continue", "switch", "assert", "default", "synchronized", "goto", + "break", "double", "implements", "byte", "public", "throws", "enum", "instanceof", + "transient", "int", "short", "char", "interface", "static", "void", "finally", + "long", "strictfp", "volatile", "const", "float", "native")); + + defaultIncludes = + new HashSet(Arrays.asList("double", "Int", "Long", "Float", "Double", + "char", "float", "String", "boolean", "Boolean", "Double", "Integer", + "Long", "Float", "List", "Set", "Map")); typeMapping = new HashMap(); typeMapping.put("string", "String"); @@ -114,29 +93,21 @@ public FinchServerCodegen() { supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt")); supportingFiles.add(new SupportingFile("Server.mustache", sourceFolder, "Server.scala")); - supportingFiles.add(new SupportingFile("DataAccessor.mustache", sourceFolder, "DataAccessor.scala")); + supportingFiles.add(new SupportingFile("DataAccessor.mustache", sourceFolder, + "DataAccessor.scala")); - supportingFiles.add(new SupportingFile("project/build.properties", "project", "build.properties")); + supportingFiles.add(new SupportingFile("project/build.properties", "project", + "build.properties")); supportingFiles.add(new SupportingFile("project/plugins.sbt", "project", "plugins.sbt")); supportingFiles.add(new SupportingFile("sbt", "", "sbt")); - supportingFiles.add(new SupportingFile("endpoint.mustache", sourceFolder, "endpoint.scala")); + supportingFiles + .add(new SupportingFile("endpoint.mustache", sourceFolder, "endpoint.scala")); supportingFiles.add(new SupportingFile("errors.mustache", sourceFolder, "errors.scala")); - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "Boolean", - "Double", - "Int", - "Integer", - "Long", - "Float", - "Any", - "AnyVal", - "AnyRef", - "Object") - ); + languageSpecificPrimitives = + new HashSet(Arrays.asList("String", "Boolean", "Double", "Int", "Integer", + "Long", "Float", "Any", "AnyVal", "AnyRef", "Object")); instantiationTypes.put("array", "ArrayList"); instantiationTypes.put("map", "HashMap"); @@ -156,10 +127,12 @@ public FinchServerCodegen() { importMapping.put("LocalTime", "java.time.LocalTime"); cliOptions.clear(); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Finch package name (e.g. io.swagger).") - .defaultValue(this.packageName)); - cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, + "Finch package name (e.g. io.swagger).").defaultValue(this.packageName)); + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, + CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, + CodegenConstants.API_PACKAGE_DESC)); } @Override @@ -184,19 +157,21 @@ public String escapeReservedWord(String name) { @Override public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar); + return outputFolder + File.separator + sourceFolder + File.separator + + apiPackage().replace('.', File.separatorChar); } @Override public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar); + return outputFolder + File.separator + sourceFolder + File.separator + + modelPackage().replace('.', File.separatorChar); } /** * Convert Swagger Model object to Codegen Model object * - * @param name the name of the model - * @param model Swagger Model object + * @param name the name of the model + * @param model Swagger Model object * @param allDefinitions a map of all Swagger models from the spec * @return Codegen Model object */ @@ -220,7 +195,7 @@ public Map postProcessOperations(Map objs) { } // remove last / if (path.endsWith("/")) { - path = path.substring(0, path.length()-1); + path = path.substring(0, path.length() - 1); } String[] items = path.split("/", -1); @@ -240,7 +215,7 @@ public Map postProcessOperations(Map objs) { scalaPath = scalaPath + "\"" + items[i] + "\""; } - if (i != items.length -1) { + if (i != items.length - 1) { scalaPath = scalaPath + " :: "; } } @@ -248,17 +223,23 @@ public Map postProcessOperations(Map objs) { for (CodegenParameter p : op.allParams) { // TODO: This hacky, should be converted to mappings if possible to keep it clean. // This could also be done using template imports - if(Boolean.TRUE.equals(p.isPrimitiveType)) { - p.vendorExtensions.put("x-codegen-normalized-path-type", p.dataType.toLowerCase()); + if (Boolean.TRUE.equals(p.isPrimitiveType)) { + p.vendorExtensions.put("x-codegen-normalized-path-type", + p.dataType.toLowerCase()); p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType); - } else if(Boolean.TRUE.equals(p.isBodyParam)) { - p.vendorExtensions.put("x-codegen-normalized-path-type", "jsonBody["+ p.dataType + "]"); + } else if (Boolean.TRUE.equals(p.isBodyParam)) { + p.vendorExtensions.put("x-codegen-normalized-path-type", "jsonBody[" + + p.dataType + "]"); p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType); - } else if(Boolean.TRUE.equals(p.isContainer) || Boolean.TRUE.equals(p.isListContainer)) { - p.vendorExtensions.put("x-codegen-normalized-path-type", "params(\""+ p.paramName + "\")"); - p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType.replaceAll("^[^\\[]+", "Seq")); - } else if(Boolean.TRUE.equals(p.isFile)) { - p.vendorExtensions.put("x-codegen-normalized-path-type", "fileUpload(\""+ p.paramName + "\")"); + } else if (Boolean.TRUE.equals(p.isContainer) + || Boolean.TRUE.equals(p.isListContainer)) { + p.vendorExtensions.put("x-codegen-normalized-path-type", "params(\"" + + p.paramName + "\")"); + p.vendorExtensions.put("x-codegen-normalized-input-type", + p.dataType.replaceAll("^[^\\[]+", "Seq")); + } else if (Boolean.TRUE.equals(p.isFile)) { + p.vendorExtensions.put("x-codegen-normalized-path-type", "fileUpload(\"" + + p.paramName + "\")"); p.vendorExtensions.put("x-codegen-normalized-input-type", "FileUpload"); } else { p.vendorExtensions.put("x-codegen-normalized-path-type", p.dataType); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java index 1a9cbdd6299..44b1e4fd2c7 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java @@ -1,390 +1,414 @@ -package io.swagger.codegen.languages; - -import io.swagger.codegen.CliOption; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; -import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.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; -import org.apache.commons.lang3.StringUtils; - -import java.io.File; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; - -public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String packageName = "io.swagger"; - protected String packageVersion; - - protected String invokerPackage = "io.swagger"; - protected String sourceFolder = "flash"; - - public FlashClientCodegen() { - super(); - - modelPackage = "io.swagger.client.model"; - apiPackage = "io.swagger.client.api"; - outputFolder = "generated-code" + File.separatorChar + "flash"; - modelTemplateFiles.put("model.mustache", ".as"); - modelTemplateFiles.put("modelList.mustache", "List.as"); - apiTemplateFiles.put("api.mustache", ".as"); - embeddedTemplateDir = templateDir = "flash"; - - languageSpecificPrimitives.clear(); - languageSpecificPrimitives.add("Number"); - languageSpecificPrimitives.add("Boolean"); - languageSpecificPrimitives.add("String"); - languageSpecificPrimitives.add("Date"); - languageSpecificPrimitives.add("Array"); - languageSpecificPrimitives.add("Dictionary"); - - typeMapping.clear(); - typeMapping.put("integer", "Number"); - typeMapping.put("float", "Number"); - typeMapping.put("long", "Number"); - typeMapping.put("double", "Number"); - typeMapping.put("array", "Array"); - typeMapping.put("map", "Dictionary"); - typeMapping.put("boolean", "Boolean"); - typeMapping.put("string", "String"); - typeMapping.put("date", "Date"); - typeMapping.put("DateTime", "Date"); - typeMapping.put("object", "Object"); - typeMapping.put("file", "File"); - //TODO binary should be mapped to byte array - // mapped to String as a workaround - typeMapping.put("binary", "String"); - - importMapping = new HashMap(); - importMapping.put("File", "flash.filesystem.File"); - - // from - setReservedWordsLowerCase(Arrays.asList("add", "for", "lt", "tellTarget", "and", - "function", "ne", "this", "break", "ge", "new", "typeof", "continue", "gt", "not", - "var", "delete", "if", "on", "void", "do", "ifFrameLoaded", "onClipEvent", "while", - "else", "in", "or", "with", "eq", "le", "return")); - - cliOptions.clear(); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "flash package name (convention:" + - " package.name)").defaultValue("io.swagger")); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "flash package version") - .defaultValue("1.0.0")); - cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, "source folder for generated " + - "code. e.g. flash")); - - } - - @Override - public void processOpts() { - super.processOpts(); - - if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { - this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); - } else { - //not set, use default to be passed to template - additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); - } - - if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { - this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); - } - - if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { - setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); - apiPackage = packageName + ".client.api"; - modelPackage = packageName + ".client.model"; - } - else { - setPackageName("io.swagger"); - } - - if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { - setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); - } - else { - setPackageVersion("1.0.0"); - } - - additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); - additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); - - //modelPackage = invokerPackage + File.separatorChar + "client" + File.separatorChar + "model"; - //apiPackage = invokerPackage + File.separatorChar + "client" + File.separatorChar + "api"; - - final String invokerFolder = (sourceFolder + File.separator + "src/" + invokerPackage + File.separator).replace(".", File.separator).replace('.', File.separatorChar); - - supportingFiles.add(new SupportingFile("ApiInvoker.as", invokerFolder + "common", "ApiInvoker.as")); - supportingFiles.add(new SupportingFile("ApiUrlHelper.as", invokerFolder + "common", "ApiUrlHelper.as")); - supportingFiles.add(new SupportingFile("ApiUserCredentials.as", invokerFolder + "common", "ApiUserCredentials.as")); - supportingFiles.add(new SupportingFile("ListWrapper.as", invokerFolder + "common", "ListWrapper.as")); - supportingFiles.add(new SupportingFile("SwaggerApi.as", invokerFolder + "common", "SwaggerApi.as")); - supportingFiles.add(new SupportingFile("XMLWriter.as", invokerFolder + "common", "XMLWriter.as")); - supportingFiles.add(new SupportingFile("ApiError.as", invokerFolder + "exception", "ApiError.as")); - supportingFiles.add(new SupportingFile("ApiErrorCodes.as", invokerFolder + "exception", "ApiErrorCodes.as")); - supportingFiles.add(new SupportingFile("ApiClientEvent.as", invokerFolder + "event", "ApiClientEvent.as")); - supportingFiles.add(new SupportingFile("Response.as", invokerFolder + "event", "Response.as")); - supportingFiles.add(new SupportingFile("build.properties", sourceFolder, "build.properties")); - supportingFiles.add(new SupportingFile("build.xml", sourceFolder, "build.xml")); - supportingFiles.add(new SupportingFile("README.txt", sourceFolder, "README.txt")); - //supportingFiles.add(new SupportingFile("AirExecutorApp-app.xml", sourceFolder + File.separatorChar - // + "bin", "AirExecutorApp-app.xml")); - supportingFiles.add(new SupportingFile("ASAXB-0.1.1.swc", sourceFolder + File.separatorChar - + "lib", "ASAXB-0.1.1.swc")); - supportingFiles.add(new SupportingFile("as3corelib.swc", sourceFolder + File.separatorChar - + "lib", "as3corelib.swc")); - supportingFiles.add(new SupportingFile("flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc", sourceFolder - + File.separator + "lib" + File.separator + "ext", "flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc")); - supportingFiles.add(new SupportingFile("flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc", sourceFolder - + File.separator + "lib" + File.separator + "ext", "flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc")); - supportingFiles.add(new SupportingFile("flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc", sourceFolder - + File.separator + "lib" + File.separator + "ext", "flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc")); - supportingFiles.add(new SupportingFile("flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc", sourceFolder - + File.separator + "lib" + File.separator + "ext", "flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - } - - private static String dropDots(String str) { - return str.replaceAll("\\.", "_"); - } - - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - @Override - public String getName() { - return "flash"; - } - - @Override - public String getHelp() { - return "Generates a Flash client library."; - } - - @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { - return this.reservedWordsMappings().get(name); - } - return "_" + name; - } - - @Override - public String apiFileFolder() { - return (outputFolder + File.separatorChar + sourceFolder + File.separatorChar + "src/" - + apiPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); - } - - @Override - public String modelFileFolder() { - return (outputFolder + File.separatorChar + sourceFolder + File.separatorChar + "src/" - + modelPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty || p instanceof MapProperty) { - return getSwaggerType(p); - } - return super.getTypeDeclaration(p); - } - - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) { - return type; - } - } else { - type = toModelName(swaggerType); - } - return type; - } - - @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - return "null"; - } else if (p instanceof BooleanProperty) { - return "false"; - } else if (p instanceof DateProperty) { - return "null"; - } else if (p instanceof DateTimeProperty) { - return "null"; - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return "0.0"; - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return "0.0"; - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return "0"; - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return "0"; - } else if (p instanceof MapProperty) { - return "new Dictionary()"; - } else if (p instanceof ArrayProperty) { - return "new Array()"; - } else { - return "NaN"; - } - } - - @Override - public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - // if it's all uppper case, convert to lower case - if (name.matches("^[A-Z_]*$")) { - name = name.toLowerCase(); - } - - // underscore the variable name - // petId => pet_id - name = camelize(dropDots(name), true); - - // for reserved word or word starting with number, append _ - if (isReservedWord(name) || name.matches("^\\d.*")) { - name = escapeReservedWord(name); - } - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - - @Override - public String toModelName(String name) { - if (!StringUtils.isEmpty(modelNamePrefix)) { - name = modelNamePrefix + "_" + name; - } - - if (!StringUtils.isEmpty(modelNameSuffix)) { - name = name + "_" + modelNameSuffix; - } - - name = sanitizeName(name); - - // model name cannot use reserved keyword, e.g. return - if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); - name = "model_" + name; // e.g. return => ModelReturn (after camelize) - } - - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } - - @Override - public String toModelFilename(String name) { - // leverage toModelName - return dropDots(toModelName(name)); - } - - @Override - public String toApiFilename(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - // e.g. PhoneNumberApi.rb => phone_number_api.rb - return camelize(name) + "Api"; - } - - @Override - public String toApiName(String name) { - if (name.length() == 0) { - return "DefaultApi"; - } - // e.g. phone_number_api => PhoneNumberApi - return camelize(name) + "Api"; - } - - @Override - public String toApiVarName(String name) { - if (name.length() == 0) { - return "DefaultApi"; - } - return camelize(name) + "Api"; - } - - @Override - public String toOperationId(String operationId) { - // throw exception if method name is empty - if (StringUtils.isEmpty(operationId)) { - throw new RuntimeException("Empty method name (operationId) not allowed"); - } - - // method name cannot use reserved keyword, e.g. return - if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); - operationId = "call_" + operationId; - } - - return underscore(operationId); - } - - public void setPackageName(String packageName) { - this.packageName = packageName; - } - - public void setPackageVersion(String packageVersion) { - this.packageVersion = packageVersion; - } - - public void setInvokerPackage(String invokerPackage) { - this.invokerPackage = invokerPackage; - } - - public void setSourceFolder(String sourceFolder) { - this.sourceFolder = sourceFolder; - } - - @Override - public String escapeQuotationMark(String input) { - // remove " to avoid code injection - return input.replace("\"", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } -} +package io.swagger.codegen.languages; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.BooleanProperty; +import io.swagger.models.properties.DateProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.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; +import org.apache.commons.lang3.StringUtils; + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; + +public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String packageName = "io.swagger"; + protected String packageVersion; + + protected String invokerPackage = "io.swagger"; + protected String sourceFolder = "flash"; + + public FlashClientCodegen() { + super(); + + modelPackage = "io.swagger.client.model"; + apiPackage = "io.swagger.client.api"; + outputFolder = "generated-code" + File.separatorChar + "flash"; + modelTemplateFiles.put("model.mustache", ".as"); + modelTemplateFiles.put("modelList.mustache", "List.as"); + apiTemplateFiles.put("api.mustache", ".as"); + embeddedTemplateDir = templateDir = "flash"; + + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("Number"); + languageSpecificPrimitives.add("Boolean"); + languageSpecificPrimitives.add("String"); + languageSpecificPrimitives.add("Date"); + languageSpecificPrimitives.add("Array"); + languageSpecificPrimitives.add("Dictionary"); + + typeMapping.clear(); + typeMapping.put("integer", "Number"); + typeMapping.put("float", "Number"); + typeMapping.put("long", "Number"); + typeMapping.put("double", "Number"); + typeMapping.put("array", "Array"); + typeMapping.put("map", "Dictionary"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("string", "String"); + typeMapping.put("date", "Date"); + typeMapping.put("DateTime", "Date"); + typeMapping.put("object", "Object"); + typeMapping.put("file", "File"); + // TODO binary should be mapped to byte array + // mapped to String as a workaround + typeMapping.put("binary", "String"); + + importMapping = new HashMap(); + importMapping.put("File", "flash.filesystem.File"); + + // from + setReservedWordsLowerCase(Arrays.asList("add", "for", "lt", "tellTarget", "and", + "function", "ne", "this", "break", "ge", "new", "typeof", "continue", "gt", "not", + "var", "delete", "if", "on", "void", "do", "ifFrameLoaded", "onClipEvent", "while", + "else", "in", "or", "with", "eq", "le", "return")); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, + "flash package name (convention:" + " package.name)").defaultValue("io.swagger")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "flash package version") + .defaultValue("1.0.0")); + cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, + CodegenConstants.INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, "source folder for generated " + + "code. e.g. flash")); + + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + this.setInvokerPackage((String) additionalProperties + .get(CodegenConstants.INVOKER_PACKAGE)); + } else { + // not set, use default to be passed to template + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + } + + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { + this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); + } + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + apiPackage = packageName + ".client.api"; + modelPackage = packageName + ".client.model"; + } else { + setPackageName("io.swagger"); + } + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); + } else { + setPackageVersion("1.0.0"); + } + + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); + + // modelPackage = invokerPackage + File.separatorChar + "client" + File.separatorChar + + // "model"; + // apiPackage = invokerPackage + File.separatorChar + "client" + File.separatorChar + "api"; + + final String invokerFolder = + (sourceFolder + File.separator + "src/" + invokerPackage + File.separator).replace( + ".", File.separator).replace('.', File.separatorChar); + + supportingFiles.add(new SupportingFile("ApiInvoker.as", invokerFolder + "common", + "ApiInvoker.as")); + supportingFiles.add(new SupportingFile("ApiUrlHelper.as", invokerFolder + "common", + "ApiUrlHelper.as")); + supportingFiles.add(new SupportingFile("ApiUserCredentials.as", invokerFolder + "common", + "ApiUserCredentials.as")); + supportingFiles.add(new SupportingFile("ListWrapper.as", invokerFolder + "common", + "ListWrapper.as")); + supportingFiles.add(new SupportingFile("SwaggerApi.as", invokerFolder + "common", + "SwaggerApi.as")); + supportingFiles.add(new SupportingFile("XMLWriter.as", invokerFolder + "common", + "XMLWriter.as")); + supportingFiles.add(new SupportingFile("ApiError.as", invokerFolder + "exception", + "ApiError.as")); + supportingFiles.add(new SupportingFile("ApiErrorCodes.as", invokerFolder + "exception", + "ApiErrorCodes.as")); + supportingFiles.add(new SupportingFile("ApiClientEvent.as", invokerFolder + "event", + "ApiClientEvent.as")); + supportingFiles.add(new SupportingFile("Response.as", invokerFolder + "event", + "Response.as")); + supportingFiles + .add(new SupportingFile("build.properties", sourceFolder, "build.properties")); + supportingFiles.add(new SupportingFile("build.xml", sourceFolder, "build.xml")); + supportingFiles.add(new SupportingFile("README.txt", sourceFolder, "README.txt")); + // supportingFiles.add(new SupportingFile("AirExecutorApp-app.xml", sourceFolder + + // File.separatorChar + // + "bin", "AirExecutorApp-app.xml")); + supportingFiles.add(new SupportingFile("ASAXB-0.1.1.swc", sourceFolder + File.separatorChar + + "lib", "ASAXB-0.1.1.swc")); + supportingFiles.add(new SupportingFile("as3corelib.swc", sourceFolder + File.separatorChar + + "lib", "as3corelib.swc")); + supportingFiles.add(new SupportingFile("flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc", + sourceFolder + File.separator + "lib" + File.separator + "ext", + "flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc")); + supportingFiles.add(new SupportingFile( + "flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc", sourceFolder + + File.separator + "lib" + File.separator + "ext", + "flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc")); + supportingFiles.add(new SupportingFile("flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc", + sourceFolder + File.separator + "lib" + File.separator + "ext", + "flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc")); + supportingFiles.add(new SupportingFile("flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc", + sourceFolder + File.separator + "lib" + File.separator + "ext", + "flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + } + + private static String dropDots(String str) { + return str.replaceAll("\\.", "_"); + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String getName() { + return "flash"; + } + + @Override + public String getHelp() { + return "Generates a Flash client library."; + } + + @Override + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; + } + + @Override + public String apiFileFolder() { + return (outputFolder + File.separatorChar + sourceFolder + File.separatorChar + "src/" + apiPackage() + .replace('.', File.separatorChar)).replace('/', File.separatorChar); + } + + @Override + public String modelFileFolder() { + return (outputFolder + File.separatorChar + sourceFolder + File.separatorChar + "src/" + modelPackage() + .replace('.', File.separatorChar)).replace('/', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty || p instanceof MapProperty) { + return getSwaggerType(p); + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return type; + } + } else { + type = toModelName(swaggerType); + } + return type; + } + + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + return "null"; + } else if (p instanceof BooleanProperty) { + return "false"; + } else if (p instanceof DateProperty) { + return "null"; + } else if (p instanceof DateTimeProperty) { + return "null"; + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "0.0"; + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "0.0"; + } else if (p instanceof IntegerProperty) { + IntegerProperty dp = (IntegerProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "0"; + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "0"; + } else if (p instanceof MapProperty) { + return "new Dictionary()"; + } else if (p instanceof ArrayProperty) { + return "new Array()"; + } else { + return "NaN"; + } + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare + // the methods parameters as 'final'. + + // if it's all uppper case, convert to lower case + if (name.matches("^[A-Z_]*$")) { + name = name.toLowerCase(); + } + + // underscore the variable name + // petId => pet_id + name = camelize(dropDots(name), true); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + if (!StringUtils.isEmpty(modelNamePrefix)) { + name = modelNamePrefix + "_" + name; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + name = name + "_" + modelNameSuffix; + } + + name = sanitizeName(name); + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + camelize("model_" + name)); + name = "model_" + name; // e.g. return => ModelReturn (after camelize) + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // leverage toModelName + return dropDots(toModelName(name)); + } + + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare + // the methods parameters as 'final'. + + // e.g. PhoneNumberApi.rb => phone_number_api.rb + return camelize(name) + "Api"; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + // e.g. phone_number_api => PhoneNumberApi + return camelize(name) + "Api"; + } + + @Override + public String toApiVarName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + return camelize(name) + "Api"; + } + + @Override + public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + underscore(sanitizeName("call_" + operationId))); + operationId = "call_" + operationId; + } + + return underscore(operationId); + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + + public void setInvokerPackage(String invokerPackage) { + this.invokerPackage = invokerPackage; + } + + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java index e99a6b29e38..4719b78f6a0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java @@ -27,7 +27,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf public static final String CONTROLLER_PACKAGE = "controllerPackage"; public static final String DEFAULT_CONTROLLER = "defaultController"; - public static final String SUPPORT_PYTHON2= "supportPython2"; + public static final String SUPPORT_PYTHON2 = "supportPython2"; protected int serverPort = 8080; protected String packageName; @@ -80,12 +80,10 @@ public FlaskConnexionCodegen() { embeddedTemplateDir = templateDir = "flaskConnexion"; // from https://docs.python.org/release/2.5.4/ref/keywords.html - setReservedWordsLowerCase( - Arrays.asList( - "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", - "assert", "else", "if", "pass", "yield", "break", "except", "import", - "print", "class", "exec", "in", "raise", "continue", "finally", "is", - "return", "def", "for", "lambda", "try")); + setReservedWordsLowerCase(Arrays.asList("and", "del", "from", "not", "while", "as", "elif", + "global", "or", "with", "assert", "else", "if", "pass", "yield", "break", "except", + "import", "print", "class", "exec", "in", "raise", "continue", "finally", "is", + "return", "def", "for", "lambda", "try")); /* * Additional Properties. These values can be passed to the templates and @@ -101,28 +99,28 @@ public FlaskConnexionCodegen() { supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py")); supportingFiles.add(new SupportingFile("tox.mustache", "", "tox.ini")); - supportingFiles.add(new SupportingFile("test-requirements.mustache", "", "test-requirements.txt")); + supportingFiles.add(new SupportingFile("test-requirements.mustache", "", + "test-requirements.txt")); supportingFiles.add(new SupportingFile("requirements.mustache", "", "requirements.txt")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml")); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case).") - .defaultValue("swagger_server")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, + "python package name (convention: snake_case).").defaultValue("swagger_server")); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "python package version.") .defaultValue("1.0.0")); - cliOptions.add(new CliOption(CONTROLLER_PACKAGE, "controller package"). - defaultValue("controllers")); - cliOptions.add(new CliOption(DEFAULT_CONTROLLER, "default controller"). - defaultValue("default_controller")); - cliOptions.add(new CliOption(SUPPORT_PYTHON2, "support python2"). - defaultValue("false")); + cliOptions.add(new CliOption(CONTROLLER_PACKAGE, "controller package") + .defaultValue("controllers")); + cliOptions.add(new CliOption(DEFAULT_CONTROLLER, "default controller") + .defaultValue("default_controller")); + cliOptions.add(new CliOption(SUPPORT_PYTHON2, "support python2").defaultValue("false")); } @Override public void processOpts() { super.processOpts(); - //apiTemplateFiles.clear(); + // apiTemplateFiles.clear(); if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); @@ -156,11 +154,16 @@ public void processOpts() { supportingFiles.add(new SupportingFile("__main__.mustache", packageName, "__main__.py")); supportingFiles.add(new SupportingFile("encoder.mustache", packageName, "encoder.py")); supportingFiles.add(new SupportingFile("util.mustache", packageName, "util.py")); - supportingFiles.add(new SupportingFile("__init__.mustache", packageName + File.separatorChar + controllerPackage, "__init__.py")); - supportingFiles.add(new SupportingFile("__init__model.mustache", packageName + File.separatorChar + modelPackage, "__init__.py")); - supportingFiles.add(new SupportingFile("base_model_.mustache", packageName + File.separatorChar + modelPackage, "base_model_.py")); - supportingFiles.add(new SupportingFile("__init__test.mustache", packageName + File.separatorChar + testPackage, "__init__.py")); - supportingFiles.add(new SupportingFile("swagger.mustache", packageName + File.separatorChar + "swagger", "swagger.yaml")); + supportingFiles.add(new SupportingFile("__init__.mustache", packageName + + File.separatorChar + controllerPackage, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__model.mustache", packageName + + File.separatorChar + modelPackage, "__init__.py")); + supportingFiles.add(new SupportingFile("base_model_.mustache", packageName + + File.separatorChar + modelPackage, "base_model_.py")); + supportingFiles.add(new SupportingFile("__init__test.mustache", packageName + + File.separatorChar + testPackage, "__init__.py")); + supportingFiles.add(new SupportingFile("swagger.mustache", packageName + File.separatorChar + + "swagger", "swagger.yaml")); modelPackage = packageName + "." + modelPackage; controllerPackage = packageName + "." + controllerPackage; @@ -189,8 +192,8 @@ public CodegenType getTag() { } /** - * Configures a friendly name for the generator. This will be used by the generator - * to select the library with the -l flag. + * Configures a friendly name for the generator. This will be used by the generator to select + * the library with the -l flag. * * @return the friendly name for the generator */ @@ -200,15 +203,15 @@ public String getName() { } /** - * Returns human-friendly help for the generator. Provide the consumer with help - * tips, parameters here + * Returns human-friendly help for the generator. Provide the consumer with help tips, + * parameters here * * @return A string value for the help message */ @Override public String getHelp() { - return "Generates a Python server library using the Connexion project. By default, " + - "it will also generate service classes -- which you can disable with the `-Dnoservice` environment variable."; + return "Generates a Python server library using the Connexion project. By default, " + + "it will also generate service classes -- which you can disable with the `-Dnoservice` environment variable."; } @Override @@ -230,21 +233,21 @@ public String toApiTestFilename(String name) { } /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping - * those terms here. This logic is only called if a variable matches the reseved words + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping those terms + * here. This logic is only called if a variable matches the reseved words * * @return the escaped term */ @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; // add an underscore to the name } - + /** - * Location to write api files. You can use the apiPackage() as defined when the class is + * Location to write api files. You can use the apiPackage() as defined when the class is * instantiated */ @Override @@ -286,34 +289,36 @@ public String getSwaggerType(Property p) { public void preprocessSwagger(Swagger swagger) { // need vendor extensions for x-swagger-router-controller Map paths = swagger.getPaths(); - if(paths != null) { - for(String pathname : paths.keySet()) { + if (paths != null) { + for (String pathname : paths.keySet()) { Path path = paths.get(pathname); Map operationMap = path.getOperationMap(); - if(operationMap != null) { - for(HttpMethod method : operationMap.keySet()) { + if (operationMap != null) { + for (HttpMethod method : operationMap.keySet()) { Operation operation = operationMap.get(method); String tag = "default"; - if(operation.getTags() != null && operation.getTags().size() > 0) { + if (operation.getTags() != null && operation.getTags().size() > 0) { tag = operation.getTags().get(0); } String operationId = operation.getOperationId(); - if(operationId == null) { - operationId = getOrGenerateOperationId(operation, pathname, method.toString()); + if (operationId == null) { + operationId = + getOrGenerateOperationId(operation, pathname, method.toString()); } operation.setOperationId(toOperationId(operationId)); - if(operation.getVendorExtensions().get("x-swagger-router-controller") == null) { - operation.getVendorExtensions().put( - "x-swagger-router-controller", - controllerPackage + "." + toApiFilename(tag) - ); + if (operation.getVendorExtensions().get("x-swagger-router-controller") == null) { + operation.getVendorExtensions().put("x-swagger-router-controller", + controllerPackage + "." + toApiFilename(tag)); } - for (Parameter param: operation.getParameters()) { - // sanitize the param name but don't underscore it since it's used for request mapping + for (Parameter param : operation.getParameters()) { + // sanitize the param name but don't underscore it since it's used for + // request mapping String name = param.getName(); String paramName = sanitizeName(name); if (!paramName.equals(name)) { - LOGGER.warn(name + " cannot be used as parameter name with flask-connexion and was sanitized as " + paramName); + LOGGER.warn(name + + " cannot be used as parameter name with flask-connexion and was sanitized as " + + paramName); } param.setName(paramName); } @@ -359,8 +364,8 @@ private static List> sortOperationsByPath(List postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { + Swagger swagger = (Swagger) objs.get("swagger"); + if (swagger != null) { try { objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); } catch (JsonProcessingException e) { @@ -380,7 +385,8 @@ public Map postProcessSupportingFileData(Map obj @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'. + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. // remove dollar sign name = name.replaceAll("$", ""); @@ -413,19 +419,23 @@ public String toParamName(String name) { @Override public String toModelFilename(String name) { - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. // remove dollar sign name = name.replaceAll("$", ""); // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + underscore(dropDots("model_" + name))); + LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + + underscore(dropDots("model_" + name))); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + underscore("model_" + name)); + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + underscore("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -444,19 +454,23 @@ public String toModelFilename(String name) { @Override public String toModelName(String name) { - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. // remove dollar sign name = name.replaceAll("$", ""); // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -475,12 +489,15 @@ public String toModelName(String name) { @Override public String toOperationId(String operationId) { - operationId = super.toOperationId(operationId); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + operationId = super.toOperationId(operationId); // FIXME: a parameter should not be + // assigned. Also declare the methods + // parameters as 'final'. // Use the part after the last dot, e.g. - // controllers.defaultController.addPet => addPet + // controllers.defaultController.addPet => addPet operationId = operationId.replaceAll(".*\\.", ""); - // Need to underscore it since it has been processed via removeNonNameElementToCamelCase, e.g. - // addPet => add_pet + // Need to underscore it since it has been processed via removeNonNameElementToCamelCase, + // e.g. + // addPet => add_pet return underscore(operationId); } @@ -555,28 +572,28 @@ public void setParameterExampleValue(CodegenParameter p) { } example = "'" + escapeText(example) + "'"; } else if ("Integer".equals(type) || "int".equals(type)) { - if(p.minimum != null) { + if (p.minimum != null) { example = "" + (Integer.valueOf(p.minimum) + 1); } - if(p.maximum != null) { + if (p.maximum != null) { example = "" + p.maximum; } else if (example == null) { example = "56"; } } else if ("Long".equalsIgnoreCase(type)) { - if(p.minimum != null) { + if (p.minimum != null) { example = "" + (Long.valueOf(p.minimum) + 1); } - if(p.maximum != null) { + if (p.maximum != null) { example = "" + p.maximum; } else if (example == null) { example = "789"; } } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) { - if(p.minimum != null) { + if (p.minimum != null) { example = "" + p.minimum; - } else if(p.maximum != null) { + } else if (p.maximum != null) { example = "" + p.maximum; } else if (example == null) { example = "3.4"; @@ -604,7 +621,7 @@ public void setParameterExampleValue(CodegenParameter p) { LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); } - if(p.items != null && p.items.defaultValue != null) { + if (p.items != null && p.items.defaultValue != null) { example = p.items.defaultValue; } if (example == null) { @@ -647,7 +664,7 @@ public String toModelImport(String name) { if (!"".equals(modelPackage())) { modelImport += modelPackage() + "."; } - modelImport += toModelFilename(name)+ " import " + name; + modelImport += toModelFilename(name) + " import " + name; return modelImport; } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java index dab49acd9ac..a91545566e8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -45,44 +45,25 @@ public GoClientCodegen() { embeddedTemplateDir = templateDir = "go"; - setReservedWordsLowerCase( - Arrays.asList( + setReservedWordsLowerCase(Arrays.asList( // data type - "string", "bool", "uint", "uint8", "uint16", "uint32", "uint64", - "int", "int8", "int16", "int32", "int64", "float32", "float64", - "complex64", "complex128", "rune", "byte", "uintptr", - - "break", "default", "func", "interface", "select", - "case", "defer", "go", "map", "struct", - "chan", "else", "goto", "package", "switch", - "const", "fallthrough", "if", "range", "type", - "continue", "for", "import", "return", "var", "error", "ApiResponse") - // Added "error" as it's used so frequently that it may as well be a keyword + "string", "bool", "uint", "uint8", "uint16", "uint32", "uint64", "int", "int8", + "int16", "int32", "int64", "float32", "float64", "complex64", "complex128", "rune", + "byte", "uintptr", + + "break", "default", "func", "interface", "select", "case", "defer", "go", "map", + "struct", "chan", "else", "goto", "package", "switch", "const", "fallthrough", + "if", "range", "type", "continue", "for", "import", "return", "var", "error", + "ApiResponse") + // Added "error" as it's used so frequently that it may as well be a keyword ); - defaultIncludes = new HashSet( - Arrays.asList( - "map", - "array") - ); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "string", - "bool", - "uint", - "uint32", - "uint64", - "int", - "int32", - "int64", - "float32", - "float64", - "complex64", - "complex128", - "rune", - "byte") - ); + defaultIncludes = new HashSet(Arrays.asList("map", "array")); + + languageSpecificPrimitives = + new HashSet(Arrays.asList("string", "bool", "uint", "uint32", "uint64", + "int", "int32", "int64", "float32", "float64", "complex64", "complex128", + "rune", "byte")); instantiationTypes.clear(); /*instantiationTypes.put("array", "GoArray"); @@ -114,12 +95,13 @@ public GoClientCodegen() { importMapping.put("os", "io/ioutil"); cliOptions.clear(); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Go package name (convention: lowercase).") - .defaultValue("swagger")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, + "Go package name (convention: lowercase).").defaultValue("swagger")); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Go package version.") .defaultValue("1.0.0")); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") - .defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + "hides the timestamp when files were generated").defaultValue(Boolean.TRUE + .toString())); } @@ -129,29 +111,30 @@ public void processOpts() { // default HIDE_GENERATION_TIMESTAMP to true if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.TRUE.toString()); + } else { + additionalProperties.put( + CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get( + CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); - } - else { + } else { setPackageName("swagger"); } if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); - } - else { + } else { setPackageVersion("1.0.0"); } additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); - + additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); @@ -168,8 +151,7 @@ public void processOpts() { } @Override - public String escapeReservedWord(String name) - { + public String escapeReservedWord(String name) { // Can't start with an underscore, as our fields need to start with an // UppercaseLetter so that Go treats them as public/visible. @@ -180,10 +162,10 @@ public String escapeReservedWord(String name) // - XName // - X_Name // ... or maybe a suffix? - // - Name_ ... think this will work. - if(this.reservedWordsMappings().containsKey(name)) { + // - Name_ ... think this will work. + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); - } + } return camelize(name) + '_'; } @@ -252,13 +234,16 @@ public String toModelFilename(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + ("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + ("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + ("model_" + name)); + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + ("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -268,7 +253,8 @@ public String toModelFilename(String name) { @Override public String toApiFilename(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare + // the methods parameters as 'final'. // e.g. PetApi.go => pet_api.go return underscore(name) + "_api"; @@ -277,14 +263,14 @@ public String toApiFilename(String name) { /** - * Overrides postProcessParameter to add a vendor extension "x-exportParamName". - * This is useful when paramName starts with a lowercase letter, but we need that - * param to be exportable (starts with an Uppercase letter). + * Overrides postProcessParameter to add a vendor extension "x-exportParamName". This is useful + * when paramName starts with a lowercase letter, but we need that param to be exportable + * (starts with an Uppercase letter). * * @param parameter CodegenParameter object to be processed. */ @Override - public void postProcessParameter(CodegenParameter parameter){ + public void postProcessParameter(CodegenParameter parameter) { // Give the base class a chance to process super.postProcessParameter(parameter); @@ -326,18 +312,17 @@ public String toApiDocFilename(String name) { @Override public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { + if (p instanceof ArrayProperty) { ArrayProperty ap = (ArrayProperty) p; Property inner = ap.getItems(); return "[]" + getTypeDeclaration(inner); - } - else if (p instanceof MapProperty) { + } else if (p instanceof MapProperty) { MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); return getSwaggerType(p) + "[string]" + getTypeDeclaration(inner); } - //return super.getTypeDeclaration(p); + // return super.getTypeDeclaration(p); // Not using the supertype invocation, because we want to UpperCamelize // the type. @@ -346,11 +331,11 @@ else if (p instanceof MapProperty) { return typeMapping.get(swaggerType); } - if(typeMapping.containsValue(swaggerType)) { + if (typeMapping.containsValue(swaggerType)) { return swaggerType; } - if(languageSpecificPrimitives.contains(swaggerType)) { + if (languageSpecificPrimitives.contains(swaggerType)) { return swaggerType; } @@ -361,12 +346,11 @@ else if (p instanceof MapProperty) { public String getSwaggerType(Property p) { String swaggerType = super.getSwaggerType(p); String type = null; - if(typeMapping.containsKey(swaggerType)) { + if (typeMapping.containsKey(swaggerType)) { type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) + if (languageSpecificPrimitives.contains(type)) return (type); - } - else + } else type = swaggerType; return type; } @@ -377,7 +361,8 @@ public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(sanitizedOperationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize("call_" + operationId)); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + camelize("call_" + operationId)); sanitizedOperationId = "call_" + sanitizedOperationId; } @@ -408,23 +393,24 @@ public Map postProcessOperations(Map objs) { } // if the return type is not primitive, import encoding/json for (CodegenOperation operation : operations) { - if(operation.returnBaseType != null && needToImport(operation.returnBaseType)) { + if (operation.returnBaseType != null && needToImport(operation.returnBaseType)) { imports.add(createMapping("import", "encoding/json")); - break; //just need to import once + break; // just need to import once } } // this will only import "fmt" if there are items in pathParams for (CodegenOperation operation : operations) { - if(operation.pathParams != null && operation.pathParams.size() > 0) { + if (operation.pathParams != null && operation.pathParams.size() > 0) { imports.add(createMapping("import", "fmt")); - break; //just need to import once + break; // just need to import once } } // recursively add import for mapping one type to multiple imports - List> recursiveImports = (List>) objs.get("imports"); + List> recursiveImports = + (List>) objs.get("imports"); if (recursiveImports == null) return objs; @@ -454,7 +440,8 @@ public Map postProcessModels(Map objs) { } // recursively add import for mapping one type to multiple imports - List> recursiveImports = (List>) objs.get("imports"); + List> recursiveImports = + (List>) objs.get("imports"); if (recursiveImports == null) return objs; @@ -473,8 +460,7 @@ public Map postProcessModels(Map objs) { @Override protected boolean needToImport(String type) { - return !defaultIncludes.contains(type) - && !languageSpecificPrimitives.contains(type); + return !defaultIncludes.contains(type) && !languageSpecificPrimitives.contains(type); } public void setPackageName(String packageName) { @@ -496,7 +482,7 @@ public String escapeUnsafeCharacters(String input) { return input.replace("*/", "*_/").replace("/*", "/_*"); } - public Map createMapping(String key, String value){ + public Map createMapping(String key, String value) { Map customImport = new HashMap(); customImport.put(key, value); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java index b7d2b00967a..b182ba7e937 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java @@ -29,7 +29,7 @@ public class GoServerCodegen extends DefaultCodegen implements CodegenConfig { protected int serverPort = 8080; protected String projectName = "swagger-server"; protected String apiPath = "go"; - + public GoServerCodegen() { super(); @@ -49,9 +49,8 @@ public GoServerCodegen() { * as with models, add multiple entries with different extensions for multiple files per * class */ - apiTemplateFiles.put( - "controller.mustache", // the template to use - ".go"); // the extension for each file to write + apiTemplateFiles.put("controller.mustache", // the template to use + ".go"); // the extension for each file to write /* * Template Location. This is the location which templates will be read from. The generator @@ -62,39 +61,19 @@ public GoServerCodegen() { /* * Reserved words. Override this with reserved words specific to your language */ - setReservedWordsLowerCase( - Arrays.asList( - "break", "default", "func", "interface", "select", - "case", "defer", "go", "map", "struct", - "chan", "else", "goto", "package", "switch", - "const", "fallthrough", "if", "range", "type", - "continue", "for", "import", "return", "var", "error", "ApiResponse") - // Added "error" as it's used so frequently that it may as well be a keyword + setReservedWordsLowerCase(Arrays.asList("break", "default", "func", "interface", "select", + "case", "defer", "go", "map", "struct", "chan", "else", "goto", "package", + "switch", "const", "fallthrough", "if", "range", "type", "continue", "for", + "import", "return", "var", "error", "ApiResponse") + // Added "error" as it's used so frequently that it may as well be a keyword ); - defaultIncludes = new HashSet( - Arrays.asList( - "map", - "array") - ); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "string", - "bool", - "uint", - "uint32", - "uint64", - "int", - "int32", - "int64", - "float32", - "float64", - "complex64", - "complex128", - "rune", - "byte") - ); + defaultIncludes = new HashSet(Arrays.asList("map", "array")); + + languageSpecificPrimitives = + new HashSet(Arrays.asList("string", "bool", "uint", "uint32", "uint64", + "int", "int32", "int64", "float32", "float64", "complex64", "complex128", + "rune", "byte")); instantiationTypes.clear(); /*instantiationTypes.put("array", "GoArray"); @@ -124,8 +103,8 @@ public GoServerCodegen() { importMapping.put("os", "io/ioutil"); cliOptions.clear(); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Go package name (convention: lowercase).") - .defaultValue("swagger")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, + "Go package name (convention: lowercase).").defaultValue("swagger")); /* * Additional Properties. These values can be passed to the templates and * are available in models, apis, and supporting files @@ -138,14 +117,11 @@ public GoServerCodegen() { * entire object tree available. If the input file has a suffix of `.mustache * it will be processed by the template engine. Otherwise, it will be copied */ - supportingFiles.add(new SupportingFile("swagger.mustache", - "api", - "swagger.yaml") - ); + supportingFiles.add(new SupportingFile("swagger.mustache", "api", "swagger.yaml")); supportingFiles.add(new SupportingFile("main.mustache", "", "main.go")); supportingFiles.add(new SupportingFile("routers.mustache", apiPath, "routers.go")); - supportingFiles.add(new SupportingFile("logger.mustache", apiPath, "logger.go")); - supportingFiles.add(new SupportingFile("app.mustache", apiPath, "app.yaml")); + supportingFiles.add(new SupportingFile("logger.mustache", apiPath, "logger.go")); + supportingFiles.add(new SupportingFile("app.mustache", apiPath, "app.yaml")); writeOptional(outputFolder, new SupportingFile("README.mustache", apiPath, "README.md")); } @@ -166,8 +142,8 @@ public CodegenType getTag() { } /** - * Configures a friendly name for the generator. This will be used by the generator - * to select the library with the -l flag. + * Configures a friendly name for the generator. This will be used by the generator to select + * the library with the -l flag. * * @return the friendly name for the generator */ @@ -177,15 +153,15 @@ public String getName() { } /** - * Returns human-friendly help for the generator. Provide the consumer with help - * tips, parameters here + * Returns human-friendly help for the generator. Provide the consumer with help tips, + * parameters here * * @return A string value for the help message */ @Override public String getHelp() { - return "Generates a Go server library using the swagger-tools project. By default, " + - "it will also generate service classes--which you can disable with the `-Dnoservice` environment variable."; + return "Generates a Go server library using the swagger-tools project. By default, " + + "it will also generate service classes--which you can disable with the `-Dnoservice` environment variable."; } @Override @@ -197,21 +173,21 @@ public String toApiName(String name) { } /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping - * those terms here. This logic is only called if a variable matches the reseved words + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping those terms + * here. This logic is only called if a variable matches the reseved words * * @return the escaped term */ @Override public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); - } - return "_" + name; // add an underscore to the name + } + return "_" + name; // add an underscore to the name } /** - * Location to write api files. You can use the apiPackage() as defined when the class is + * Location to write api files. You can use the apiPackage() as defined when the class is * instantiated */ @Override @@ -230,7 +206,8 @@ public String toModelName(String name) { public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } @@ -251,7 +228,8 @@ public String toModelFilename(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } @@ -261,7 +239,8 @@ public String toModelFilename(String name) { @Override public String toApiFilename(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare + // the methods parameters as 'final'. // e.g. PetApi.go => pet_api.go return underscore(name); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java index 033dceeb669..7b53376d567 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java @@ -25,16 +25,16 @@ public GroovyClientCodegen() { // clear model and api doc template as this codegen // does not support auto-generated markdown doc at the moment - //TODO: add doc templates + // TODO: add doc templates modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); - + apiPackage = "io.swagger.api"; modelPackage = "io.swagger.model"; configPackage = "io.swagger.configuration"; invokerPackage = "io.swagger.api"; artifactId = "swagger-groovy"; - dateLibrary = "legacy"; //TODO: add joda support to groovy + dateLibrary = "legacy"; // TODO: add joda support to groovy additionalProperties.put("title", title); additionalProperties.put(CONFIG_PACKAGE, configPackage); @@ -68,9 +68,10 @@ public void processOpts() { supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); // TODO readme to be added later - //supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + // supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("ApiUtils.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiUtils.groovy")); + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), + "ApiUtils.groovy")); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java index 96a8a7bb926..afbc62c6348 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java @@ -27,8 +27,8 @@ public CodegenType getTag() { } /** - * Configures a friendly name for the generator. This will be used by the generator - * to select the library with the -l flag. + * Configures a friendly name for the generator. This will be used by the generator to select + * the library with the -l flag. * * @return the friendly name for the generator */ @@ -37,8 +37,8 @@ public String getName() { } /** - * Returns human-friendly help for the generator. Provide the consumer with help - * tips, parameters here + * Returns human-friendly help for the generator. Provide the consumer with help tips, + * parameters here * * @return A string value for the help message */ @@ -57,71 +57,53 @@ public HaskellServantCodegen() { // set the output folder here outputFolder = "generated-code/haskell-servant"; - /* - * Template Location. This is the location which templates will be read from. The generator - * will use the resource stream to attempt to read the templates. - */ + /* + * Template Location. This is the location which templates will be read from. The generator + * will use the resource stream to attempt to read the templates. + */ embeddedTemplateDir = templateDir = "haskell-servant"; - /* - * Api Package. Optional, if needed, this can be used in templates - */ + /* + * Api Package. Optional, if needed, this can be used in templates + */ apiPackage = "API"; - /* - * Model Package. Optional, if needed, this can be used in templates - */ + /* + * Model Package. Optional, if needed, this can be used in templates + */ modelPackage = "Types"; - // Haskell keywords and reserved function names, taken mostly from https://wiki.haskell.org/Keywords - setReservedWordsLowerCase( - Arrays.asList( - // Keywords - "as", "case", "of", - "class", "data", "family", - "default", "deriving", - "do", "forall", "foreign", "hiding", - "if", "then", "else", - "import", "infix", "infixl", "infixr", - "instance", "let", "in", - "mdo", "module", "newtype", - "proc", "qualified", "rec", - "type", "where" - ) - ); - - /* - * Additional Properties. These values can be passed to the templates and - * are available in models, apis, and supporting files - */ + // Haskell keywords and reserved function names, taken mostly from + // https://wiki.haskell.org/Keywords + setReservedWordsLowerCase(Arrays.asList( + // Keywords + "as", "case", "of", "class", "data", "family", "default", "deriving", "do", + "forall", "foreign", "hiding", "if", "then", "else", "import", "infix", "infixl", + "infixr", "instance", "let", "in", "mdo", "module", "newtype", "proc", "qualified", + "rec", "type", "where")); + + /* + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ additionalProperties.put("apiVersion", apiVersion); - /* - * Supporting Files. You can write single files for the generator with the - * entire object tree available. If the input file has a suffix of `.mustache - * it will be processed by the template engine. Otherwise, it will be copied - */ + /* + * Supporting Files. You can write single files for the generator with the + * entire object tree available. If the input file has a suffix of `.mustache + * it will be processed by the template engine. Otherwise, it will be copied + */ supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("stack.mustache", "", "stack.yaml")); supportingFiles.add(new SupportingFile("Setup.mustache", "", "Setup.hs")); - /* - * Language Specific Primitives. These types will not trigger imports by - * the client generator - */ - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "Bool", - "String", - "Int", - "Integer", - "Float", - "Char", - "Double", - "List", - "FilePath" - ) - ); + /* + * Language Specific Primitives. These types will not trigger imports by + * the client generator + */ + languageSpecificPrimitives = + new HashSet(Arrays.asList("Bool", "String", "Int", "Integer", "Float", + "Char", "Double", "List", "FilePath")); typeMapping.clear(); typeMapping.put("array", "List"); @@ -143,19 +125,21 @@ public HaskellServantCodegen() { importMapping.clear(); importMapping.put("Map", "qualified Data.Map as Map"); - 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.MODEL_PACKAGE, + CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, + CodegenConstants.API_PACKAGE_DESC)); } /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping - * those terms here. This logic is only called if a variable matches the reseved words + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping those terms + * here. This logic is only called if a variable matches the reseved words * * @return the escaped term */ @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -187,7 +171,7 @@ public void preprocessSwagger(Swagger swagger) { String title = swagger.getInfo().getTitle(); // Drop any API suffix - if(title == null) { + if (title == null) { title = "Swagger"; } else { title = title.trim(); @@ -198,7 +182,8 @@ public void preprocessSwagger(Swagger swagger) { String[] words = title.split(" "); - // The package name is made by appending the lowercased words of the title interspersed with dashes + // The package name is made by appending the lowercased words of the title interspersed with + // dashes List wordsLower = new ArrayList(); for (String word : words) { wordsLower.add(word.toLowerCase()); @@ -213,7 +198,8 @@ public void preprocessSwagger(Swagger swagger) { String apiName = joinStrings("", wordsCaps); // Set the filenames to write for the API - supportingFiles.add(new SupportingFile("haskell-servant-codegen.mustache", "", cabalName + ".cabal")); + supportingFiles.add(new SupportingFile("haskell-servant-codegen.mustache", "", cabalName + + ".cabal")); supportingFiles.add(new SupportingFile("API.mustache", "lib/" + apiName, "API.hs")); supportingFiles.add(new SupportingFile("Types.mustache", "lib/" + apiName, "Types.hs")); @@ -227,7 +213,7 @@ public void preprocessSwagger(Swagger swagger) { List> replacements = new ArrayList<>(); Object[] replacementChars = specialCharReplacements.keySet().toArray(); - for(int i = 0; i < replacementChars.length; i++) { + for (int i = 0; i < replacementChars.length; i++) { String c = (String) replacementChars[i]; Map o = new HashMap<>(); o.put("char", c); @@ -242,10 +228,11 @@ public void preprocessSwagger(Swagger swagger) { /** - * Optional - type declaration. This is a String which is used by the templates to instantiate your - * types. There is typically special handling for different property types + * Optional - type declaration. This is a String which is used by the templates to instantiate + * your types. There is typically special handling for different property types * - * @return a string value used as the `dataType` field for model templates, `returnType` for api templates + * @return a string value used as the `dataType` field for model templates, `returnType` for api + * templates */ @Override public String getTypeDeclaration(Property p) { @@ -262,8 +249,9 @@ public String getTypeDeclaration(Property p) { } /** - * Optional - swagger type conversion. This is used to map swagger types in a `Property` into - * either language specific types via `typeMapping` or into complex models if there is not a mapping. + * Optional - swagger type conversion. This is used to map swagger types in a `Property` into + * either language specific types via `typeMapping` or into complex models if there is not a + * mapping. * * @return a string value of the type or complex model for this property * @see io.swagger.models.properties.Property @@ -276,9 +264,9 @@ public String getSwaggerType(Property p) { type = typeMapping.get(swaggerType); if (languageSpecificPrimitives.contains(type)) return toModelName(type); - } else if(swaggerType == "object") { + } else if (swaggerType == "object") { type = "Value"; - } else if(typeMapping.containsValue(swaggerType)) { + } else if (typeMapping.containsValue(swaggerType)) { type = swaggerType + "_"; } else { type = swaggerType; @@ -293,7 +281,8 @@ public String toInstantiationType(Property p) { Property additionalProperties2 = ap.getAdditionalProperties(); String type = additionalProperties2.getType(); if (null == type) { - LOGGER.error("No Type defined for Additional Property " + additionalProperties2 + "\n" // + LOGGER.error("No Type defined for Additional Property " + additionalProperties2 + + "\n" // + "\tIn Property: " + p); } String inner = getSwaggerType(additionalProperties2); @@ -324,7 +313,7 @@ private String joinStrings(String sep, List ss) { // Convert an HTTP path to a Servant route, including captured parameters. // For example, the path /api/jobs/info/{id}/last would become: - // "api" :> "jobs" :> "info" :> Capture "id" IdType :> "last" + // "api" :> "jobs" :> "info" :> Capture "id" IdType :> "last" // IdType is provided by the capture params. private List pathToServantRoute(String path, List pathParams) { // Map the capture params by their names. @@ -380,8 +369,10 @@ private List pathToClientType(String path, List pathPa @Override - public CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(resourcePath, httpMethod, operation, definitions, swagger); + public CodegenOperation fromOperation(String resourcePath, String httpMethod, + Operation operation, Map definitions, Swagger swagger) { + CodegenOperation op = + super.fromOperation(resourcePath, httpMethod, operation, definitions, swagger); List path = pathToServantRoute(op.path, op.pathParams); List type = pathToClientType(op.path, op.pathParams); @@ -405,13 +396,13 @@ public CodegenOperation fromOperation(String resourcePath, String httpMethod, Op path.add("ReqBody '[JSON] " + param.dataType); bodyType = param.dataType; } - } else if(op.getHasFormParams()) { + } else if (op.getHasFormParams()) { // Use the FormX data type, where X is the conglomerate of all things being passed String formName = "Form" + camelize(op.operationId); bodyType = formName; path.add("ReqBody '[FormUrlEncoded] " + formName); } - if(bodyType != null) { + if (bodyType != null) { type.add(bodyType); } @@ -440,7 +431,7 @@ public CodegenOperation fromOperation(String resourcePath, String httpMethod, Op op.vendorExtensions.put("x-routeType", joinStrings(" :> ", path)); op.vendorExtensions.put("x-clientType", joinStrings(" -> ", type)); op.vendorExtensions.put("x-formName", "Form" + camelize(op.operationId)); - for(CodegenParameter param : op.formParams) { + for (CodegenParameter param : op.formParams) { param.vendorExtensions.put("x-formPrefix", camelize(op.operationId, true)); } return op; @@ -448,12 +439,17 @@ public CodegenOperation fromOperation(String resourcePath, String httpMethod, Op private String makeQueryListType(String type, String collectionFormat) { type = type.substring(1, type.length() - 1); - switch(collectionFormat) { - case "csv": return "(QueryList 'CommaSeparated (" + type + "))"; - case "tsv": return "(QueryList 'TabSeparated (" + type + "))"; - case "ssv": return "(QueryList 'SpaceSeparated (" + type + "))"; - case "pipes": return "(QueryList 'PipeSeparated (" + type + "))"; - case "multi": return "(QueryList 'MultiParamArray (" + type + "))"; + switch (collectionFormat) { + case "csv": + return "(QueryList 'CommaSeparated (" + type + "))"; + case "tsv": + return "(QueryList 'TabSeparated (" + type + "))"; + case "ssv": + return "(QueryList 'SpaceSeparated (" + type + "))"; + case "pipes": + return "(QueryList 'PipeSeparated (" + type + "))"; + case "multi": + return "(QueryList 'MultiParamArray (" + type + "))"; default: throw new UnsupportedOperationException(); } @@ -484,30 +480,31 @@ public CodegenModel fromModel(String name, Model mod, Map allDefi // Clean up the class name to remove invalid characters model.classname = fixModelChars(model.classname); - if(typeMapping.containsValue(model.classname)) { + if (typeMapping.containsValue(model.classname)) { model.classname += "_"; } // From the model name, compute the prefix for the fields. String prefix = camelize(model.classname, true); - for(CodegenProperty prop : model.vars) { + for (CodegenProperty prop : model.vars) { prop.name = prefix + camelize(fixOperatorChars(prop.name)); } // Create newtypes for things with non-object types String dataOrNewtype = "data"; - // check if it's a ModelImpl before casting + // check if it's a ModelImpl before casting if (!(mod instanceof ModelImpl)) { return model; } - String modelType = ((ModelImpl) mod).getType(); - if(modelType != "object" && typeMapping.containsKey(modelType)) { + String modelType = ((ModelImpl) mod).getType(); + if (modelType != "object" && typeMapping.containsKey(modelType)) { String newtype = typeMapping.get(modelType); model.vendorExtensions.put("x-customNewtype", newtype); } - // Provide the prefix as a vendor extension, so that it can be used in the ToJSON and FromJSON instances. + // Provide the prefix as a vendor extension, so that it can be used in the ToJSON and + // FromJSON instances. model.vendorExtensions.put("x-prefix", prefix); model.vendorExtensions.put("x-data", dataOrNewtype); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java index 6ebfbea6f17..fdea5a40361 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java @@ -10,192 +10,191 @@ public class JMeterCodegen extends DefaultCodegen implements CodegenConfig { - // source folder where to write the files - protected String sourceFolder = ""; - protected String apiVersion = "1.0.0"; - - /** - * Configures the type of generator. - * - * @return the CodegenType for this generator - * @see io.swagger.codegen.CodegenType - */ - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - /** - * Configures a friendly name for the generator. This will be used by the generator - * to select the library with the -l flag. - * - * @return the friendly name for the generator - */ - @Override - public String getName() { - return "jmeter"; - } - - /** - * Returns human-friendly help for the generator. Provide the consumer with help - * tips, parameters here - * - * @return A string value for the help message - */ - @Override - public String getHelp() { - return "Generates a JMeter .jmx file."; - } - - public JMeterCodegen() { - super(); - - // set the output folder here - outputFolder = "generated-code/JMeterCodegen"; - - /* - * Api classes. You can write classes for each Api file with the apiTemplateFiles map. - * as with models, add multiple entries with different extensions for multiple files per - * class + // source folder where to write the files + protected String sourceFolder = ""; + protected String apiVersion = "1.0.0"; + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType */ - apiTemplateFiles.put( - "api.mustache", // the template to use - ".jmx"); // the extension for each file to write - - apiTemplateFiles.put("testdata-localhost.mustache", ".csv"); + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } - /* - * Template Location. This is the location which templates will be read from. The generator - * will use the resource stream to attempt to read the templates. + /** + * Configures a friendly name for the generator. This will be used by the generator to select + * the library with the -l flag. + * + * @return the friendly name for the generator */ - embeddedTemplateDir = templateDir = "JMeter"; + @Override + public String getName() { + return "jmeter"; + } - /* - * Api Package. Optional, if needed, this can be used in templates + /** + * Returns human-friendly help for the generator. Provide the consumer with help tips, + * parameters here + * + * @return A string value for the help message */ - apiPackage = ""; + @Override + public String getHelp() { + return "Generates a JMeter .jmx file."; + } - /* - * Model Package. Optional, if needed, this can be used in templates - */ - modelPackage = ""; + public JMeterCodegen() { + super(); + + // set the output folder here + outputFolder = "generated-code/JMeterCodegen"; + + /* + * Api classes. You can write classes for each Api file with the apiTemplateFiles map. + * as with models, add multiple entries with different extensions for multiple files per + * class + */ + apiTemplateFiles.put("api.mustache", // the template to use + ".jmx"); // the extension for each file to write + + apiTemplateFiles.put("testdata-localhost.mustache", ".csv"); + + /* + * Template Location. This is the location which templates will be read from. The generator + * will use the resource stream to attempt to read the templates. + */ + embeddedTemplateDir = templateDir = "JMeter"; + + /* + * Api Package. Optional, if needed, this can be used in templates + */ + apiPackage = ""; + + /* + * Model Package. Optional, if needed, this can be used in templates + */ + modelPackage = ""; + + /* + * Reserved words. Override this with reserved words specific to your language + */ + reservedWords = new HashSet(Arrays.asList("sample1", // replace with static values + "sample2")); + + /* + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("apiVersion", apiVersion); + + // supportingFiles.add(new SupportingFile("testdata-localhost.mustache", "input", + // "testdata-localhost.csv")); + } - /* - * Reserved words. Override this with reserved words specific to your language - */ - reservedWords = new HashSet ( - Arrays.asList( - "sample1", // replace with static values - "sample2") - ); - - /* - * Additional Properties. These values can be passed to the templates and - * are available in models, apis, and supporting files - */ - additionalProperties.put("apiVersion", apiVersion); - -// supportingFiles.add(new SupportingFile("testdata-localhost.mustache", "input", "testdata-localhost.csv")); - } - - @Override - public void preprocessSwagger(Swagger swagger) { - if (swagger != null && swagger.getPaths() != null) { - for (String pathname : swagger.getPaths().keySet()) { - Path path = swagger.getPath(pathname); - if (path.getOperations() != null) { - for (Operation operation : path.getOperations()) { - String pathWithDollars = pathname.replaceAll("\\{", "\\$\\{"); - operation.setVendorExtension("x-path", pathWithDollars); - } + @Override + public void preprocessSwagger(Swagger swagger) { + if (swagger != null && swagger.getPaths() != null) { + for (String pathname : swagger.getPaths().keySet()) { + Path path = swagger.getPath(pathname); + if (path.getOperations() != null) { + for (Operation operation : path.getOperations()) { + String pathWithDollars = pathname.replaceAll("\\{", "\\$\\{"); + operation.setVendorExtension("x-path", pathWithDollars); + } + } + } } - } } - } - - /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping - * those terms here. This logic is only called if a variable matches the reseved words - * - * @return the escaped term - */ + + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping those terms + * here. This logic is only called if a variable matches the reseved words + * + * @return the escaped term + */ @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; } - /** - * Location to write model files. You can use the modelPackage() as defined when the class is - * instantiated - */ - @Override - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - /** - * Location to write api files. You can use the apiPackage() as defined when the class is - * instantiated - */ - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - /** - * Optional - type declaration. This is a String which is used by the templates to instantiate your - * types. There is typically special handling for different property types - * - * @return a string value used as the `dataType` field for model templates, `returnType` for api templates - */ - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + /** + * Location to write model files. You can use the modelPackage() as defined when the class is + * instantiated + */ + @Override + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + + modelPackage().replace('.', File.separatorChar); } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + + /** + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated + */ + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + + apiPackage().replace('.', File.separatorChar); + } + + /** + * Optional - type declaration. This is a String which is used by the templates to instantiate + * your types. There is typically special handling for different property types + * + * @return a string value used as the `dataType` field for model templates, `returnType` for api + * templates + */ + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); } - return super.getTypeDeclaration(p); - } - - /** - * Optional - swagger type conversion. This is used to map swagger types in a `Property` into - * either language specific types via `typeMapping` or into complex models if there is not a mapping. - * - * @return a string value of the type or complex model for this property - * @see io.swagger.models.properties.Property - */ - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) + + /** + * Optional - swagger type conversion. This is used to map swagger types in a `Property` into + * either language specific types via `typeMapping` or into complex models if there is not a + * mapping. + * + * @return a string value of the type or complex model for this property + * @see io.swagger.models.properties.Property + */ + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) + return toModelName(type); + } else + type = swaggerType; return toModelName(type); } - else - type = swaggerType; - return toModelName(type); - } - - @Override - public String escapeQuotationMark(String input) { - // remove ' to avoid code injection - return input.replace("'", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } + + @Override + public String escapeQuotationMark(String input) { + // remove ' to avoid code injection + return input.replace("'", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFClientCodegen.java index d1c9d41ae31..95904d76578 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFClientCodegen.java @@ -1,4 +1,3 @@ - package io.swagger.codegen.languages; import java.io.File; @@ -20,50 +19,51 @@ import io.swagger.codegen.languages.features.LoggingTestFeatures; import io.swagger.models.Operation; -public class JavaCXFClientCodegen extends AbstractJavaCodegen - implements BeanValidationFeatures, JaxbFeatures, GzipTestFeatures, LoggingTestFeatures -{ +public class JavaCXFClientCodegen extends AbstractJavaCodegen implements BeanValidationFeatures, + JaxbFeatures, GzipTestFeatures, LoggingTestFeatures { private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFClientCodegen.class); - + /** - * Name of the sub-directory in "src/main/resource" where to find the - * Mustache template for the JAX-RS Codegen. + * Name of the sub-directory in "src/main/resource" where to find the Mustache template for the + * JAX-RS Codegen. */ protected static final String JAXRS_TEMPLATE_DIRECTORY_NAME = "JavaJaxRS"; - + protected boolean useJaxbAnnotations = true; protected boolean useBeanValidation = false; - + protected boolean useGzipFeatureForTests = false; - + protected boolean useLoggingFeatureForTests = false; - - public JavaCXFClientCodegen() - { + + public JavaCXFClientCodegen() { super(); supportsInheritance = true; - + sourceFolder = "src/gen/java"; invokerPackage = "io.swagger.api"; artifactId = "swagger-jaxrs-client"; - dateLibrary = "legacy"; //TODO: add joda support to all jax-rs + dateLibrary = "legacy"; // TODO: add joda support to all jax-rs apiPackage = "io.swagger.api"; modelPackage = "io.swagger.model"; - + outputFolder = "generated-code/JavaJaxRS-CXF"; - + // clear model and api doc template as this codegen // does not support auto-generated markdown doc at the moment - //TODO: add doc templates + // TODO: add doc templates modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); typeMapping.put("date", "LocalDate"); - typeMapping.put("DateTime", "javax.xml.datatype.XMLGregorianCalendar"); // Map DateTime fields to Java standart class 'XMLGregorianCalendar' + typeMapping.put("DateTime", "javax.xml.datatype.XMLGregorianCalendar"); // Map DateTime + // fields to Java + // standart class + // 'XMLGregorianCalendar' importMapping.put("LocalDate", "org.joda.time.LocalDate"); @@ -71,59 +71,62 @@ public JavaCXFClientCodegen() cliOptions.add(CliOption.newBoolean(USE_JAXB_ANNOTATIONS, "Use JAXB annotations for XML")); - cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); - - cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE_FOR_TESTS, "Use Gzip Feature for tests")); - cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE_FOR_TESTS, "Use Logging Feature for tests")); - - + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, + "Use BeanValidation API annotations")); + + cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE_FOR_TESTS, + "Use Gzip Feature for tests")); + cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE_FOR_TESTS, + "Use Logging Feature for tests")); + + } @Override - public void processOpts() - { + public void processOpts() { super.processOpts(); - + if (additionalProperties.containsKey(USE_JAXB_ANNOTATIONS)) { - boolean useJaxbAnnotationsProp = convertPropertyToBooleanAndWriteBack(USE_JAXB_ANNOTATIONS); + boolean useJaxbAnnotationsProp = + convertPropertyToBooleanAndWriteBack(USE_JAXB_ANNOTATIONS); this.setUseJaxbAnnotations(useJaxbAnnotationsProp); } if (additionalProperties.containsKey(USE_BEANVALIDATION)) { - boolean useBeanValidationProp = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION); + boolean useBeanValidationProp = + convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION); this.setUseBeanValidation(useBeanValidationProp); } - + this.setUseGzipFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE_FOR_TESTS)); this.setUseLoggingFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE_FOR_TESTS)); - - + + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen - + writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); - + } @Override - public String getName() - { + public String getName() { return "jaxrs-cxf-client"; } @Override - public CodegenType getTag() - { + public CodegenType getTag() { return CodegenType.CLIENT; } - + @Override - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { - super.addOperationToGroup(tag, resourcePath, operation, co, operations); + public void addOperationToGroup(String tag, String resourcePath, Operation operation, + CodegenOperation co, Map> operations) { + super.addOperationToGroup(tag, resourcePath, operation, co, operations); co.subresourceOperation = !co.path.isEmpty(); } - + @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); @@ -132,17 +135,16 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert model.imports.remove("JsonSerialize"); model.imports.remove("ToStringSerializer"); } - + @Override - public String getHelp() - { + public String getHelp() { return "Generates a Java JAXRS Client based on Apache CXF framework."; } - + public void setUseBeanValidation(boolean useBeanValidation) { this.useBeanValidation = useBeanValidation; } - + public void setUseJaxbAnnotations(boolean useJaxbAnnotations) { this.useJaxbAnnotations = useJaxbAnnotations; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index 720cbc49331..ee72d2da0e6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -1,4 +1,3 @@ - package io.swagger.codegen.languages; import java.io.File; @@ -19,31 +18,30 @@ import io.swagger.codegen.languages.features.LoggingTestFeatures; import io.swagger.models.Operation; -public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen - implements CXFServerFeatures, GzipTestFeatures, LoggingTestFeatures, JaxbFeatures -{ +public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen implements + CXFServerFeatures, GzipTestFeatures, LoggingTestFeatures, JaxbFeatures { private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFServerCodegen.class); - + protected boolean addConsumesProducesJson = true; protected boolean useJaxbAnnotations = true; - + protected boolean generateSpringApplication = false; - + protected boolean useSpringAnnotationConfig = false; protected boolean useSwaggerFeature = false; - + protected boolean useSwaggerUI = false; protected boolean useWadlFeature = false; - + protected boolean useMultipartFeature = false; protected boolean useBeanValidationFeature = false; - - protected boolean generateSpringBootApplication= false; - + + protected boolean generateSpringBootApplication = false; + protected boolean generateJbossDeploymentDescriptor = false; protected boolean useGzipFeature = false; @@ -58,27 +56,29 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen protected boolean generateNonSpringApplication = false; - public JavaCXFServerCodegen() - { + public JavaCXFServerCodegen() { super(); supportsInheritance = true; - + artifactId = "swagger-cxf-server"; - + outputFolder = "generated-code/JavaJaxRS-CXF"; - + apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); - + // clear model and api doc template as this codegen // does not support auto-generated markdown doc at the moment - //TODO: add doc templates + // TODO: add doc templates modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); typeMapping.put("date", "LocalDate"); - typeMapping.put("DateTime", "javax.xml.datatype.XMLGregorianCalendar"); // Map DateTime fields to Java standart class 'XMLGregorianCalendar' + typeMapping.put("DateTime", "javax.xml.datatype.XMLGregorianCalendar"); // Map DateTime + // fields to Java + // standart class + // 'XMLGregorianCalendar' importMapping.put("LocalDate", "org.joda.time.LocalDate"); @@ -86,9 +86,11 @@ public JavaCXFServerCodegen() cliOptions.add(CliOption.newBoolean(USE_JAXB_ANNOTATIONS, "Use JAXB annotations for XML")); - cliOptions.add(CliOption.newBoolean(GENERATE_SPRING_APPLICATION, "Generate Spring application")); - cliOptions.add(CliOption.newBoolean(USE_SPRING_ANNOTATION_CONFIG, "Use Spring Annotation Config")); - + cliOptions.add(CliOption.newBoolean(GENERATE_SPRING_APPLICATION, + "Generate Spring application")); + cliOptions.add(CliOption.newBoolean(USE_SPRING_ANNOTATION_CONFIG, + "Use Spring Annotation Config")); + cliOptions.add(CliOption.newBoolean(USE_SWAGGER_FEATURE, "Use Swagger Feature")); cliOptions.add(CliOption.newBoolean(USE_SWAGGER_UI, "Use Swagger UI")); @@ -96,42 +98,48 @@ public JavaCXFServerCodegen() cliOptions.add(CliOption.newBoolean(USE_MULTIPART_FEATURE, "Use Multipart Feature")); cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE, "Use Gzip Feature")); - cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE_FOR_TESTS, "Use Gzip Feature for tests")); + cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE_FOR_TESTS, + "Use Gzip Feature for tests")); - cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION_FEATURE, "Use BeanValidation Feature")); + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION_FEATURE, + "Use BeanValidation Feature")); cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE, "Use Logging Feature")); - cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE_FOR_TESTS, "Use Logging Feature for tests")); - - cliOptions.add(CliOption.newBoolean(GENERATE_SPRING_BOOT_APPLICATION, "Generate Spring Boot application")); - cliOptions.add( - CliOption.newBoolean(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, "Generate Jboss Deployment Descriptor")); - - cliOptions - .add(CliOption.newBoolean(ADD_CONSUMES_PRODUCES_JSON, "Add @Consumes/@Produces Json to API interface")); - - cliOptions.add(CliOption.newBoolean(USE_ANNOTATED_BASE_PATH, "Use @Path annotations for basePath")); - - cliOptions.add(CliOption.newBoolean(GENERATE_NON_SPRING_APPLICATION, "Generate non-Spring application")); + cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE_FOR_TESTS, + "Use Logging Feature for tests")); + + cliOptions.add(CliOption.newBoolean(GENERATE_SPRING_BOOT_APPLICATION, + "Generate Spring Boot application")); + cliOptions.add(CliOption.newBoolean(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, + "Generate Jboss Deployment Descriptor")); + + cliOptions.add(CliOption.newBoolean(ADD_CONSUMES_PRODUCES_JSON, + "Add @Consumes/@Produces Json to API interface")); + + cliOptions.add(CliOption.newBoolean(USE_ANNOTATED_BASE_PATH, + "Use @Path annotations for basePath")); + + cliOptions.add(CliOption.newBoolean(GENERATE_NON_SPRING_APPLICATION, + "Generate non-Spring application")); } @Override - public void processOpts() - { + public void processOpts() { super.processOpts(); - + if (additionalProperties.containsKey(USE_JAXB_ANNOTATIONS)) { - boolean useJaxbAnnotationsProp = convertPropertyToBooleanAndWriteBack(USE_JAXB_ANNOTATIONS); + boolean useJaxbAnnotationsProp = + convertPropertyToBooleanAndWriteBack(USE_JAXB_ANNOTATIONS); this.setUseJaxbAnnotations(useJaxbAnnotationsProp); } - + if (additionalProperties.containsKey(ADD_CONSUMES_PRODUCES_JSON)) { this.setAddConsumesProducesJson(convertPropertyToBooleanAndWriteBack(ADD_CONSUMES_PRODUCES_JSON)); } if (additionalProperties.containsKey(GENERATE_SPRING_APPLICATION)) { this.setGenerateSpringApplication(convertPropertyToBooleanAndWriteBack(GENERATE_SPRING_APPLICATION)); - + this.setUseSwaggerFeature(convertPropertyToBooleanAndWriteBack(USE_SWAGGER_FEATURE)); this.setUseSwaggerUI(convertPropertyToBooleanAndWriteBack(USE_SWAGGER_UI)); @@ -142,84 +150,91 @@ public void processOpts() this.setUseLoggingFeature(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE)); this.setUseLoggingFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE_FOR_TESTS)); this.setUseSpringAnnotationConfig(convertPropertyToBooleanAndWriteBack(USE_SPRING_ANNOTATION_CONFIG)); - - boolean useBeanValidationFeature = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION_FEATURE); + + boolean useBeanValidationFeature = + convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION_FEATURE); this.setUseBeanValidationFeature(useBeanValidationFeature); if (useBeanValidationFeature) { LOGGER.info("make sure your target server supports Bean Validation 1.1"); } - + this.setGenerateSpringBootApplication(convertPropertyToBooleanAndWriteBack(GENERATE_SPRING_BOOT_APPLICATION)); } - + if (additionalProperties.containsKey(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)) { - boolean generateJbossDeploymentDescriptorProp = convertPropertyToBooleanAndWriteBack( - GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); + boolean generateJbossDeploymentDescriptorProp = + convertPropertyToBooleanAndWriteBack(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); this.setGenerateJbossDeploymentDescriptor(generateJbossDeploymentDescriptorProp); } if (additionalProperties.containsKey(USE_ANNOTATED_BASE_PATH)) { - boolean useAnnotatedBasePathProp = convertPropertyToBooleanAndWriteBack(USE_ANNOTATED_BASE_PATH); + boolean useAnnotatedBasePathProp = + convertPropertyToBooleanAndWriteBack(USE_ANNOTATED_BASE_PATH); this.setUseAnnotatedBasePath(useAnnotatedBasePathProp); } if (additionalProperties.containsKey(GENERATE_NON_SPRING_APPLICATION)) { - boolean generateNonSpringApplication = convertPropertyToBooleanAndWriteBack(GENERATE_NON_SPRING_APPLICATION); + boolean generateNonSpringApplication = + convertPropertyToBooleanAndWriteBack(GENERATE_NON_SPRING_APPLICATION); this.setGenerateNonSpringApplication(generateNonSpringApplication); } supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen - + writeOptional(outputFolder, new SupportingFile("server/pom.mustache", "", "pom.xml")); - - writeOptional(outputFolder, - new SupportingFile("server/swagger-codegen-ignore.mustache", "", ".swagger-codegen-ignore")); + + writeOptional(outputFolder, new SupportingFile("server/swagger-codegen-ignore.mustache", + "", ".swagger-codegen-ignore")); if (this.generateSpringApplication) { writeOptional(outputFolder, new SupportingFile("server/readme.md", "", "readme.md")); - - writeOptional(outputFolder, new SupportingFile("server/ApplicationContext.xml.mustache", - ("src/main/resources"), "ApplicationContext.xml")); + + writeOptional(outputFolder, new SupportingFile( + "server/ApplicationContext.xml.mustache", ("src/main/resources"), + "ApplicationContext.xml")); writeOptional(outputFolder, new SupportingFile("server/web.mustache", ("src/main/webapp/WEB-INF"), "web.xml")); writeOptional(outputFolder, new SupportingFile("server/context.xml.mustache", ("src/main/webapp/WEB-INF"), "context.xml")); - + // Jboss if (generateJbossDeploymentDescriptor) { writeOptional(outputFolder, new SupportingFile("server/jboss-web.xml.mustache", ("src/main/webapp/WEB-INF"), "jboss-web.xml")); } - + // Spring Boot if (this.generateSpringBootApplication) { - writeOptional(outputFolder, new SupportingFile("server/SpringBootApplication.mustache", - (testFolder + '/' + apiPackage).replace(".", "/"), "SpringBootApplication.java")); - writeOptional(outputFolder, new SupportingFile("server/application.properties.mustache", - (testResourcesFolder + '/'), "application.properties")); + writeOptional(outputFolder, + new SupportingFile("server/SpringBootApplication.mustache", + (testFolder + '/' + apiPackage).replace(".", "/"), + "SpringBootApplication.java")); + writeOptional(outputFolder, new SupportingFile( + "server/application.properties.mustache", (testResourcesFolder + '/'), + "application.properties")); } } - + if (this.generateNonSpringApplication) { writeOptional(outputFolder, new SupportingFile("server/nonspring-web.mustache", ("src/main/webapp/WEB-INF"), "web.xml")); } } - + @Override - public String getName() - { + public String getName() { return "jaxrs-cxf"; } @Override - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { - super.addOperationToGroup(tag, resourcePath, operation, co, operations); + public void addOperationToGroup(String tag, String resourcePath, Operation operation, + CodegenOperation co, Map> operations) { + super.addOperationToGroup(tag, resourcePath, operation, co, operations); co.subresourceOperation = !co.path.isEmpty(); } - + @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); @@ -228,13 +243,12 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert model.imports.remove("JsonSerialize"); model.imports.remove("ToStringSerializer"); } - + @Override - public String getHelp() - { + public String getHelp() { return "Generates a Java JAXRS Server application based on Apache CXF framework."; } - + public void setGenerateSpringApplication(boolean generateSpringApplication) { this.generateSpringApplication = generateSpringApplication; } @@ -271,7 +285,7 @@ public void setUseLoggingFeature(boolean useLoggingFeature) { public void setUseBeanValidationFeature(boolean useBeanValidationFeature) { this.useBeanValidationFeature = useBeanValidationFeature; } - + public void setGenerateSpringBootApplication(boolean generateSpringBootApplication) { this.generateSpringBootApplication = generateSpringBootApplication; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index ab4345f997a..9cf0b0116bb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -12,11 +12,11 @@ import java.util.*; import java.util.regex.Pattern; -public class JavaClientCodegen extends AbstractJavaCodegen - implements BeanValidationFeatures, PerformBeanValidationFeatures { +public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValidationFeatures, + PerformBeanValidationFeatures { static final String MEDIA_TYPE = "mediaType"; - @SuppressWarnings("hiding") + @SuppressWarnings("hiding") private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class); public static final String USE_RX_JAVA = "useRxJava"; @@ -42,21 +42,39 @@ public JavaClientCodegen() { apiPackage = "io.swagger.client.api"; modelPackage = "io.swagger.client.model"; - cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library.")); - cliOptions.add(CliOption.newBoolean(PARCELABLE_MODEL, "Whether to generate models for Android that implement Parcelable with the okhttp-gson library.")); - cliOptions.add(CliOption.newBoolean(USE_PLAY24_WS, "Use Play! 2.4 Async HTTP client (Play WS API)")); - cliOptions.add(CliOption.newBoolean(SUPPORT_JAVA6, "Whether to support Java6 with the Jersey1 library.")); - cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); + cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, + "Whether to use the RxJava adapter with the retrofit2 library.")); + cliOptions + .add(CliOption + .newBoolean(PARCELABLE_MODEL, + "Whether to generate models for Android that implement Parcelable with the okhttp-gson library.")); + cliOptions.add(CliOption.newBoolean(USE_PLAY24_WS, + "Use Play! 2.4 Async HTTP client (Play WS API)")); + cliOptions.add(CliOption.newBoolean(SUPPORT_JAVA6, + "Whether to support Java6 with the Jersey1 library.")); + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, + "Use BeanValidation API annotations")); cliOptions.add(CliOption.newBoolean(PERFORM_BEANVALIDATION, "Perform BeanValidation")); - supportedLibraries.put("jersey1", "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0. Enable Java6 support using '-DsupportJava6=true'."); - supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0"); - supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.22.2. JSON processing: Jackson 2.7.0"); - supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2. Enable Parcelable modles on Android using '-DparcelableModel=true'"); - supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead."); - supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.3)"); - - CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); + supportedLibraries + .put("jersey1", + "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0. Enable Java6 support using '-DsupportJava6=true'."); + supportedLibraries.put("feign", + "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0"); + supportedLibraries.put("jersey2", + "HTTP client: Jersey client 2.22.2. JSON processing: Jackson 2.7.0"); + supportedLibraries + .put("okhttp-gson", + "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2. Enable Parcelable modles on Android using '-DparcelableModel=true'"); + supportedLibraries + .put(RETROFIT_1, + "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead."); + supportedLibraries + .put(RETROFIT_2, + "HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.3)"); + + CliOption libraryOption = + new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); libraryOption.setEnum(supportedLibraries); // set okhttp-gson as the default libraryOption.setDefault("okhttp-gson"); @@ -93,7 +111,8 @@ public void processOpts() { additionalProperties.put(USE_PLAY24_WS, usePlay24WS); if (additionalProperties.containsKey(PARCELABLE_MODEL)) { - this.setParcelableModel(Boolean.valueOf(additionalProperties.get(PARCELABLE_MODEL).toString())); + this.setParcelableModel(Boolean.valueOf(additionalProperties.get(PARCELABLE_MODEL) + .toString())); } // put the boolean value back to PARCELABLE_MODEL in additionalProperties additionalProperties.put(PARCELABLE_MODEL, parcelableModel); @@ -109,67 +128,85 @@ public void processOpts() { final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/"); final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); - //Common files + // Common files writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); writeOptional(outputFolder, new SupportingFile("build.gradle.mustache", "", "build.gradle")); writeOptional(outputFolder, new SupportingFile("build.sbt.mustache", "", "build.sbt")); - writeOptional(outputFolder, new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); - writeOptional(outputFolder, new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); - writeOptional(outputFolder, new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); + writeOptional(outputFolder, new SupportingFile("settings.gradle.mustache", "", + "settings.gradle")); + writeOptional(outputFolder, new SupportingFile("gradle.properties.mustache", "", + "gradle.properties")); + writeOptional(outputFolder, new SupportingFile("manifest.mustache", projectFolder, + "AndroidManifest.xml")); supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml")); - supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); - supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); - supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); - supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, + "ApiClient.java")); + supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, + "StringUtil.java")); + supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, + "HttpBasicAuth.java")); + supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, + "ApiKeyAuth.java")); supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); - supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); - supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew") ); - supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") ); - supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache", - gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") ); - supportingFiles.add(new SupportingFile( "gradle-wrapper.jar", - gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") ); + supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, + "OAuthFlow.java")); + supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); + supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat")); + supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache", + gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties")); + supportingFiles.add(new SupportingFile("gradle-wrapper.jar", gradleWrapperPackage.replace( + ".", File.separator), "gradle-wrapper.jar")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); if (performBeanValidation) { - supportingFiles.add(new SupportingFile("BeanValidationException.mustache", invokerFolder, - "BeanValidationException.java")); + supportingFiles.add(new SupportingFile("BeanValidationException.mustache", + invokerFolder, "BeanValidationException.java")); } - //TODO: add doc to retrofit1 and feign - if ( "feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) ){ + // TODO: add doc to retrofit1 and feign + if ("feign".equals(getLibrary()) || "retrofit".equals(getLibrary())) { modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); } if (!("feign".equals(getLibrary()) || usesAnyRetrofitLibrary())) { - supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); - supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); + supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, + "ApiException.java")); + supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, + "Configuration.java")); supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); - supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); + supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, + "Authentication.java")); } if ("feign".equals(getLibrary())) { additionalProperties.put("jackson", "true"); - supportingFiles.add(new SupportingFile("ParamExpander.mustache", invokerFolder, "ParamExpander.java")); + supportingFiles.add(new SupportingFile("ParamExpander.mustache", invokerFolder, + "ParamExpander.java")); } else if ("okhttp-gson".equals(getLibrary()) || StringUtils.isEmpty(getLibrary())) { // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call - supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); - supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java")); + supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, + "ApiCallback.java")); + supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, + "ApiResponse.java")); supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); - supportingFiles.add(new SupportingFile("ProgressRequestBody.mustache", invokerFolder, "ProgressRequestBody.java")); - supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java")); + supportingFiles.add(new SupportingFile("ProgressRequestBody.mustache", invokerFolder, + "ProgressRequestBody.java")); + supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, + "ProgressResponseBody.java")); additionalProperties.put("gson", "true"); } else if (usesAnyRetrofitLibrary()) { - supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); - supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java")); + supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, + "OAuthOkHttpClient.java")); + supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, + "CollectionFormats.java")); additionalProperties.put("gson", "true"); - } else if("jersey2".equals(getLibrary())) { + } else if ("jersey2".equals(getLibrary())) { supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); additionalProperties.put("jackson", "true"); - } else if("jersey1".equals(getLibrary())) { + } else if ("jersey1".equals(getLibrary())) { additionalProperties.put("jackson", "true"); } else { LOGGER.error("Unknown library option (-l/--library): " + getLibrary()); @@ -186,24 +223,28 @@ public void processOpts() { } // auth - supportingFiles.add(new SupportingFile("play24/auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); - supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); + supportingFiles.add(new SupportingFile("play24/auth/ApiKeyAuth.mustache", authFolder, + "ApiKeyAuth.java")); + supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, + "Authentication.java")); supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); // api client - supportingFiles.add(new SupportingFile("play24/ApiClient.mustache", invokerFolder, "ApiClient.java")); + supportingFiles.add(new SupportingFile("play24/ApiClient.mustache", invokerFolder, + "ApiClient.java")); // adapters - supportingFiles - .add(new SupportingFile("play24/Play24CallFactory.mustache", invokerFolder, "Play24CallFactory.java")); - supportingFiles.add(new SupportingFile("play24/Play24CallAdapterFactory.mustache", invokerFolder, - "Play24CallAdapterFactory.java")); + supportingFiles.add(new SupportingFile("play24/Play24CallFactory.mustache", + invokerFolder, "Play24CallFactory.java")); + supportingFiles.add(new SupportingFile("play24/Play24CallAdapterFactory.mustache", + invokerFolder, "Play24CallAdapterFactory.java")); additionalProperties.put("jackson", "true"); additionalProperties.remove("gson"); } - if (additionalProperties.containsKey("jackson") ) { - supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder, "RFC3339DateFormat.java")); + if (additionalProperties.containsKey("jackson")) { + supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder, + "RFC3339DateFormat.java")); } } @@ -218,24 +259,25 @@ private boolean usesRetrofit2Library() { @Override public Map postProcessOperations(Map objs) { super.postProcessOperations(objs); - if(usesAnyRetrofitLibrary()) { + if (usesAnyRetrofitLibrary()) { Map operations = (Map) objs.get("operations"); if (operations != null) { List ops = (List) operations.get("operation"); for (CodegenOperation operation : ops) { if (operation.hasConsumes == Boolean.TRUE) { - if ( isMultipartType(operation.consumes) ) { + if (isMultipartType(operation.consumes)) { operation.isMultipart = Boolean.TRUE; - } - else { - operation.prioritizedContentTypes = prioritizeContentTypes(operation.consumes); + } else { + operation.prioritizedContentTypes = + prioritizeContentTypes(operation.consumes); } } if (operation.returnType == null) { operation.returnType = "Void"; } - if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) + if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) + && operation.path.startsWith("/")) operation.path = operation.path.substring(1); } } @@ -244,43 +286,41 @@ public Map postProcessOperations(Map objs) { } /** - * Prioritizes consumes mime-type list by moving json-vendor and json mime-types up front, but - * otherwise preserves original consumes definition order. - * [application/vnd...+json,... application/json, ..as is..] - * + * Prioritizes consumes mime-type list by moving json-vendor and json mime-types up front, but + * otherwise preserves original consumes definition order. [application/vnd...+json,... + * application/json, ..as is..] + * * @param consumes consumes mime-type list - * @return + * @return */ static List> prioritizeContentTypes(List> consumes) { - if ( consumes.size() <= 1 ) + if (consumes.size() <= 1) return consumes; - + List> prioritizedContentTypes = new ArrayList<>(consumes.size()); - + List> jsonVendorMimeTypes = new ArrayList<>(consumes.size()); List> jsonMimeTypes = new ArrayList<>(consumes.size()); - - for ( Map consume : consumes) { - if ( isJsonVendorMimeType(consume.get(MEDIA_TYPE))) { + + for (Map consume : consumes) { + if (isJsonVendorMimeType(consume.get(MEDIA_TYPE))) { jsonVendorMimeTypes.add(consume); - } - else if ( isJsonMimeType(consume.get(MEDIA_TYPE))) { + } else if (isJsonMimeType(consume.get(MEDIA_TYPE))) { jsonMimeTypes.add(consume); - } - else + } else prioritizedContentTypes.add(consume); - + consume.put("hasMore", "true"); } - + prioritizedContentTypes.addAll(0, jsonMimeTypes); prioritizedContentTypes.addAll(0, jsonVendorMimeTypes); - - prioritizedContentTypes.get(prioritizedContentTypes.size()-1).put("hasMore", null); - + + prioritizedContentTypes.get(prioritizedContentTypes.size() - 1).put("hasMore", null); + return prioritizedContentTypes; } - + private static boolean isMultipartType(List> consumes) { Map firstType = consumes.get(0); if (firstType != null) { @@ -294,18 +334,18 @@ private static boolean isMultipartType(List> consumes) { @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); - if(!BooleanUtils.toBoolean(model.isEnum)) { - //final String lib = getLibrary(); - //Needed imports for Jackson based libraries - if(additionalProperties.containsKey("jackson")) { + if (!BooleanUtils.toBoolean(model.isEnum)) { + // final String lib = getLibrary(); + // Needed imports for Jackson based libraries + if (additionalProperties.containsKey("jackson")) { model.imports.add("JsonProperty"); } - if(additionalProperties.containsKey("gson")) { + if (additionalProperties.containsKey("gson")) { model.imports.add("SerializedName"); } } else { // enum class - //Needed imports for Jackson's JsonCreator - if(additionalProperties.containsKey("jackson")) { + // Needed imports for Jackson's JsonCreator + if (additionalProperties.containsKey("jackson")) { model.imports.add("JsonCreator"); } } @@ -314,9 +354,9 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert @Override public Map postProcessModelsEnum(Map objs) { objs = super.postProcessModelsEnum(objs); - //Needed import for Gson based libraries + // Needed import for Gson based libraries if (additionalProperties.containsKey("gson")) { - List> imports = (List>)objs.get("imports"); + List> imports = (List>) objs.get("imports"); List models = (List) objs.get("models"); for (Object _mo : models) { Map mo = (Map) _mo; @@ -354,25 +394,22 @@ public void setPerformBeanValidation(boolean performBeanValidation) { this.performBeanValidation = performBeanValidation; } - final private static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application\\/json(;.*)?"); - final private static Pattern JSON_VENDOR_MIME_PATTERN = Pattern.compile("(?i)application\\/vnd.(.*)+json(;.*)?"); + final private static Pattern JSON_MIME_PATTERN = Pattern + .compile("(?i)application\\/json(;.*)?"); + final private static Pattern JSON_VENDOR_MIME_PATTERN = Pattern + .compile("(?i)application\\/vnd.(.*)+json(;.*)?"); /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON + * Check if the given MIME is a JSON MIME. JSON MIME examples: application/json + * application/json; charset=UTF8 APPLICATION/JSON */ static boolean isJsonMimeType(String mime) { - return mime != null && ( JSON_MIME_PATTERN.matcher(mime).matches()); + return mime != null && (JSON_MIME_PATTERN.matcher(mime).matches()); } /** - * Check if the given MIME is a JSON Vendor MIME. - * JSON MIME examples: - * application/vnd.mycompany+json - * application/vnd.mycompany.resourceA.version1+json + * Check if the given MIME is a JSON Vendor MIME. JSON MIME examples: + * application/vnd.mycompany+json application/vnd.mycompany.resourceA.version1+json */ static boolean isJsonVendorMimeType(String mime) { return mime != null && JSON_VENDOR_MIME_PATTERN.matcher(mime).matches(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java index 1c856c95382..bf4a9004f1c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java @@ -18,6 +18,7 @@ public class JavaInflectorServerCodegen extends AbstractJavaCodegen { protected String title = "Swagger Inflector"; protected String implFolder = "src/main/java"; + public JavaInflectorServerCodegen() { super(); @@ -26,17 +27,19 @@ public JavaInflectorServerCodegen() { embeddedTemplateDir = templateDir = "JavaInflector"; invokerPackage = "io.swagger.handler"; artifactId = "swagger-inflector-server"; - dateLibrary = "legacy"; //TODO: add joda support + dateLibrary = "legacy"; // TODO: add joda support // clear model and api doc template as this codegen // does not support auto-generated markdown doc at the moment - //TODO: add doc templates + // TODO: add doc templates modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); - apiPackage = System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.handler"); - modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model"); + apiPackage = + System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.handler"); + modelPackage = + System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model"); additionalProperties.put("title", title); // java inflector uses the jackson lib @@ -64,18 +67,18 @@ public void processOpts() { writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); - writeOptional(outputFolder, new SupportingFile("web.mustache", "src/main/webapp/WEB-INF", "web.xml")); + writeOptional(outputFolder, new SupportingFile("web.mustache", "src/main/webapp/WEB-INF", + "web.xml")); writeOptional(outputFolder, new SupportingFile("inflector.mustache", "", "inflector.yaml")); - supportingFiles.add(new SupportingFile("swagger.mustache", - "src/main/swagger", - "swagger.yaml") - ); + supportingFiles.add(new SupportingFile("swagger.mustache", "src/main/swagger", + "swagger.yaml")); supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + invokerPackage).replace(".", "/"), "StringUtil.java")); } @Override - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + public void addOperationToGroup(String tag, String resourcePath, Operation operation, + CodegenOperation co, Map> operations) { String basePath = resourcePath; if (basePath.startsWith("/")) { basePath = basePath.substring(1); @@ -141,11 +144,11 @@ public Map postProcessOperations(Map objs) { public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); - //Add imports for Jackson - if(!BooleanUtils.toBoolean(model.isEnum)) { + // Add imports for Jackson + if (!BooleanUtils.toBoolean(model.isEnum)) { model.imports.add("JsonProperty"); - if(BooleanUtils.toBoolean(model.hasEnums)) { + if (BooleanUtils.toBoolean(model.hasEnums)) { model.imports.add("JsonValue"); } } @@ -155,8 +158,8 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert public Map postProcessModelsEnum(Map objs) { objs = super.postProcessModelsEnum(objs); - //Add imports for Jackson - List> imports = (List>)objs.get("imports"); + // Add imports for Jackson + List> imports = (List>) objs.get("imports"); List models = (List) objs.get("models"); for (Object _mo : models) { Map mo = (Map) _mo; @@ -176,7 +179,7 @@ public Map postProcessModelsEnum(Map objs) { public String apiFilename(String templateName, String tag) { String result = super.apiFilename(templateName, tag); - if ( templateName.endsWith("api.mustache") ) { + if (templateName.endsWith("api.mustache")) { int ix = result.indexOf(sourceFolder); String beg = result.substring(0, ix); String end = result.substring(ix + sourceFolder.length()); @@ -188,8 +191,8 @@ public String apiFilename(String templateName, String tag) { @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { + Swagger swagger = (Swagger) objs.get("swagger"); + if (swagger != null) { try { objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); } catch (JsonProcessingException e) { @@ -204,7 +207,9 @@ public String toApiName(String name) { if (name.length() == 0) { return "DefaultController"; } - name = name.replaceAll("[^a-zA-Z0-9]+", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - return camelize(name)+ "Controller"; + name = name.replaceAll("[^a-zA-Z0-9]+", "_"); // FIXME: a parameter should not be assigned. + // Also declare the methods parameters as + // 'final'. + return camelize(name) + "Controller"; } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java index d3895532f76..040afbef39a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java @@ -9,16 +9,16 @@ import java.io.File; /** - * Generates a Java JAXRS Server according to JAXRS 2.0 specification, assuming an - * Apache CXF runtime and a Java EE runtime with CDI enabled. - * Similar to the original JAXRS generator, this creates API and Service classes - * in /src/gen/java and a sample ServiceImpl in /src/main/java. The API uses CDI - * to get an instance of ServiceImpl that implements the Service interface. + * Generates a Java JAXRS Server according to JAXRS 2.0 specification, assuming an Apache CXF + * runtime and a Java EE runtime with CDI enabled. Similar to the original JAXRS generator, this + * creates API and Service classes in /src/gen/java and a sample ServiceImpl in /src/main/java. The + * API uses CDI to get an instance of ServiceImpl that implements the Service interface. */ -public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen implements BeanValidationFeatures { - +public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen implements + BeanValidationFeatures { + protected boolean useBeanValidation = true; - + /** * Default constructor */ @@ -35,10 +35,11 @@ public JavaJAXRSCXFCDIServerCodegen() { typeMapping.put("DateTime", "java.util.Date"); // Updated template directory - embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME - + File.separator + "cxf-cdi"; - - cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); + embeddedTemplateDir = + templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf-cdi"; + + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, + "Use BeanValidation API annotations")); } @Override @@ -57,7 +58,7 @@ public void processOpts() { if (useBeanValidation) { writePropertyBack(USE_BEANVALIDATION, useBeanValidation); } - + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen // writeOptional means these files are only written if they don't already exist @@ -70,8 +71,8 @@ public void processOpts() { (implFolder + '/' + invokerPackage).replace(".", "/"), "RestApplication.java")); // Make CDI work in containers with implicit archive scanning disabled - writeOptional(outputFolder, new SupportingFile("beans.mustache", - "src/main/webapp/WEB-INF", "beans.xml")); + writeOptional(outputFolder, new SupportingFile("beans.mustache", "src/main/webapp/WEB-INF", + "beans.xml")); } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java index 6c91e175db5..3676d971245 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java @@ -21,11 +21,9 @@ import io.swagger.models.properties.Property; import io.swagger.util.Json; -public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen -{ - - public JavaJAXRSSpecServerCodegen() - { +public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen { + + public JavaJAXRSSpecServerCodegen() { super(); invokerPackage = "io.swagger.api"; artifactId = "swagger-jaxrs-server"; @@ -41,59 +39,63 @@ public JavaJAXRSSpecServerCodegen() // clear model and api doc template as this codegen // does not support auto-generated markdown doc at the moment - //TODO: add doc templates + // TODO: add doc templates modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); additionalProperties.put("title", title); typeMapping.put("date", "LocalDate"); - typeMapping.put("DateTime", "javax.xml.datatype.XMLGregorianCalendar"); // Map DateTime fields to Java standart class 'XMLGregorianCalendar' + typeMapping.put("DateTime", "javax.xml.datatype.XMLGregorianCalendar"); // Map DateTime + // fields to Java + // standart class + // 'XMLGregorianCalendar' importMapping.put("LocalDate", "org.joda.time.LocalDate"); - super.embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "spec"; + super.embeddedTemplateDir = + templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "spec"; - for ( int i = 0; i < cliOptions.size(); i++ ) { - if ( CodegenConstants.LIBRARY.equals(cliOptions.get(i).getOpt()) ) { + for (int i = 0; i < cliOptions.size(); i++) { + if (CodegenConstants.LIBRARY.equals(cliOptions.get(i).getOpt())) { cliOptions.remove(i); break; } } - - CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); + + CliOption library = + new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); library.setDefault(DEFAULT_LIBRARY); - Map supportedLibraries = new LinkedHashMap(); + Map supportedLibraries = new LinkedHashMap(); supportedLibraries.put(DEFAULT_LIBRARY, "JAXRS"); library.setEnum(supportedLibraries); cliOptions.add(library); } - + @Override - public void processOpts() - { + public void processOpts() { super.processOpts(); - + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); - + writeOptional(outputFolder, new SupportingFile("RestApplication.mustache", (sourceFolder + '/' + invokerPackage).replace(".", "/"), "RestApplication.java")); - - } - + + } + @Override - public String getName() - { + public String getName() { return "jaxrs-spec"; } @Override - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + public void addOperationToGroup(String tag, String resourcePath, Operation operation, + CodegenOperation co, Map> operations) { String basePath = resourcePath; if (basePath.startsWith("/")) { basePath = basePath.substring(1); @@ -119,7 +121,7 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera opList.add(co); co.baseName = basePath; } - + @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); @@ -130,22 +132,23 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert model.imports.remove("JsonValue"); model.imports.remove("JsonProperty"); } - + @Override public void preprocessSwagger(Swagger swagger) { - //copy input swagger to output folder + // copy input swagger to output folder try { String swaggerJson = Json.pretty(swagger); - FileUtils.writeStringToFile(new File(outputFolder + File.separator + "swagger.json"), swaggerJson); + FileUtils.writeStringToFile(new File(outputFolder + File.separator + "swagger.json"), + swaggerJson); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e.getCause()); } super.preprocessSwagger(swagger); } + @Override - public String getHelp() - { + public String getHelp() { return "Generates a Java JAXRS Server according to JAXRS 2.0 specification."; } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java index 8cbd3a485d5..b8b6ade3a63 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java @@ -13,7 +13,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { protected static final String LIBRARY_JERSEY1 = "jersey1"; protected static final String LIBRARY_JERSEY2 = "jersey2"; - + /** * Default library template to use. (Default:{@value #DEFAULT_LIBRARY}) */ @@ -31,13 +31,14 @@ public JavaJerseyServerCodegen() { // clear model and api doc template as this codegen // does not support auto-generated markdown doc at the moment - //TODO: add doc templates + // TODO: add doc templates modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME; - CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); + CliOption library = + new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); supportedLibraries.put(LIBRARY_JERSEY1, "Jersey core 1.x"); supportedLibraries.put(LIBRARY_JERSEY2, "Jersey core 2.x"); @@ -45,33 +46,32 @@ public JavaJerseyServerCodegen() { library.setDefault(DEFAULT_LIBRARY); cliOptions.add(library); - cliOptions.add(CliOption.newBoolean(SUPPORT_JAVA6, "Whether to support Java6 with the Jersey1/2 library.")); + cliOptions.add(CliOption.newBoolean(SUPPORT_JAVA6, + "Whether to support Java6 with the Jersey1/2 library.")); } @Override - public String getName() - { + public String getName() { return "jaxrs"; // TODO should be renamed as "jaxrs-jersey" } @Override - public String getHelp() - { + public String getHelp() { return "Generates a Java JAXRS Server application based on Jersey framework."; } @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); - if("null".equals(property.example)) { + if ("null".equals(property.example)) { property.example = null; } - //Add imports for Jackson - if(!BooleanUtils.toBoolean(model.isEnum)) { + // Add imports for Jackson + if (!BooleanUtils.toBoolean(model.isEnum)) { model.imports.add("JsonProperty"); - if(BooleanUtils.toBoolean(model.hasEnums)) { + if (BooleanUtils.toBoolean(model.hasEnums)) { model.imports.add("JsonValue"); } } @@ -85,30 +85,46 @@ public void processOpts() { if (StringUtils.isEmpty(library)) { setLibrary(DEFAULT_LIBRARY); } - - if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { + + if (additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); } if ("joda".equals(dateLibrary)) { - supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java")); - supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java")); - } else if ( dateLibrary.startsWith("java8") ) { - supportingFiles.add(new SupportingFile("OffsetDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "OffsetDateTimeProvider.java")); - supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java")); + supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), + "JodaDateTimeProvider.java")); + supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), + "JodaLocalDateProvider.java")); + } else if (dateLibrary.startsWith("java8")) { + supportingFiles.add(new SupportingFile("OffsetDateTimeProvider.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), + "OffsetDateTimeProvider.java")); + supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java")); } writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("ApiException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiException.java")); - supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiOriginFilter.java")); - supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiResponseMessage.java")); - supportingFiles.add(new SupportingFile("NotFoundException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java")); - supportingFiles.add(new SupportingFile("jacksonJsonProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JacksonJsonProvider.java")); - supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "RFC3339DateFormat.java")); - writeOptional(outputFolder, new SupportingFile("bootstrap.mustache", (implFolder + '/' + apiPackage).replace(".", "/"), "Bootstrap.java")); - writeOptional(outputFolder, new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml")); - supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java")); + supportingFiles.add(new SupportingFile("ApiException.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiException.java")); + supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiOriginFilter.java")); + supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiResponseMessage.java")); + supportingFiles.add(new SupportingFile("NotFoundException.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java")); + supportingFiles.add(new SupportingFile("jacksonJsonProvider.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "JacksonJsonProvider.java")); + supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "RFC3339DateFormat.java")); + writeOptional(outputFolder, new SupportingFile("bootstrap.mustache", + (implFolder + '/' + apiPackage).replace(".", "/"), "Bootstrap.java")); + writeOptional(outputFolder, new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), + "web.xml")); + supportingFiles.add(new SupportingFile("StringUtil.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java")); } @@ -116,8 +132,8 @@ public void processOpts() { public Map postProcessModelsEnum(Map objs) { objs = super.postProcessModelsEnum(objs); - //Add imports for Jackson - List> imports = (List>)objs.get("imports"); + // Add imports for Jackson + List> imports = (List>) objs.get("imports"); List models = (List) objs.get("models"); for (Object _mo : models) { Map mo = (Map) _mo; @@ -135,7 +151,8 @@ public Map postProcessModelsEnum(Map objs) { } @Override - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + public void addOperationToGroup(String tag, String resourcePath, Operation operation, + CodegenOperation co, Map> operations) { String basePath = resourcePath; if (basePath.startsWith("/")) { basePath = basePath.substring(1); @@ -161,5 +178,5 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera opList.add(co); co.baseName = basePath; } - + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaMSF4JServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaMSF4JServerCodegen.java index 459a8cee29b..81240965291 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaMSF4JServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaMSF4JServerCodegen.java @@ -22,11 +22,12 @@ public JavaMSF4JServerCodegen() { apiTemplateFiles.put("apiService.mustache", ".java"); apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); apiTemplateFiles.put("apiServiceFactory.mustache", ".java"); - apiTestTemplateFiles.clear(); + apiTestTemplateFiles.clear(); modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); embeddedTemplateDir = templateDir = "MSF4J"; - CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); + CliOption library = + new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); supportedLibraries.put(LIBRARY_JERSEY1, "Jersey core 1.x"); supportedLibraries.put(LIBRARY_JERSEY2, "Jersey core 2.x"); library.setEnum(supportedLibraries); @@ -36,29 +37,27 @@ public JavaMSF4JServerCodegen() { } @Override - public String getName() - { + public String getName() { return "msf4j"; } @Override - public String getHelp() - { + public String getHelp() { return "Generates a Java Micro Service based on WSO2 Microservices Framework for Java (MSF4J)"; } @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); - if("null".equals(property.example)) { + if ("null".equals(property.example)) { property.example = null; } - //Add imports for Jackson - if(!BooleanUtils.toBoolean(model.isEnum)) { + // Add imports for Jackson + if (!BooleanUtils.toBoolean(model.isEnum)) { model.imports.add("JsonProperty"); - if(BooleanUtils.toBoolean(model.hasEnums)) { + if (BooleanUtils.toBoolean(model.hasEnums)) { model.imports.add("JsonValue"); } } @@ -73,38 +72,55 @@ public void processOpts() { setLibrary(DEFAULT_LIBRARY); } - if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { + if (additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); } if ("joda".equals(dateLibrary)) { - supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java")); - supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java")); - } else if ( dateLibrary.startsWith("java8") ) { - supportingFiles.add(new SupportingFile("OffsetDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "OffsetDateTimeProvider.java")); - supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java")); + supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), + "JodaDateTimeProvider.java")); + supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), + "JodaLocalDateProvider.java")); + } else if (dateLibrary.startsWith("java8")) { + supportingFiles.add(new SupportingFile("OffsetDateTimeProvider.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), + "OffsetDateTimeProvider.java")); + supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java")); } writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("ApiException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiException.java")); - supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiOriginFilter.java")); - supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiResponseMessage.java")); - supportingFiles.add(new SupportingFile("NotFoundException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java")); - supportingFiles.add(new SupportingFile("jacksonJsonProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JacksonJsonProvider.java")); - supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "RFC3339DateFormat.java")); - //writeOptional(outputFolder, new SupportingFile("bootstrap.mustache", (implFolder + '/' + apiPackage).replace(".", "/"), "Bootstrap.java")); - //writeOptional(outputFolder, new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml")); - supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java")); - supportingFiles.add(new SupportingFile("Application.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "Application.java")); + supportingFiles.add(new SupportingFile("ApiException.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiException.java")); + supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiOriginFilter.java")); + supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiResponseMessage.java")); + supportingFiles.add(new SupportingFile("NotFoundException.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java")); + supportingFiles.add(new SupportingFile("jacksonJsonProvider.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "JacksonJsonProvider.java")); + supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "RFC3339DateFormat.java")); + // writeOptional(outputFolder, new SupportingFile("bootstrap.mustache", (implFolder + '/' + + // apiPackage).replace(".", "/"), "Bootstrap.java")); + // writeOptional(outputFolder, new SupportingFile("web.mustache", + // ("src/main/webapp/WEB-INF"), "web.xml")); + supportingFiles.add(new SupportingFile("StringUtil.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java")); + supportingFiles.add(new SupportingFile("Application.mustache", + (sourceFolder + '/' + apiPackage).replace(".", "/"), "Application.java")); } @Override public Map postProcessModelsEnum(Map objs) { objs = super.postProcessModelsEnum(objs); - //Add imports for Jackson - List> imports = (List>)objs.get("imports"); + // Add imports for Jackson + List> imports = (List>) objs.get("imports"); List models = (List) objs.get("models"); for (Object _mo : models) { Map mo = (Map) _mo; @@ -122,7 +138,8 @@ public Map postProcessModelsEnum(Map objs) { } @Override - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + public void addOperationToGroup(String tag, String resourcePath, Operation operation, + CodegenOperation co, Map> operations) { String basePath = resourcePath; if (basePath.startsWith("/")) { basePath = basePath.substring(1); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java index 7627884c407..fd2eb2daaa8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java @@ -10,10 +10,11 @@ import java.io.File; import java.util.*; -public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen implements JbossFeature { +public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen implements + JbossFeature { protected boolean generateJbossDeploymentDescriptor = true; - + public JavaResteasyServerCodegen() { super(); @@ -28,7 +29,7 @@ public JavaResteasyServerCodegen() { // clear model and api doc template as AbstractJavaJAXRSServerCodegen // does not support auto-generated markdown doc at the moment - //TODO: add doc templates + // TODO: add doc templates modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); @@ -36,8 +37,8 @@ public JavaResteasyServerCodegen() { embeddedTemplateDir = templateDir = "JavaJaxRS" + File.separator + "resteasy"; - cliOptions.add( - CliOption.newBoolean(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, "Generate Jboss Deployment Descriptor")); + cliOptions.add(CliOption.newBoolean(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, + "Generate Jboss Deployment Descriptor")); } @Override @@ -55,14 +56,15 @@ public void processOpts() { super.processOpts(); if (additionalProperties.containsKey(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)) { - boolean generateJbossDeploymentDescriptorProp = convertPropertyToBooleanAndWriteBack( - GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); + boolean generateJbossDeploymentDescriptorProp = + convertPropertyToBooleanAndWriteBack(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); this.setGenerateJbossDeploymentDescriptor(generateJbossDeploymentDescriptorProp); } - + writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); writeOptional(outputFolder, new SupportingFile("gradle.mustache", "", "build.gradle")); - writeOptional(outputFolder, new SupportingFile("settingsGradle.mustache", "", "settings.gradle")); + writeOptional(outputFolder, new SupportingFile("settingsGradle.mustache", "", + "settings.gradle")); writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("ApiException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiException.java")); @@ -72,12 +74,12 @@ public void processOpts() { (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiResponseMessage.java")); supportingFiles.add(new SupportingFile("NotFoundException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java")); - writeOptional(outputFolder, new SupportingFile("web.mustache", - ("src/main/webapp/WEB-INF"), "web.xml")); + writeOptional(outputFolder, new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), + "web.xml")); if (generateJbossDeploymentDescriptor) { writeOptional(outputFolder, new SupportingFile("jboss-web.mustache", - ("src/main/webapp/WEB-INF"), "jboss-web.xml")); + ("src/main/webapp/WEB-INF"), "jboss-web.xml")); } writeOptional(outputFolder, new SupportingFile("RestApplication.mustache", @@ -91,19 +93,23 @@ public void processOpts() { if ("joda".equals(dateLibrary)) { supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", - (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java")); + (sourceFolder + '/' + apiPackage).replace(".", "/"), + "JodaDateTimeProvider.java")); supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", - (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java")); + (sourceFolder + '/' + apiPackage).replace(".", "/"), + "JodaLocalDateProvider.java")); } else if (dateLibrary.startsWith("java8")) { supportingFiles.add(new SupportingFile("OffsetDateTimeProvider.mustache", - (sourceFolder + '/' + apiPackage).replace(".", "/"), "OffsetDateTimeProvider.java")); + (sourceFolder + '/' + apiPackage).replace(".", "/"), + "OffsetDateTimeProvider.java")); supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java")); } } @Override - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + public void addOperationToGroup(String tag, String resourcePath, Operation operation, + CodegenOperation co, Map> operations) { String basePath = resourcePath; if (basePath.startsWith("/")) { basePath = basePath.substring(1); @@ -166,7 +172,8 @@ public Map postProcessOperations(Map objs) { String rt = operation.returnType; int end = rt.lastIndexOf(">"); if (end > 0) { - operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim(); + operation.returnType = + rt.substring("Map<".length(), end).split(",")[1].trim(); operation.returnContainer = "Map"; } } else if (operation.returnType.startsWith("Set")) { @@ -184,11 +191,11 @@ public Map postProcessOperations(Map objs) { @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { - //Add imports for Jackson - if(!BooleanUtils.toBoolean(model.isEnum)) { + // Add imports for Jackson + if (!BooleanUtils.toBoolean(model.isEnum)) { model.imports.add("JsonProperty"); - if(BooleanUtils.toBoolean(model.hasEnums)) { + if (BooleanUtils.toBoolean(model.hasEnums)) { model.imports.add("JsonValue"); } } @@ -198,8 +205,8 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert public Map postProcessModelsEnum(Map objs) { objs = super.postProcessModelsEnum(objs); - //Add imports for Jackson - List> imports = (List>)objs.get("imports"); + // Add imports for Jackson + List> imports = (List>) objs.get("imports"); List models = (List) objs.get("models"); for (Object _mo : models) { Map mo = (Map) _mo; @@ -215,7 +222,7 @@ public Map postProcessModelsEnum(Map objs) { return objs; } - + public void setGenerateJbossDeploymentDescriptor(boolean generateJbossDeploymentDescriptor) { this.generateJbossDeploymentDescriptor = generateJbossDeploymentDescriptor; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java index dd211512906..ef317c89545 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java @@ -91,30 +91,21 @@ public JavascriptClientCodegen() { apiDocTemplateFiles.put("api_doc.mustache", ".md"); // reference: http://www.w3schools.com/js/js_reserved.asp - setReservedWordsLowerCase( - Arrays.asList( - "abstract", "arguments", "boolean", "break", "byte", - "case", "catch", "char", "class", "const", - "continue", "debugger", "default", "delete", "do", - "double", "else", "enum", "eval", "export", - "extends", "false", "final", "finally", "float", - "for", "function", "goto", "if", "implements", - "import", "in", "instanceof", "int", "interface", - "let", "long", "native", "new", "null", - "package", "private", "protected", "public", "return", - "short", "static", "super", "switch", "synchronized", - "this", "throw", "throws", "transient", "true", - "try", "typeof", "var", "void", "volatile", - "while", "with", "yield", - "Array", "Date", "eval", "function", "hasOwnProperty", - "Infinity", "isFinite", "isNaN", "isPrototypeOf", - "Math", "NaN", "Number", "Object", - "prototype", "String", "toString", "undefined", "valueOf") - ); - - languageSpecificPrimitives = new HashSet( - Arrays.asList("String", "Boolean", "Number", "Array", "Object", "Date", "File") - ); + setReservedWordsLowerCase(Arrays.asList("abstract", "arguments", "boolean", "break", + "byte", "case", "catch", "char", "class", "const", "continue", "debugger", + "default", "delete", "do", "double", "else", "enum", "eval", "export", "extends", + "false", "final", "finally", "float", "for", "function", "goto", "if", + "implements", "import", "in", "instanceof", "int", "interface", "let", "long", + "native", "new", "null", "package", "private", "protected", "public", "return", + "short", "static", "super", "switch", "synchronized", "this", "throw", "throws", + "transient", "true", "try", "typeof", "var", "void", "volatile", "while", "with", + "yield", "Array", "Date", "eval", "function", "hasOwnProperty", "Infinity", + "isFinite", "isNaN", "isPrototypeOf", "Math", "NaN", "Number", "Object", + "prototype", "String", "toString", "undefined", "valueOf")); + + languageSpecificPrimitives = + new HashSet(Arrays.asList("String", "Boolean", "Number", "Array", "Object", + "Date", "File")); defaultIncludes = new HashSet(languageSpecificPrimitives); instantiationTypes.put("array", "Array"); @@ -138,41 +129,51 @@ public JavascriptClientCodegen() { typeMapping.put("object", "Object"); typeMapping.put("integer", "Number"); // binary not supported in JavaScript client right now, using String as a workaround - typeMapping.put("ByteArray", "String"); // I don't see ByteArray defined in the Swagger docs. + typeMapping.put("ByteArray", "String"); // I don't see ByteArray defined in the Swagger + // docs. typeMapping.put("binary", "String"); typeMapping.put("UUID", "String"); importMapping.clear(); - cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC).defaultValue("src")); - cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC)); - cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); - cliOptions.add(new CliOption(PROJECT_NAME, - "name of the project (Default: generated from info.title or \"swagger-js-client\")")); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, + CodegenConstants.SOURCE_FOLDER_DESC).defaultValue("src")); + cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, + CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC)); + cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, + CodegenConstants.INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, + CodegenConstants.API_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, + CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions + .add(new CliOption(PROJECT_NAME, + "name of the project (Default: generated from info.title or \"swagger-js-client\")")); cliOptions.add(new CliOption(MODULE_NAME, "module name for AMD, Node or globals (Default: generated from )")); - cliOptions.add(new CliOption(PROJECT_DESCRIPTION, - "description of the project (Default: using info.description or \"Client library of \")")); + cliOptions + .add(new CliOption( + PROJECT_DESCRIPTION, + "description of the project (Default: using info.description or \"Client library of \")")); cliOptions.add(new CliOption(PROJECT_VERSION, "version of the project (Default: using info.version or \"1.0.0\")")); cliOptions.add(new CliOption(PROJECT_LICENSE_NAME, "name of the license the project uses (Default: using info.license.name)")); - cliOptions.add(new CliOption(USE_PROMISES, - "use Promises as return values from the client API, instead of superagent callbacks") - .defaultValue(Boolean.FALSE.toString())); + cliOptions + .add(new CliOption(USE_PROMISES, + "use Promises as return values from the client API, instead of superagent callbacks") + .defaultValue(Boolean.FALSE.toString())); cliOptions.add(new CliOption(EMIT_MODEL_METHODS, - "generate getters and setters for model properties") - .defaultValue(Boolean.FALSE.toString())); - cliOptions.add(new CliOption(EMIT_JS_DOC, - "generate JSDoc comments") + "generate getters and setters for model properties").defaultValue(Boolean.FALSE + .toString())); + cliOptions.add(new CliOption(EMIT_JS_DOC, "generate JSDoc comments") .defaultValue(Boolean.TRUE.toString())); cliOptions.add(new CliOption(USE_INHERITANCE, "use JavaScript prototype chains & delegation for inheritance") .defaultValue(Boolean.TRUE.toString())); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") - .defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + "hides the timestamp when files were generated").defaultValue(Boolean.TRUE + .toString())); } @Override @@ -196,10 +197,13 @@ public void processOpts() { // default HIDE_GENERATION_TIMESTAMP to true if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.TRUE.toString()); + } else { + additionalProperties.put( + CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get( + CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } @@ -219,7 +223,8 @@ public void processOpts() { setProjectLicenseName(((String) additionalProperties.get(PROJECT_LICENSE_NAME))); } if (additionalProperties.containsKey(CodegenConstants.LOCAL_VARIABLE_PREFIX)) { - setLocalVariablePrefix((String) additionalProperties.get(CodegenConstants.LOCAL_VARIABLE_PREFIX)); + setLocalVariablePrefix((String) additionalProperties + .get(CodegenConstants.LOCAL_VARIABLE_PREFIX)); } if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); @@ -228,19 +233,21 @@ public void processOpts() { setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); } if (additionalProperties.containsKey(USE_PROMISES)) { - setUsePromises(Boolean.parseBoolean((String)additionalProperties.get(USE_PROMISES))); + setUsePromises(Boolean.parseBoolean((String) additionalProperties.get(USE_PROMISES))); } if (additionalProperties.containsKey(USE_INHERITANCE)) { - setUseInheritance(Boolean.parseBoolean((String)additionalProperties.get(USE_INHERITANCE))); + setUseInheritance(Boolean.parseBoolean((String) additionalProperties + .get(USE_INHERITANCE))); } else { supportsInheritance = true; supportsMixins = true; } if (additionalProperties.containsKey(EMIT_MODEL_METHODS)) { - setEmitModelMethods(Boolean.parseBoolean((String)additionalProperties.get(EMIT_MODEL_METHODS))); + setEmitModelMethods(Boolean.parseBoolean((String) additionalProperties + .get(EMIT_MODEL_METHODS))); } if (additionalProperties.containsKey(EMIT_JS_DOC)) { - setEmitJSDoc(Boolean.parseBoolean((String)additionalProperties.get(EMIT_JS_DOC))); + setEmitJSDoc(Boolean.parseBoolean((String) additionalProperties.get(EMIT_JS_DOC))); } } @@ -304,8 +311,10 @@ public void preprocessSwagger(Swagger swagger) { additionalProperties.put("modelDocPath", modelDocPath); supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); - supportingFiles.add(new SupportingFile("index.mustache", createPath(sourceFolder, invokerPackage), "index.js")); - supportingFiles.add(new SupportingFile("ApiClient.mustache", createPath(sourceFolder, invokerPackage), "ApiClient.js")); + supportingFiles.add(new SupportingFile("index.mustache", createPath(sourceFolder, + invokerPackage), "index.js")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", createPath(sourceFolder, + invokerPackage), "ApiClient.js")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("mocha.opts", "", "mocha.opts")); @@ -313,8 +322,8 @@ public void preprocessSwagger(Swagger swagger) { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -322,8 +331,10 @@ public String escapeReservedWord(String name) { /** * Concatenates an array of path segments into a path string. - * @param segments The path segments to concatenate. A segment may contain either of the file separator characters '\' or '/'. - * A segment is ignored if it is null, empty or ".". + * + * @param segments The path segments to concatenate. A segment may contain either of the file + * separator characters '\' or '/'. A segment is ignored if it is null, + * empty or ".". * @return A path string using the correct platform-specific file separator character. */ private String createPath(String... segments) { @@ -445,10 +456,11 @@ public String toModelTestFilename(String name) { @Override public String toVarName(String name) { // sanitize name - name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as "final" + name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as + // "final" - if("_".equals(name)) { - name = "_u"; + if ("_".equals(name)) { + name = "_u"; } // if it's all uppper case, do nothing @@ -476,7 +488,8 @@ public String toParamName(String name) { @Override public String toModelName(String name) { - name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as "final" + name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as + // "final" if (!StringUtils.isEmpty(modelNamePrefix)) { name = modelNamePrefix + "_" + name; @@ -493,14 +506,18 @@ public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { String modelName = "Model" + name; - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + modelName); return modelName; } // model name starts with number if (name.matches("^\\d.*")) { - String modelName = "Model" + name; // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + String modelName = "Model" + name; // e.g. 200Response => Model200Response (after + // camelize) + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + modelName); return modelName; } @@ -584,7 +601,7 @@ public String toDefaultValueWithParam(String name, Property p) { if (p instanceof RefProperty) { return " = " + type + ".constructFromObject(data['" + name + "']);"; } else { - return " = ApiClient.convertToType(data['" + name + "'], " + type + ");"; + return " = ApiClient.convertToType(data['" + name + "'], " + type + ");"; } } @@ -653,7 +670,7 @@ public void setParameterExampleValue(CodegenParameter p) { * @return Normalized type */ public String normalizeType(String type) { - return type.replaceAll("\\b(Boolean|Integer|Number|String|Date)\\b", "'$1'"); + return type.replaceAll("\\b(Boolean|Integer|Number|String|Date)\\b", "'$1'"); } @Override @@ -686,7 +703,8 @@ public String toOperationId(String operationId) { // 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); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + newOperationId); return newOperationId; } @@ -694,51 +712,56 @@ public String toOperationId(String operationId) { } @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); - if (op.returnType != null) { - op.returnType = normalizeType(op.returnType); - } - - //path is an unescaped variable in the mustache template api.mustache line 82 '<&path>' - op.path = sanitizePath(op.path); - - // Set vendor-extension to be used in template: - // x-codegen-hasMoreRequired - // x-codegen-hasMoreOptional - // x-codegen-hasRequiredParams - CodegenParameter lastRequired = null; - CodegenParameter lastOptional = null; - for (CodegenParameter p : op.allParams) { - if (p.required) { - lastRequired = p; - } else { - lastOptional = p; - } - } - for (CodegenParameter p : op.allParams) { - if (p == lastRequired) { - p.vendorExtensions.put("x-codegen-hasMoreRequired", false); - } else if (p == lastOptional) { - p.vendorExtensions.put("x-codegen-hasMoreOptional", false); - } else { - p.vendorExtensions.put("x-codegen-hasMoreRequired", true); - p.vendorExtensions.put("x-codegen-hasMoreOptional", true); - } - } - op.vendorExtensions.put("x-codegen-hasRequiredParams", lastRequired != null); - - return op; + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, + Map definitions, Swagger swagger) { + CodegenOperation op = + super.fromOperation(path, httpMethod, operation, definitions, swagger); + if (op.returnType != null) { + op.returnType = normalizeType(op.returnType); + } + + // path is an unescaped variable in the mustache template api.mustache line 82 '<&path>' + op.path = sanitizePath(op.path); + + // Set vendor-extension to be used in template: + // x-codegen-hasMoreRequired + // x-codegen-hasMoreOptional + // x-codegen-hasRequiredParams + CodegenParameter lastRequired = null; + CodegenParameter lastOptional = null; + for (CodegenParameter p : op.allParams) { + if (p.required) { + lastRequired = p; + } else { + lastOptional = p; + } + } + for (CodegenParameter p : op.allParams) { + if (p == lastRequired) { + p.vendorExtensions.put("x-codegen-hasMoreRequired", false); + } else if (p == lastOptional) { + p.vendorExtensions.put("x-codegen-hasMoreOptional", false); + } else { + p.vendorExtensions.put("x-codegen-hasMoreRequired", true); + p.vendorExtensions.put("x-codegen-hasMoreOptional", true); + } + } + op.vendorExtensions.put("x-codegen-hasRequiredParams", lastRequired != null); + + return op; } @Override public CodegenModel fromModel(String name, Model model, Map allDefinitions) { CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); - if (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) { + if (allDefinitions != null && codegenModel != null && codegenModel.parent != null + && codegenModel.hasEnums) { final Model parentModel = allDefinitions.get(codegenModel.parentSchema); - final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel, allDefinitions); - codegenModel = JavascriptClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); + final CodegenModel parentCodegenModel = + super.fromModel(codegenModel.parent, parentModel, allDefinitions); + codegenModel = + JavascriptClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); } if (model instanceof ArrayModel) { ArrayModel am = (ArrayModel) model; @@ -747,10 +770,11 @@ public CodegenModel fromModel(String name, Model model, Map allDe codegenModel.vendorExtensions.put("x-itemType", getSwaggerType(am.getItems())); } } else if (model instanceof ModelImpl) { - ModelImpl mm = (ModelImpl)model; + ModelImpl mm = (ModelImpl) model; if (mm.getAdditionalProperties() != null) { codegenModel.vendorExtensions.put("x-isMap", true); - codegenModel.vendorExtensions.put("x-itemType", getSwaggerType(mm.getAdditionalProperties())); + codegenModel.vendorExtensions.put("x-itemType", + getSwaggerType(mm.getAdditionalProperties())); } } @@ -758,10 +782,10 @@ public CodegenModel fromModel(String name, Model model, Map allDe } private String sanitizePath(String p) { - //prefer replace a ', instead of a fuLL URL encode for readability + // prefer replace a ', instead of a fuLL URL encode for readability return p.replaceAll("'", "%27"); } - + private String trimBrackets(String s) { if (s != null) { int beginIdx = s.charAt(0) == '[' ? 1 : 0; @@ -775,7 +799,7 @@ private String trimBrackets(String s) { private String getModelledType(String dataType) { return "module:" + (StringUtils.isEmpty(invokerPackage) ? "" : (invokerPackage + "/")) - + (StringUtils.isEmpty(modelPackage) ? "" : (modelPackage + "/")) + dataType; + + (StringUtils.isEmpty(modelPackage) ? "" : (modelPackage + "/")) + dataType; } /* @@ -801,8 +825,11 @@ else if (cp.containerType.equals("map")) } private boolean isModelledType(CodegenProperty cp) { - // N.B. enums count as modelled types, file is not modelled (SuperAgent uses some 3rd party library). - return cp.isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.datatype : cp.baseType); + // N.B. enums count as modelled types, file is not modelled (SuperAgent uses some 3rd party + // library). + return cp.isEnum + || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.datatype + : cp.baseType); } /* @@ -824,8 +851,11 @@ private String getJSDocType(CodegenParameter cp) { } private boolean isModelledType(CodegenParameter cp) { - // N.B. enums count as modelled types, file is not modelled (SuperAgent uses some 3rd party library). - return cp.isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.dataType : cp.baseType); + // N.B. enums count as modelled types, file is not modelled (SuperAgent uses some 3rd party + // library). + return cp.isEnum + || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.dataType + : cp.baseType); } /* @@ -869,7 +899,7 @@ public Map postProcessOperations(Map objs) { if (p.required) { argList.add(p.paramName); } else { - hasOptionalParams = true; + hasOptionalParams = true; } } if (hasOptionalParams) { @@ -878,7 +908,8 @@ public Map postProcessOperations(Map objs) { if (!usePromises) { argList.add("callback"); } - operation.vendorExtensions.put("x-codegen-argList", StringUtils.join(argList, ", ")); + operation.vendorExtensions + .put("x-codegen-argList", StringUtils.join(argList, ", ")); // Store JSDoc type specification into vendor-extension: x-jsdoc-type. for (CodegenParameter cp : operation.allParams) { @@ -902,10 +933,14 @@ public Map postProcessModels(Map objs) { CodegenModel cm = (CodegenModel) mo.get("model"); // Collect each model's required property names in *document order*. - // NOTE: can't use 'mandatory' as it is built from ModelImpl.getRequired(), which sorts names - // alphabetically and in any case the document order of 'required' and 'properties' can differ. + // NOTE: can't use 'mandatory' as it is built from ModelImpl.getRequired(), which sorts + // names + // alphabetically and in any case the document order of 'required' and 'properties' can + // differ. List required = new ArrayList<>(); - List allRequired = supportsInheritance || supportsMixins ? new ArrayList() : required; + List allRequired = + supportsInheritance || supportsMixins ? new ArrayList() + : required; cm.vendorExtensions.put("x-required", required); cm.vendorExtensions.put("x-all-required", allRequired); @@ -947,20 +982,21 @@ public Map postProcessModels(Map objs) { @Override protected boolean needToImport(String type) { - return !defaultIncludes.contains(type) - && !languageSpecificPrimitives.contains(type); - } -/* - @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", ""); + return !defaultIncludes.contains(type) && !languageSpecificPrimitives.contains(type); } -*/ - private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { + /* + @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", ""); + } + */ + + 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 @@ -984,7 +1020,8 @@ private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, Code Iterator iterator = codegenProperties.iterator(); while (iterator.hasNext()) { CodegenProperty codegenProperty = iterator.next(); - if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) { + 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(); @@ -994,10 +1031,11 @@ private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, Code } } - if(removedChildEnum) { - // If we removed an entry from this model's vars, we need to ensure hasMore is updated + 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) { + for (CodegenProperty codegenProperty : codegenProperties) { count += 1; codegenProperty.hasMore = (count < numVars) ? true : false; } @@ -1008,10 +1046,12 @@ private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, Code return codegenModel; } - private static String sanitizePackageName(String packageName) { // FIXME parameter should not be assigned. Also declare it as "final" + private static String sanitizePackageName(String packageName) { // FIXME parameter should not be + // assigned. Also declare it as + // "final" packageName = packageName.trim(); packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_"); - if(Strings.isNullOrEmpty(packageName)) { + if (Strings.isNullOrEmpty(packageName)) { return "invalidPackageName"; } return packageName; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java index 779f51d178b..c1c88ae6985 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java @@ -15,22 +15,16 @@ public JavascriptClosureAngularClientCodegen() { super(); supportsInheritance = false; - setReservedWordsLowerCase(Arrays.asList("abstract", - "continue", "for", "new", "switch", "assert", "default", "if", - "package", "synchronized", "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", "const", "super", "while")); - - languageSpecificPrimitives = new HashSet(Arrays.asList( - "string", - "boolean", - "number", - "Object", - "Blob", - "Date")); + setReservedWordsLowerCase(Arrays.asList("abstract", "continue", "for", "new", "switch", + "assert", "default", "if", "package", "synchronized", "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", "const", "super", "while")); + + languageSpecificPrimitives = + new HashSet(Arrays.asList("string", "boolean", "number", "Object", "Blob", + "Date")); instantiationTypes.put("array", "Array"); typeMapping = new HashMap(); @@ -56,11 +50,7 @@ public JavascriptClosureAngularClientCodegen() { typeMapping.put("DateTime", "Date"); importMapping = new HashMap(); - defaultIncludes = new HashSet(Arrays.asList( - "Object", - "Array", - "Blob" - )); + defaultIncludes = new HashSet(Arrays.asList("Object", "Array", "Blob")); typeMapping.put("binary", "string"); @@ -71,8 +61,9 @@ public JavascriptClosureAngularClientCodegen() { apiPackage = "API.Client"; modelPackage = "API.Client"; - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") - .defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + "hides the timestamp when files were generated").defaultValue(Boolean.TRUE + .toString())); } @Override @@ -81,7 +72,8 @@ public void processOpts() { // default HIDE_GENERATION_TIMESTAMP to true if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.TRUE.toString()); } } @@ -92,8 +84,8 @@ public String getName() { @Override public String getHelp() { - return "Generates a Javascript AngularJS client library (beta) annotated with Google Closure Compiler annotations" + - "(https://developers.google.com/closure/compiler/docs/js-for-compiler?hl=en)"; + return "Generates a Javascript AngularJS client library (beta) annotated with Google Closure Compiler annotations" + + "(https://developers.google.com/closure/compiler/docs/js-for-compiler?hl=en)"; } @Override @@ -102,8 +94,8 @@ public CodegenType getTag() { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -121,7 +113,7 @@ public String modelFileFolder() { @Override public String toVarName(String name) { // sanitize name - name = sanitizeName(name); + name = sanitizeName(name); // replace - with _ e.g. created-at => created_at name = name.replaceAll("-", "_"); @@ -159,7 +151,8 @@ public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } @@ -183,17 +176,15 @@ public String getTypeDeclaration(Property p) { } else if (p instanceof MapProperty) { MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); - return "Object"; + return "Object"; } else if (p instanceof FileProperty) { return "Object"; } String type = super.getTypeDeclaration(p); - if (type.equals("boolean") || - type.equals("Date") || - type.equals("number") || - type.equals("string")) { + if (type.equals("boolean") || type.equals("Date") || type.equals("number") + || type.equals("string")) { return type; - } + } return apiPackage + "." + type; } @@ -232,7 +223,8 @@ public Map postProcessModels(Map objs) { @Override public Map postProcessOperations(Map objs) { if (objs.get("imports") instanceof List) { - List> imports = (ArrayList>)objs.get("imports"); + List> imports = + (ArrayList>) objs.get("imports"); Collections.sort(imports, new Comparator>() { public int compare(Map o1, Map o2) { return o1.get("import").compareTo(o2.get("import")); @@ -255,7 +247,8 @@ public String toOperationId(String operationId) { // 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); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + newOperationId); return newOperationId; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java index 5dd35ba1b0f..adccc134c8a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java @@ -10,24 +10,23 @@ import java.util.Map; import java.util.TreeMap; -public class LumenServerCodegen extends AbstractPhpCodegen -{ - @SuppressWarnings("hiding") +public class LumenServerCodegen extends AbstractPhpCodegen { + @SuppressWarnings("hiding") protected String apiVersion = "1.0.0"; - + /** * Configures the type of generator. * - * @return the CodegenType for this generator - * @see io.swagger.codegen.CodegenType + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType */ public CodegenType getTag() { return CodegenType.SERVER; } /** - * Configures a friendly name for the generator. This will be used by the generator - * to select the library with the -l flag. + * Configures a friendly name for the generator. This will be used by the generator to select + * the library with the -l flag. * * @return the friendly name for the generator */ @@ -36,8 +35,8 @@ public String getName() { } /** - * Returns human-friendly help for the generator. Provide the consumer with help - * tips, parameters here + * Returns human-friendly help for the generator. Provide the consumer with help tips, + * parameters here * * @return A string value for the help message */ @@ -83,18 +82,31 @@ public LumenServerCodegen() { * entire object tree available. If the input file has a suffix of `.mustache * it will be processed by the template engine. Otherwise, it will be copied */ - supportingFiles.add(new SupportingFile("composer.mustache", packagePath + File.separator + srcBasePath, "composer.json")); - supportingFiles.add(new SupportingFile("readme.md", packagePath + File.separator + srcBasePath, "readme.md")); - supportingFiles.add(new SupportingFile("app.php", packagePath + File.separator + srcBasePath + File.separator + "bootstrap", "app.php")); - supportingFiles.add(new SupportingFile("index.php", packagePath + File.separator + srcBasePath + File.separator + "public", "index.php")); - supportingFiles.add(new SupportingFile("User.php", packagePath + File.separator + srcBasePath + File.separator + "app", "User.php")); - supportingFiles.add(new SupportingFile("Kernel.php", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Console", "Kernel.php")); - supportingFiles.add(new SupportingFile("Handler.php", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Exceptions", "Handler.php")); - supportingFiles.add(new SupportingFile("routes.mustache", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Http", "routes.php")); - - supportingFiles.add(new SupportingFile("Controller.php", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator, "Controller.php")); - supportingFiles.add(new SupportingFile("Authenticate.php", packagePath + File.separator + srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "Authenticate.php")); - + supportingFiles.add(new SupportingFile("composer.mustache", packagePath + File.separator + + srcBasePath, "composer.json")); + supportingFiles.add(new SupportingFile("readme.md", packagePath + File.separator + + srcBasePath, "readme.md")); + supportingFiles.add(new SupportingFile("app.php", packagePath + File.separator + + srcBasePath + File.separator + "bootstrap", "app.php")); + supportingFiles.add(new SupportingFile("index.php", packagePath + File.separator + + srcBasePath + File.separator + "public", "index.php")); + supportingFiles.add(new SupportingFile("User.php", packagePath + File.separator + + srcBasePath + File.separator + "app", "User.php")); + supportingFiles.add(new SupportingFile("Kernel.php", packagePath + File.separator + + srcBasePath + File.separator + "app" + File.separator + "Console", "Kernel.php")); + supportingFiles.add(new SupportingFile("Handler.php", packagePath + File.separator + + srcBasePath + File.separator + "app" + File.separator + "Exceptions", + "Handler.php")); + supportingFiles.add(new SupportingFile("routes.mustache", packagePath + File.separator + + srcBasePath + File.separator + "app" + File.separator + "Http", "routes.php")); + + supportingFiles.add(new SupportingFile("Controller.php", packagePath + File.separator + + srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + + "Controllers" + File.separator, "Controller.php")); + supportingFiles.add(new SupportingFile("Authenticate.php", packagePath + File.separator + + srcBasePath + File.separator + "app" + File.separator + "Http" + File.separator + + "Middleware" + File.separator, "Authenticate.php")); + } // override with any special post-processing @@ -104,8 +116,8 @@ public Map postProcessOperations(Map objs) { Map objectMap = (Map) objs.get("operations"); @SuppressWarnings("unchecked") List operations = (List) objectMap.get("operation"); - - // sort the endpoints in ascending to avoid the route priority issure. + + // sort the endpoints in ascending to avoid the route priority issure. // https://github.com/swagger-api/swagger-codegen/issues/2643 Collections.sort(operations, new Comparator() { @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java index ace3ccaa4e2..91312a007f8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java @@ -58,13 +58,12 @@ public NancyFXServerCodegen() { outputFolder = "generated-code" + File.separator + getName(); apiTemplateFiles.put("api.mustache", ".cs"); - // Early versions use no prefix for interfaces. Defaulting to I- common practice would break existing users. + // Early versions use no prefix for interfaces. Defaulting to I- common practice would break + // existing users. setInterfacePrefix(""); // contextually reserved words - setReservedWordsLowerCase( - asList("var", "async", "await", "dynamic", "yield") - ); + setReservedWordsLowerCase(asList("var", "async", "await", "dynamic", "yield")); cliOptions.clear(); @@ -75,13 +74,16 @@ public NancyFXServerCodegen() { addOption(INTERFACE_PREFIX, INTERFACE_PREFIX_DESC, interfacePrefix); // CLI Switches - addSwitch(SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_BY_REQUIRED_FLAG_DESC, sortParamsByRequiredFlag); + addSwitch(SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_BY_REQUIRED_FLAG_DESC, + sortParamsByRequiredFlag); addSwitch(OPTIONAL_PROJECT_FILE, OPTIONAL_PROJECT_FILE_DESC, optionalProjectFileFlag); addSwitch(USE_DATETIME_OFFSET, USE_DATETIME_OFFSET_DESC, useDateTimeOffsetFlag); addSwitch(USE_COLLECTION, USE_COLLECTION_DESC, useCollection); addSwitch(RETURN_ICOLLECTION, RETURN_ICOLLECTION_DESC, returnICollection); - addSwitch(IMMUTABLE_OPTION, "Enabled by default. If disabled generates model classes with setters", true); - addSwitch(USE_BASE_PATH, "Enabled by default. If disabled, module paths will not mirror api base path", true); + addSwitch(IMMUTABLE_OPTION, + "Enabled by default. If disabled generates model classes with setters", true); + addSwitch(USE_BASE_PATH, + "Enabled by default. If disabled, module paths will not mirror api base path", true); typeMapping.putAll(nodaTimeTypesMappings()); languageSpecificPrimitives.addAll(nodaTimePrimitiveTypes()); @@ -107,16 +109,21 @@ public String getHelp() { public void processOpts() { super.processOpts(); - apiPackage = isNullOrEmpty(packageName) ? API_NAMESPACE : packageName + "." + API_NAMESPACE; - modelPackage = isNullOrEmpty(packageName) ? MODEL_NAMESPACE : packageName + "." + MODEL_NAMESPACE; + apiPackage = isNullOrEmpty(packageName) ? API_NAMESPACE : packageName + "." + API_NAMESPACE; + modelPackage = + isNullOrEmpty(packageName) ? MODEL_NAMESPACE : packageName + "." + MODEL_NAMESPACE; - supportingFiles.add(new SupportingFile("parameters.mustache", sourceFile("Utils"), "Parameters.cs")); - supportingFiles.add(new SupportingFile("packages.config.mustache", sourceFolder(), "packages.config")); - supportingFiles.add(new SupportingFile("nuspec.mustache", sourceFolder(), packageName + ".nuspec")); + supportingFiles.add(new SupportingFile("parameters.mustache", sourceFile("Utils"), + "Parameters.cs")); + supportingFiles.add(new SupportingFile("packages.config.mustache", sourceFolder(), + "packages.config")); + supportingFiles.add(new SupportingFile("nuspec.mustache", sourceFolder(), packageName + + ".nuspec")); if (optionalProjectFileFlag) { supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln")); - supportingFiles.add(new SupportingFile("Project.mustache", sourceFolder(), packageName + ".csproj")); + supportingFiles.add(new SupportingFile("Project.mustache", sourceFolder(), packageName + + ".csproj")); } additionalProperties.put("packageGuid", packageGuid); @@ -140,18 +147,23 @@ private void processImportedMappings() { for (final Entry entry : ImmutableSet.copyOf(importMapping.entrySet())) { final String model = entry.getKey(); final String[] namespaceInfo = entry.getValue().split("\\s"); - final String[] namespace = (namespaceInfo.length > 0 ? namespaceInfo[0].trim() : "").split(":"); + final String[] namespace = + (namespaceInfo.length > 0 ? namespaceInfo[0].trim() : "").split(":"); final String namespaceName = namespace.length > 0 ? namespace[0].trim() : null; final String modelClass = namespace.length > 1 ? namespace[1].trim() : null; final String assembly = namespaceInfo.length > 1 ? namespaceInfo[1].trim() : null; - final String assemblyVersion = namespaceInfo.length > 2 ? namespaceInfo[2].trim() : null; - final String assemblyFramework = namespaceInfo.length > 3 ? namespaceInfo[3].trim() : "net45"; + final String assemblyVersion = + namespaceInfo.length > 2 ? namespaceInfo[2].trim() : null; + final String assemblyFramework = + namespaceInfo.length > 3 ? namespaceInfo[3].trim() : "net45"; if (isNullOrEmpty(model) || isNullOrEmpty(namespaceName)) { - log.warn(String.format("Could not import: '%s' - invalid namespace: '%s'", model, entry.getValue())); + log.warn(String.format("Could not import: '%s' - invalid namespace: '%s'", model, + entry.getValue())); importMapping.remove(model); } else { - log.info(String.format("Importing: '%s' from '%s' namespace.", model, namespaceName)); + log.info(String + .format("Importing: '%s' from '%s' namespace.", model, namespaceName)); importMapping.put(model, namespaceName); } if (!isNullOrEmpty(modelClass)) { @@ -209,7 +221,7 @@ protected void processOperation(final CodegenOperation operation) { @Override public Map postProcessAllModels(final Map models) { - final Map processed = super.postProcessAllModels(models); + final Map processed = super.postProcessAllModels(models); postProcessParentModels(models); return processed; } @@ -247,7 +259,8 @@ private CodegenModel modelByName(final String name, final Map mo return null; } - private void processParentPropertiesInChildModel(final CodegenModel parent, final CodegenModel child) { + private void processParentPropertiesInChildModel(final CodegenModel parent, + final CodegenModel child) { final Map childPropertiesByName = new HashMap<>(child.vars.size()); for (final CodegenProperty property : child.vars) { childPropertiesByName.put(property.name, property); @@ -256,7 +269,7 @@ private void processParentPropertiesInChildModel(final CodegenModel parent, fina for (final CodegenProperty property : parent.vars) { final CodegenProperty duplicatedByParent = childPropertiesByName.get(property.name); if (duplicatedByParent != null) { - log.info(String.format("Property: '%s' in '%s' model is inherited from '%s'" , + log.info(String.format("Property: '%s' in '%s' model is inherited from '%s'", property.name, child.classname, parent.classname)); duplicatedByParent.isInherited = true; final CodegenProperty parentVar = duplicatedByParent.clone(); @@ -287,11 +300,9 @@ public String toEnumVarName(final String name, final String datatype) { return "Empty"; } - final String enumName = camelize( - sanitizeName(name) - .replaceFirst("^_", "") - .replaceFirst("_$", "") - .replaceAll("-", "_")); + final String enumName = + camelize(sanitizeName(name).replaceFirst("^_", "").replaceFirst("_$", "") + .replaceAll("-", "_")); final String result; if (enumName.matches("\\d.*")) { result = "_" + enumName; @@ -324,8 +335,9 @@ public String toModelImport(final String name) { final String result; if (modelNameMapping.containsValue(name)) { final String modelName = modelNameMapping.inverse().get(name); - result = importMapping.containsKey(modelName) ? - importMapping.get(modelName) : super.toModelImport(name); + result = + importMapping.containsKey(modelName) ? importMapping.get(modelName) : super + .toModelImport(name); } else if (importMapping.containsKey(name)) { result = importMapping.get(name); } else { @@ -339,14 +351,15 @@ public String toModelImport(final String name) { public String toModelName(final String name) { final String modelName = super.toModelName(name); final String mappedModelName = modelNameMapping.get(modelName); - return isNullOrEmpty(mappedModelName) ? modelName: mappedModelName; + return isNullOrEmpty(mappedModelName) ? modelName : mappedModelName; } @Override public void preprocessSwagger(final Swagger swagger) { additionalProperties.put("packageContext", sanitizeName(swagger.getBasePath())); final Object basePathOption = additionalProperties.get(USE_BASE_PATH); - additionalProperties.put("baseContext", basePathOption == null ? swagger.getBasePath() : "/"); + additionalProperties.put("baseContext", basePathOption == null ? swagger.getBasePath() + : "/"); } @Override @@ -374,16 +387,15 @@ private static Predicate timeProperty() { return new Predicate() { @Override public boolean apply(Property property) { - return property instanceof StringProperty && "time".equalsIgnoreCase(property.getFormat()); + return property instanceof StringProperty + && "time".equalsIgnoreCase(property.getFormat()); } }; } private static Map nodaTimeTypesMappings() { - return ImmutableMap.of( - "time", "LocalTime?", - "date", "ZonedDateTime?", - "datetime", "ZonedDateTime?"); + return ImmutableMap.of("time", "LocalTime?", "date", "ZonedDateTime?", "datetime", + "ZonedDateTime?"); } private static Set nodaTimePrimitiveTypes() { @@ -395,7 +407,7 @@ private class DependencyInfo { private final String framework; private DependencyInfo(final String version, final String framework) { - this.version = version; + this.version = version; this.framework = framework; } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java index bd1d988e90a..371915dc6d2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java @@ -53,9 +53,8 @@ public NodeJSServerCodegen() { * as with models, add multiple entries with different extensions for multiple files per * class */ - apiTemplateFiles.put( - "controller.mustache", // the template to use - ".js"); // the extension for each file to write + apiTemplateFiles.put("controller.mustache", // the template to use + ".js"); // the extension for each file to write /* * Template Location. This is the location which templates will be read from. The generator @@ -66,14 +65,11 @@ public NodeJSServerCodegen() { /* * Reserved words. Override this with reserved words specific to your language */ - setReservedWordsLowerCase( - Arrays.asList( - "break", "case", "class", "catch", "const", "continue", "debugger", - "default", "delete", "do", "else", "export", "extends", "finally", - "for", "function", "if", "import", "in", "instanceof", "let", "new", - "return", "super", "switch", "this", "throw", "try", "typeof", "var", - "void", "while", "with", "yield") - ); + setReservedWordsLowerCase(Arrays.asList("break", "case", "class", "catch", "const", + "continue", "debugger", "default", "delete", "do", "else", "export", "extends", + "finally", "for", "function", "if", "import", "in", "instanceof", "let", "new", + "return", "super", "switch", "this", "throw", "try", "typeof", "var", "void", + "while", "with", "yield")); /* * Additional Properties. These values can be passed to the templates and @@ -82,15 +78,20 @@ public NodeJSServerCodegen() { additionalProperties.put("apiVersion", apiVersion); additionalProperties.put("serverPort", serverPort); - cliOptions.add(CliOption.newBoolean(GOOGLE_CLOUD_FUNCTIONS, - "When specified, it will generate the code which runs within Google Cloud Functions " - + "instead of standalone Node.JS server. See " - + "https://cloud.google.com/functions/docs/quickstart for the details of how to " - + "deploy the generated code.")); - cliOptions.add(new CliOption(EXPORTED_NAME, - "When the generated code will be deployed to Google Cloud Functions, this option can be " - + "used to update the name of the exported function. By default, it refers to the " - + "basePath. This does not affect normal standalone nodejs server code.")); + cliOptions + .add(CliOption + .newBoolean( + GOOGLE_CLOUD_FUNCTIONS, + "When specified, it will generate the code which runs within Google Cloud Functions " + + "instead of standalone Node.JS server. See " + + "https://cloud.google.com/functions/docs/quickstart for the details of how to " + + "deploy the generated code.")); + cliOptions + .add(new CliOption( + EXPORTED_NAME, + "When the generated code will be deployed to Google Cloud Functions, this option can be " + + "used to update the name of the exported function. By default, it refers to the " + + "basePath. This does not affect normal standalone nodejs server code.")); } @Override @@ -110,8 +111,8 @@ public CodegenType getTag() { } /** - * Configures a friendly name for the generator. This will be used by the generator - * to select the library with the -l flag. + * Configures a friendly name for the generator. This will be used by the generator to select + * the library with the -l flag. * * @return the friendly name for the generator */ @@ -121,15 +122,15 @@ public String getName() { } /** - * Returns human-friendly help for the generator. Provide the consumer with help - * tips, parameters here + * Returns human-friendly help for the generator. Provide the consumer with help tips, + * parameters here * * @return A string value for the help message */ @Override public String getHelp() { - return "Generates a nodejs server library using the swagger-tools project. By default, " + - "it will also generate service classes--which you can disable with the `-Dnoservice` environment variable."; + return "Generates a nodejs server library using the swagger-tools project. By default, " + + "it will also generate service classes--which you can disable with the `-Dnoservice` environment variable."; } @Override @@ -146,21 +147,21 @@ public String toApiFilename(String name) { } /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping - * those terms here. This logic is only called if a variable matches the reserved words + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping those terms + * here. This logic is only called if a variable matches the reserved words * * @return the escaped term */ @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; } /** - * Location to write api files. You can use the apiPackage() as defined when the class is + * Location to write api files. You can use the apiPackage() as defined when the class is * instantiated */ @Override @@ -207,7 +208,7 @@ public Map postProcessOperations(Map objs) { } if (operation.examples != null && !operation.examples.isEmpty()) { // Leave application/json* items only - for (Iterator> it = operation.examples.iterator(); it.hasNext(); ) { + for (Iterator> it = operation.examples.iterator(); it.hasNext();) { final Map example = it.next(); final String contentType = example.get("contentType"); if (contentType == null || !contentType.startsWith("application/json")) { @@ -258,12 +259,12 @@ public void processOpts() { super.processOpts(); if (additionalProperties.containsKey(GOOGLE_CLOUD_FUNCTIONS)) { - setGoogleCloudFunctions( - Boolean.valueOf(additionalProperties.get(GOOGLE_CLOUD_FUNCTIONS).toString())); + setGoogleCloudFunctions(Boolean.valueOf(additionalProperties + .get(GOOGLE_CLOUD_FUNCTIONS).toString())); } if (additionalProperties.containsKey(EXPORTED_NAME)) { - setExportedName((String)additionalProperties.get(EXPORTED_NAME)); + setExportedName((String) additionalProperties.get(EXPORTED_NAME)); } /* @@ -272,13 +273,10 @@ public void processOpts() { * it will be processed by the template engine. Otherwise, it will be copied */ // supportingFiles.add(new SupportingFile("controller.mustache", - // "controllers", - // "controller.js") + // "controllers", + // "controller.js") // ); - supportingFiles.add(new SupportingFile("swagger.mustache", - "api", - "swagger.yaml") - ); + supportingFiles.add(new SupportingFile("swagger.mustache", "api", "swagger.yaml")); if (getGoogleCloudFunctions()) { writeOptional(outputFolder, new SupportingFile("index-gcf.mustache", "", "index.js")); } else { @@ -287,9 +285,8 @@ public void processOpts() { writeOptional(outputFolder, new SupportingFile("package.mustache", "", "package.json")); writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); if (System.getProperty("noservice") == null) { - apiTemplateFiles.put( - "service.mustache", // the template to use - "Service.js"); // the extension for each file to write + apiTemplateFiles.put("service.mustache", // the template to use + "Service.js"); // the extension for each file to write } } @@ -310,12 +307,9 @@ public void preprocessSwagger(Swagger swagger) { if (info.getTitle() != null) { // when info.title is defined, use it for projectName // used in package.json - projectName = info.getTitle() - .replaceAll("[^a-zA-Z0-9]", "-") - .replaceAll("^[-]*", "") - .replaceAll("[-]*$", "") - .replaceAll("[-]{2,}", "-") - .toLowerCase(); + projectName = + info.getTitle().replaceAll("[^a-zA-Z0-9]", "-").replaceAll("^[-]*", "") + .replaceAll("[-]*$", "").replaceAll("[-]{2,}", "-").toLowerCase(); this.additionalProperties.put("projectName", projectName); } } @@ -326,34 +320,36 @@ public void preprocessSwagger(Swagger swagger) { if (!host.endsWith(".cloudfunctions.net")) { LOGGER.warn("Host " + host + " seems not matching with cloudfunctions.net URL."); } - if (!additionalProperties.containsKey(EXPORTED_NAME)) { + if (!additionalProperties.containsKey(EXPORTED_NAME)) { String basePath = swagger.getBasePath(); if (basePath == null || basePath.equals("/")) { LOGGER.warn("Cannot find the exported name properly. Using 'openapi' as the exported name"); basePath = "/openapi"; } additionalProperties.put(EXPORTED_NAME, basePath.substring(1)); - } + } } // need vendor extensions for x-swagger-router-controller Map paths = swagger.getPaths(); - if(paths != null) { - for(String pathname : paths.keySet()) { + if (paths != null) { + for (String pathname : paths.keySet()) { Path path = paths.get(pathname); Map operationMap = path.getOperationMap(); - if(operationMap != null) { - for(HttpMethod method : operationMap.keySet()) { + if (operationMap != null) { + for (HttpMethod method : operationMap.keySet()) { Operation operation = operationMap.get(method); String tag = "default"; - if(operation.getTags() != null && operation.getTags().size() > 0) { + if (operation.getTags() != null && operation.getTags().size() > 0) { tag = toApiName(operation.getTags().get(0)); } - if(operation.getOperationId() == null) { - operation.setOperationId(getOrGenerateOperationId(operation, pathname, method.toString())); + if (operation.getOperationId() == null) { + operation.setOperationId(getOrGenerateOperationId(operation, pathname, + method.toString())); } - if(operation.getVendorExtensions().get("x-swagger-router-controller") == null) { - operation.getVendorExtensions().put("x-swagger-router-controller", sanitizeTag(tag)); + if (operation.getVendorExtensions().get("x-swagger-router-controller") == null) { + operation.getVendorExtensions().put("x-swagger-router-controller", + sanitizeTag(tag)); } } } @@ -361,20 +357,22 @@ public void preprocessSwagger(Swagger swagger) { } } - @Override + @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { + Swagger swagger = (Swagger) objs.get("swagger"); + if (swagger != null) { try { SimpleModule module = new SimpleModule(); module.addSerializer(Double.class, new JsonSerializer() { @Override public void serialize(Double val, JsonGenerator jgen, - SerializerProvider provider) throws IOException, JsonProcessingException { + SerializerProvider provider) throws IOException, + JsonProcessingException { jgen.writeNumber(new BigDecimal(val)); } }); - objs.put("swagger-yaml", Yaml.mapper().registerModule(module).writeValueAsString(swagger)); + objs.put("swagger-yaml", + Yaml.mapper().registerModule(module).writeValueAsString(swagger)); } catch (JsonProcessingException e) { LOGGER.error(e.getMessage(), e); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index 4598113c370..4cd8b980fd9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -24,7 +24,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String GIT_REPO_URL = "gitRepoURL"; public static final String DEFAULT_LICENSE = "Proprietary"; public static final String CORE_DATA = "coreData"; - + protected Set foundationClasses = new HashSet(); protected String podName = "SwaggerClient"; protected String podVersion = "1.0.0"; @@ -41,7 +41,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { protected String apiFilesPath = "Api/"; protected boolean generateCoreData = false; - + protected Set advancedMapingTypes = new HashSet(); public ObjcClientCodegen() { @@ -117,58 +117,54 @@ public ObjcClientCodegen() { typeMapping.put("password", "NSString"); // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm - setReservedWordsLowerCase( - Arrays.asList( - // local variable names in API methods (endpoints) - "resourcePath", "pathParams", "queryParams", "headerParams", - "responseContentType", "requestContentType", "authSettings", - "formParams", "localVarFiles", "bodyParam", - // objc reserved words - "auto", "else", "long", "switch", - "break", "enum", "register", "typedef", - "case", "extern", "return", "union", - "char", "float", "short", "unsigned", - "const", "for", "signed", "void", - "continue", "goto", "sizeof", "volatile", - "default", "if", "id", "static", "while", - "do", "int", "struct", "_Packed", - "double", "protocol", "interface", "implementation", - "NSObject", "NSInteger", "NSNumber", "CGFloat", - "property", "nonatomic", "retain", "strong", - "weak", "unsafe_unretained", "readwrite", "readonly", - "description" - )); + setReservedWordsLowerCase(Arrays.asList( + // local variable names in API methods (endpoints) + "resourcePath", "pathParams", "queryParams", "headerParams", + "responseContentType", + "requestContentType", + "authSettings", + "formParams", + "localVarFiles", + "bodyParam", + // objc reserved words + "auto", "else", "long", "switch", "break", "enum", "register", "typedef", "case", + "extern", "return", "union", "char", "float", "short", "unsigned", "const", "for", + "signed", "void", "continue", "goto", "sizeof", "volatile", "default", "if", "id", + "static", "while", "do", "int", "struct", "_Packed", "double", "protocol", + "interface", "implementation", "NSObject", "NSInteger", "NSNumber", "CGFloat", + "property", "nonatomic", "retain", "strong", "weak", "unsafe_unretained", + "readwrite", "readonly", "description")); importMapping = new HashMap(); - foundationClasses = new HashSet( - Arrays.asList( - "NSNumber", - "NSObject", - "NSString", - "NSDate", - "NSData", - "NSURL", - "NSDictionary") - ); + foundationClasses = + new HashSet(Arrays.asList("NSNumber", "NSObject", "NSString", "NSDate", + "NSData", "NSURL", "NSDictionary")); instantiationTypes.put("array", "NSMutableArray"); instantiationTypes.put("map", "NSMutableDictionary"); cliOptions.clear(); - cliOptions.add(new CliOption(CORE_DATA, "Should generate core data models").defaultValue("false")); - cliOptions.add(new CliOption(CLASS_PREFIX, "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`).`") - .defaultValue("SWG")); + cliOptions.add(new CliOption(CORE_DATA, "Should generate core data models") + .defaultValue("false")); + cliOptions + .add(new CliOption(CLASS_PREFIX, + "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`).`") + .defaultValue("SWG")); cliOptions.add(new CliOption(POD_NAME, "cocoapods package name (convention: CameCase).") .defaultValue("SwaggerClient")); cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "cocoapods package version.") .defaultValue("1.0.0")); - cliOptions.add(new CliOption(AUTHOR_NAME, "Name to use in the podspec file.").defaultValue("Swagger")); - cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io")); - cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.") + cliOptions.add(new CliOption(AUTHOR_NAME, "Name to use in the podspec file.") + .defaultValue("Swagger")); + cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.") + .defaultValue("apiteam@swagger.io")); + cliOptions.add(new CliOption(GIT_REPO_URL, + "URL for the git repo where this podspec should point to.") .defaultValue("https://github.com/swagger-api/swagger-codegen")); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") - .defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + "hides the timestamp when files were generated").defaultValue(Boolean.TRUE + .toString())); } @Override @@ -192,10 +188,13 @@ public void processOpts() { // default HIDE_GENERATION_TIMESTAMP to true if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.TRUE.toString()); + } else { + additionalProperties.put( + CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get( + CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } if (additionalProperties.containsKey(POD_NAME)) { @@ -208,7 +207,7 @@ public void processOpts() { if (additionalProperties.containsKey(CORE_DATA)) { Object coreData = additionalProperties.get(CORE_DATA); - if(((String)coreData).equalsIgnoreCase("true")) { + if (((String) coreData).equalsIgnoreCase("true")) { generateCoreData = true; } } @@ -228,11 +227,13 @@ public void processOpts() { setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL)); } - if(generateCoreData) { + if (generateCoreData) { modelTemplateFiles.put("NSManagedObject-header.mustache", "ManagedObject.h"); modelTemplateFiles.put("NSManagedObject-body.mustache", "ManagedObject.m"); - modelTemplateFiles.put("NSManagedObjectBuilder-header.mustache", "ManagedObjectBuilder.h"); - modelTemplateFiles.put("NSManagedObjectBuilder-body.mustache", "ManagedObjectBuilder.m"); + modelTemplateFiles.put("NSManagedObjectBuilder-header.mustache", + "ManagedObjectBuilder.h"); + modelTemplateFiles + .put("NSManagedObjectBuilder-body.mustache", "ManagedObjectBuilder.m"); } additionalProperties.put(POD_NAME, podName); @@ -251,36 +252,66 @@ public void processOpts() { modelPackage = podName; apiPackage = podName; - supportingFiles.add(new SupportingFile("Object-header.mustache", coreFileFolder(), classPrefix + "Object.h")); - supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m")); - supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h")); - supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m")); - supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h")); - supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h")); - supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m")); - supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h")); - supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m")); - supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h")); - supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m")); - supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h")); - supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", coreFileFolder(), classPrefix + "Configuration.h")); - supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.m")); - supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.h")); - supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.h")); - supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.m")); - supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h")); + supportingFiles.add(new SupportingFile("Object-header.mustache", coreFileFolder(), + classPrefix + "Object.h")); + supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), + classPrefix + "Object.m")); + supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", + coreFileFolder(), classPrefix + "QueryParamCollection.h")); + supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", + coreFileFolder(), classPrefix + "QueryParamCollection.m")); + supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), + classPrefix + "ApiClient.h")); + supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), + classPrefix + "ApiClient.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", + coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", + coreFileFolder(), classPrefix + "JSONRequestSerializer.h")); + supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", + coreFileFolder(), classPrefix + "ResponseDeserializer.m")); + supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", + coreFileFolder(), classPrefix + "ResponseDeserializer.h")); + supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), + classPrefix + "Sanitizer.m")); + supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), + classPrefix + "Sanitizer.h")); + supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), + classPrefix + "Logger.m")); + supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), + classPrefix + "Logger.h")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", + coreFileFolder(), "JSONValueTransformer+ISO8601.m")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", + coreFileFolder(), "JSONValueTransformer+ISO8601.h")); + supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", coreFileFolder(), + classPrefix + "Configuration.h")); + supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", + coreFileFolder(), classPrefix + "DefaultConfiguration.m")); + supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", + coreFileFolder(), classPrefix + "DefaultConfiguration.h")); + supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", + coreFileFolder(), classPrefix + "BasicAuthTokenProvider.h")); + supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", + coreFileFolder(), classPrefix + "BasicAuthTokenProvider.m")); + supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), + classPrefix + "Api.h")); supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - if(generateCoreData) { - supportingFiles.add(new SupportingFile("xccurrentversion.mustache", (modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld", ".xccurrentversion")); - supportingFiles.add(new SupportingFile("Model.xcdatamodel.mustache",(modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld" + File.separator + classPrefix + "Model.xcdatamodel", "contents")); + if (generateCoreData) { + supportingFiles.add(new SupportingFile("xccurrentversion.mustache", (modelPackage() + + "/" + modelFilesPath + "/").replace("/", File.separator) + + classPrefix + "Model.xcdatamodeld", ".xccurrentversion")); + supportingFiles.add(new SupportingFile("Model.xcdatamodel.mustache", (modelPackage() + + "/" + modelFilesPath + "/").replace("/", File.separator) + + classPrefix + + "Model.xcdatamodeld" + + File.separator + + classPrefix + + "Model.xcdatamodel", "contents")); } } @@ -326,18 +357,19 @@ public String getTypeDeclaration(Property p) { Property inner = ap.getItems(); String innerTypeDeclaration = getTypeDeclaration(inner); if (innerTypeDeclaration.endsWith("*")) { - innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); + innerTypeDeclaration = + innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); } // In this condition, type of property p is array of primitive, // return container type with pointer, e.g. `NSArray**' if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { - return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; + return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; } // In this condition, type of property p is array of model, // return container type combine inner type with pointer, e.g. `NSArray*' else { for (String sd : advancedMapingTypes) { - if(innerTypeDeclaration.startsWith(sd)) { + if (innerTypeDeclaration.startsWith(sd)) { return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; } } @@ -348,15 +380,16 @@ public String getTypeDeclaration(Property p) { Property inner = mp.getAdditionalProperties(); String innerTypeDeclaration = getTypeDeclaration(inner); - + if (innerTypeDeclaration.endsWith("*")) { - innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); + innerTypeDeclaration = + innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); } if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { - return getSwaggerType(p) + "*"; + return getSwaggerType(p) + "*"; } else { for (String s : advancedMapingTypes) { - if(innerTypeDeclaration.startsWith(s)) { + if (innerTypeDeclaration.startsWith(s)) { return getSwaggerType(p) + "*"; } } @@ -366,8 +399,8 @@ public String getTypeDeclaration(Property p) { String swaggerType = getSwaggerType(p); // In this condition, type of p is objective-c primitive type, e.g. `NSSNumber', // return type of p with pointer, e.g. `NSNumber*' - if (languageSpecificPrimitives.contains(swaggerType) && - foundationClasses.contains(swaggerType)) { + if (languageSpecificPrimitives.contains(swaggerType) + && foundationClasses.contains(swaggerType)) { return swaggerType + "*"; } // In this condition, type of p is c primitive type, e.g. `bool', @@ -392,7 +425,8 @@ public boolean isDataTypeBinary(String dataType) { public String toModelName(String type) { // model name cannot use reserved keyword if (reservedWords.contains(type)) { - LOGGER.warn(type+ " (reserved word) cannot be used as model name. Renamed to " + ("model_" + type) + " before further processing"); + LOGGER.warn(type + " (reserved word) cannot be used as model name. Renamed to " + + ("model_" + type) + " before further processing"); type = "model_" + type; // e.g. return => ModelReturn (after camelize) } @@ -415,14 +449,14 @@ public String toModelName(String type) { * @return model Name in ObjC style guide */ public String toModelNameWithoutReservedWordCheck(String type) { - type = type.replaceAll("[^0-9a-zA-Z_]", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + type = type.replaceAll("[^0-9a-zA-Z_]", "_"); // FIXME: a parameter should not be assigned. + // Also declare the methods parameters as + // 'final'. // language build-in classes - if (typeMapping.keySet().contains(type) || - foundationClasses.contains(type) || - importMapping.values().contains(type) || - defaultIncludes.contains(type) || - languageSpecificPrimitives.contains(type)) { + if (typeMapping.keySet().contains(type) || foundationClasses.contains(type) + || importMapping.values().contains(type) || defaultIncludes.contains(type) + || languageSpecificPrimitives.contains(type)) { return camelize(type); } // custom classes @@ -464,17 +498,17 @@ public String toModelImport(String name) { public String apiDocFileFolder() { return (outputFolder + "/" + apiDocPath).replace("/", File.separator); } - + @Override public String modelDocFileFolder() { return (outputFolder + "/" + modelDocPath).replace("/", File.separator); } - + @Override public String toModelDocFilename(String name) { return toModelName(name); } - + @Override public String toApiDocFilename(String name) { return toApiName(name); @@ -482,12 +516,14 @@ public String toApiDocFilename(String name) { @Override public String apiFileFolder() { - return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator); + return (outputFolder + "/" + apiPackage() + "/" + apiFilesPath) + .replace("/", File.separator); } @Override public String modelFileFolder() { - return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator); + return (outputFolder + "/" + modelPackage() + "/" + modelFilesPath).replace("/", + File.separator); } public String coreFileFolder() { @@ -507,7 +543,8 @@ public String toApiFilename(String 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'. + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. // if it's all upper case, do noting if (name.matches("^[A-Z_]$")) { @@ -540,14 +577,14 @@ public String toParamName(String name) { } /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping - * those terms here. This logic is only called if a variable matches the reserved words + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping those terms + * here. This logic is only called if a variable matches the reserved words * * @return the escaped term - */ + */ @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -567,7 +604,8 @@ public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + camelize(sanitizeName("call_" + operationId), true)); operationId = "call_" + operationId; } @@ -618,8 +656,8 @@ public Map postProcessOperations(Map objs) { } @Override - public void postProcessModelProperty(CodegenModel model, CodegenProperty property){ - super.postProcessModelProperty(model,property); + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + super.postProcessModelProperty(model, property); property.vendorExtensions.put("x-uppercaseName", camelize(property.name)); } @@ -698,11 +736,11 @@ public void setParameterExampleValue(CodegenParameter p) { example = "56"; } example = "@" + example; - /* OBJC uses NSNumber to represent both int, long, double and float - } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) { - if (example == null) { - example = "3.4"; - } */ + /* OBJC uses NSNumber to represent both int, long, double and float + } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) { + if (example == null) { + example = "3.4"; + } */ } else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) { if (example == null) { example = "True"; @@ -711,13 +749,13 @@ public void setParameterExampleValue(CodegenParameter p) { if (example == null) { example = "/path/to/file"; } - //[NSURL fileURLWithPath:@"path/to/file"] + // [NSURL fileURLWithPath:@"path/to/file"] example = "[NSURL fileURLWithPath:@\"" + escapeText(example) + "\"]"; - /*} else if ("NSDate".equalsIgnoreCase(type)) { - if (example == null) { - example = "2013-10-20"; - } - example = "'" + escapeText(example) + "'";*/ + /*} else if ("NSDate".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20"; + } + example = "'" + escapeText(example) + "'";*/ } else if ("NSDate*".equalsIgnoreCase(type)) { if (example == null) { example = "2013-10-20T19:20:30+01:00"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java index bf50765f1ca..4d66c1c0aad 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java @@ -21,7 +21,6 @@ import io.swagger.models.properties.DateTimeProperty; import io.swagger.models.properties.DateProperty; - import java.io.File; import java.util.Arrays; import java.util.HashSet; @@ -33,7 +32,8 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String MODULE_NAME = "moduleName"; public static final String MODULE_VERSION = "moduleVersion"; protected String moduleName = "WWW::SwaggerClient"; - protected String modulePathPart = moduleName.replaceAll("::", Matcher.quoteReplacement(File.separator)); + protected String modulePathPart = moduleName.replaceAll("::", + Matcher.quoteReplacement(File.separator)); protected String moduleVersion = "1.0.0"; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; @@ -58,21 +58,11 @@ public PerlClientCodegen() { embeddedTemplateDir = templateDir = "perl"; - setReservedWordsLowerCase( - Arrays.asList( - "else", "lock", "qw", - "__END__", "elsif", "lt", "qx", - "__FILE__", "eq", "m", "s", - "__LINE__", "exp", "ne", "sub", - "__PACKAGE__", "for", "no", "tr", - "and", "foreach", "or", "unless", - "cmp", "ge", "package", "until", - "continue", "gt", "q", "while", - "CORE", "if", "qq", "xor", - "do", "le", "qr", "y", - "return" - ) - ); + setReservedWordsLowerCase(Arrays.asList("else", "lock", "qw", "__END__", "elsif", "lt", + "qx", "__FILE__", "eq", "m", "s", "__LINE__", "exp", "ne", "sub", "__PACKAGE__", + "for", "no", "tr", "and", "foreach", "or", "unless", "cmp", "ge", "package", + "until", "continue", "gt", "q", "while", "CORE", "if", "qq", "xor", "do", "le", + "qr", "y", "return")); languageSpecificPrimitives.clear(); languageSpecificPrimitives.add("int"); @@ -97,20 +87,24 @@ public PerlClientCodegen() { typeMapping.put("array", "ARRAY"); typeMapping.put("map", "HASH"); typeMapping.put("object", "object"); - //TODO binary should be mapped to byte array + // TODO binary should be mapped to byte array // mapped to String as a workaround typeMapping.put("binary", "string"); typeMapping.put("ByteArray", "string"); cliOptions.clear(); - cliOptions.add(new CliOption(MODULE_NAME, "Perl module name (convention: CamelCase or Long::Module).").defaultValue("SwaggerClient")); + cliOptions.add(new CliOption(MODULE_NAME, + "Perl module name (convention: CamelCase or Long::Module).") + .defaultValue("SwaggerClient")); cliOptions.add(new CliOption(MODULE_VERSION, "Perl module version.").defaultValue("1.0.0")); cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, - CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); - cliOptions.add(CliOption.newBoolean(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants - .ENSURE_UNIQUE_PARAMS_DESC).defaultValue(Boolean.TRUE.toString())); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) - .defaultValue(Boolean.TRUE.toString())); + CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue( + Boolean.TRUE.toString())); + cliOptions.add(CliOption.newBoolean(CodegenConstants.ENSURE_UNIQUE_PARAMS, + CodegenConstants.ENSURE_UNIQUE_PARAMS_DESC).defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC).defaultValue(Boolean.TRUE + .toString())); } @@ -137,17 +131,26 @@ public void processOpts() { // default HIDE_GENERATION_TIMESTAMP to true if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.TRUE.toString()); + } else { + additionalProperties.put( + CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get( + CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } - supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiClient.pm")); - supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "Configuration.pm")); - supportingFiles.add(new SupportingFile("ApiFactory.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiFactory.pm")); - supportingFiles.add(new SupportingFile("Role.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "Role.pm")); - supportingFiles.add(new SupportingFile("AutoDoc.mustache", ("lib/" + modulePathPart + "/Role").replace('/', File.separatorChar), "AutoDoc.pm")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/" + modulePathPart) + .replace('/', File.separatorChar), "ApiClient.pm")); + supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/" + modulePathPart) + .replace('/', File.separatorChar), "Configuration.pm")); + supportingFiles.add(new SupportingFile("ApiFactory.mustache", ("lib/" + modulePathPart) + .replace('/', File.separatorChar), "ApiFactory.pm")); + supportingFiles.add(new SupportingFile("Role.mustache", ("lib/" + modulePathPart).replace( + '/', File.separatorChar), "Role.pm")); + supportingFiles + .add(new SupportingFile("AutoDoc.mustache", ("lib/" + modulePathPart + "/Role") + .replace('/', File.separatorChar), "AutoDoc.pm")); supportingFiles.add(new SupportingFile("autodoc.script.mustache", "bin", "autodoc")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); @@ -171,7 +174,7 @@ public String getHelp() { @Override public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -179,12 +182,14 @@ public String escapeReservedWord(String name) { @Override public String apiFileFolder() { - return (outputFolder + "/lib/" + modulePathPart + apiPackage()).replace('/', File.separatorChar); + return (outputFolder + "/lib/" + modulePathPart + apiPackage()).replace('/', + File.separatorChar); } @Override public String modelFileFolder() { - return (outputFolder + "/lib/" + modulePathPart + modelPackage()).replace('/', File.separatorChar); + return (outputFolder + "/lib/" + modulePathPart + modelPackage()).replace('/', + File.separatorChar); } @Override @@ -285,7 +290,8 @@ public String toDefaultValue(Property p) { public String toVarName(String name) { // return the name in underscore style // PhoneNumber => phone_number - name = underscore(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = underscore(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. // parameter name starting with number won't compile // need to escape it by appending _ at the beginning @@ -303,17 +309,21 @@ public String toParamName(String name) { @Override public String toModelName(String name) { - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. // model name cannot use reserved keyword if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + camelize("model_" + name)); name = "model_" + name; } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -360,7 +370,8 @@ public String toApiDocFilename(String name) { @Override public String toApiFilename(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare + // the methods parameters as 'final'. // e.g. phone_number_api.rb => PhoneNumberApi.rb return camelize(name) + "Api"; @@ -377,7 +388,7 @@ public String toApiName(String name) { @Override public String toOperationId(String operationId) { - //rename to empty_function_name_1 (e.g.) if method name is empty + // rename to empty_function_name_1 (e.g.) if method name is empty if (StringUtils.isEmpty(operationId)) { operationId = underscore("empty_function_name_" + emptyFunctionNameCounter++); LOGGER.warn("Empty method name (operationId) found. Renamed to " + operationId); @@ -386,11 +397,12 @@ public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore("call_" + operationId)); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + underscore("call_" + operationId)); return underscore("call_" + operationId); } - //return underscore(operationId).replaceAll("[^A-Za-z0-9_]", ""); + // return underscore(operationId).replaceAll("[^A-Za-z0-9_]", ""); return underscore(sanitizeName(operationId)); } @@ -408,8 +420,8 @@ public void setModuleVersion(String moduleVersion) { @Override public void setParameterExampleValue(CodegenParameter p) { - if (Boolean.TRUE.equals(p.isString) || Boolean.TRUE.equals(p.isBinary) || - Boolean.TRUE.equals(p.isByteArray) || Boolean.TRUE.equals(p.isFile)) { + if (Boolean.TRUE.equals(p.isString) || Boolean.TRUE.equals(p.isBinary) + || Boolean.TRUE.equals(p.isByteArray) || Boolean.TRUE.equals(p.isFile)) { p.example = "'" + p.example + "'"; } else if (Boolean.TRUE.equals(p.isBoolean)) { if (Boolean.parseBoolean(p.example)) @@ -430,6 +442,7 @@ public String escapeQuotationMark(String input) { @Override public String escapeUnsafeCharacters(String input) { // remove =end, =cut to avoid code injection - return input.replace("=begin", "=_begin").replace("=end", "=_end").replace("=cut", "=_cut").replace("=pod", "=_pod"); + return input.replace("=begin", "=_begin").replace("=end", "=_end").replace("=cut", "=_cut") + .replace("=pod", "=_pod"); } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index d0b6589a587..df10fa403d1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -45,7 +45,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String docsBasePath = "docs"; protected String apiDirName = "Api"; protected String modelDirName = "Model"; - protected String variableNamingConvention= "snake_case"; + protected String variableNamingConvention = "snake_case"; protected String apiDocPath = docsBasePath + "/" + apiDirName; protected String modelDocPath = docsBasePath + "/" + modelDirName; @@ -70,40 +70,37 @@ public PhpClientCodegen() { modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); - setReservedWordsLowerCase( - Arrays.asList( - // local variables used in api methods (endpoints) - "resourcePath", "httpBody", "queryParams", "headerParams", - "formParams", "_header_accept", "_tempBody", - - // PHP reserved words - "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor") - ); + setReservedWordsLowerCase(Arrays.asList( + // local variables used in api methods (endpoints) + "resourcePath", + "httpBody", + "queryParams", + "headerParams", + "formParams", + "_header_accept", + "_tempBody", + + // PHP reserved words + "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", + "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", + "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", + "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", + "function", "global", "goto", "if", "implements", "include", "include_once", + "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", + "print", "private", "protected", "public", "require", "require_once", "return", + "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor")); // ref: http://php.net/manual/en/language.types.intro.php - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "bool", - "boolean", - "int", - "integer", - "double", - "float", - "string", - "object", - "DateTime", - "mixed", - "number", - "void", - "byte") - ); + languageSpecificPrimitives = + new HashSet(Arrays.asList("bool", "boolean", "int", "integer", "double", + "float", "string", "object", "DateTime", "mixed", "number", "void", "byte")); instantiationTypes.put("array", "array"); instantiationTypes.put("map", "map"); // provide primitives to mustache template - List sortedLanguageSpecificPrimitives= new ArrayList(languageSpecificPrimitives); + List sortedLanguageSpecificPrimitives = new ArrayList(languageSpecificPrimitives); Collections.sort(sortedLanguageSpecificPrimitives); String primitives = "'" + StringUtils.join(sortedLanguageSpecificPrimitives, "', '") + "'"; additionalProperties.put("primitives", primitives); @@ -129,20 +126,35 @@ public PhpClientCodegen() { typeMapping.put("ByteArray", "string"); typeMapping.put("UUID", "string"); - cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); - cliOptions.add(new CliOption(VARIABLE_NAMING_CONVENTION, "naming convention of variable name, e.g. camelCase.") - .defaultValue("snake_case")); - cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, "The main namespace to use for all classes. e.g. Yay\\Pets")); - cliOptions.add(new CliOption(PACKAGE_PATH, "The main package name for classes. e.g. GeneratedPetstore")); - cliOptions.add(new CliOption(SRC_BASE_PATH, "The directory under packagePath to serve as source root.")); - cliOptions.add(new CliOption(COMPOSER_VENDOR_NAME, "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. yaypets. IMPORTANT NOTE (2016/03): composerVendorName will be deprecated and replaced by gitUserId in the next swagger-codegen release")); - cliOptions.add(new CliOption(CodegenConstants.GIT_USER_ID, CodegenConstants.GIT_USER_ID_DESC)); - cliOptions.add(new CliOption(COMPOSER_PROJECT_NAME, "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client. IMPORTANT NOTE (2016/03): composerProjectName will be deprecated and replaced by gitRepoId in the next swagger-codegen release")); - cliOptions.add(new CliOption(CodegenConstants.GIT_REPO_ID, CodegenConstants.GIT_REPO_ID_DESC)); - cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "The version to use in the composer package version field. e.g. 1.2.3")); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") - .defaultValue(Boolean.TRUE.toString())); + 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(VARIABLE_NAMING_CONVENTION, + "naming convention of variable name, e.g. camelCase.").defaultValue("snake_case")); + cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, + "The main namespace to use for all classes. e.g. Yay\\Pets")); + cliOptions.add(new CliOption(PACKAGE_PATH, + "The main package name for classes. e.g. GeneratedPetstore")); + cliOptions.add(new CliOption(SRC_BASE_PATH, + "The directory under packagePath to serve as source root.")); + cliOptions + .add(new CliOption( + COMPOSER_VENDOR_NAME, + "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. yaypets. IMPORTANT NOTE (2016/03): composerVendorName will be deprecated and replaced by gitUserId in the next swagger-codegen release")); + cliOptions.add(new CliOption(CodegenConstants.GIT_USER_ID, + CodegenConstants.GIT_USER_ID_DESC)); + cliOptions + .add(new CliOption( + COMPOSER_PROJECT_NAME, + "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client. IMPORTANT NOTE (2016/03): composerProjectName will be deprecated and replaced by gitRepoId in the next swagger-codegen release")); + cliOptions.add(new CliOption(CodegenConstants.GIT_REPO_ID, + CodegenConstants.GIT_REPO_ID_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, + "The version to use in the composer package version field. e.g. 1.2.3")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + "hides the timestamp when files were generated").defaultValue(Boolean.TRUE + .toString())); } public String getPackagePath() { @@ -154,9 +166,18 @@ public String toPackagePath(String packageName, String basePath) { } public String toSrcPath(String packageName, String basePath) { - packageName = packageName.replace(invokerPackage, ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + packageName = packageName.replace(invokerPackage, ""); // FIXME: a parameter should not be + // assigned. Also declare the methods + // parameters as 'final'. if (basePath != null && basePath.length() > 0) { - basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar; // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar; // FIXME: a + // parameter + // should not be + // assigned. Also + // declare the + // methods + // parameters as + // 'final'. } String regFirstPathSeparator; @@ -174,12 +195,12 @@ public String toSrcPath(String packageName, String basePath) { } return (basePath - // Replace period, backslash, forward slash with file separator in package name - + packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement(File.separator)) - // Trim prefix file separators from package path + // Replace period, backslash, forward slash with file separator in package name + + packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement(File.separator)) + // Trim prefix file separators from package path .replaceAll(regFirstPathSeparator, "")) - // Trim trailing file separators from the overall path - .replaceAll(regLastPathSeparator+ "$", ""); + // Trim trailing file separators from the overall path + .replaceAll(regLastPathSeparator + "$", ""); } @Override @@ -212,10 +233,13 @@ public void processOpts() { // default HIDE_GENERATION_TIMESTAMP to true if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.TRUE.toString()); + } else { + additionalProperties.put( + CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get( + CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } if (additionalProperties.containsKey(PACKAGE_PATH)) { @@ -231,7 +255,8 @@ public void processOpts() { } if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { - this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); + this.setInvokerPackage((String) additionalProperties + .get(CodegenConstants.INVOKER_PACKAGE)); // Update the invokerPackage for the default apiPackage and modelPackage apiPackage = invokerPackage + "\\" + apiDirName; @@ -241,14 +266,20 @@ public void processOpts() { } if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { - // Update model package to contain the specified model package name and the invoker package - modelPackage = invokerPackage + "\\" + (String) additionalProperties.get(CodegenConstants.MODEL_PACKAGE); + // Update model package to contain the specified model package name and the invoker + // package + modelPackage = + invokerPackage + "\\" + + (String) additionalProperties.get(CodegenConstants.MODEL_PACKAGE); } additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { - // Update model package to contain the specified model package name and the invoker package - apiPackage = invokerPackage + "\\" + (String) additionalProperties.get(CodegenConstants.API_PACKAGE); + // Update model package to contain the specified model package name and the invoker + // package + apiPackage = + invokerPackage + "\\" + + (String) additionalProperties.get(CodegenConstants.API_PACKAGE); } additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); @@ -277,13 +308,15 @@ public void processOpts() { } if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) { - this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION)); + this.setArtifactVersion((String) additionalProperties + .get(CodegenConstants.ARTIFACT_VERSION)); } else { additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); } if (additionalProperties.containsKey(VARIABLE_NAMING_CONVENTION)) { - this.setParameterNamingConvention((String) additionalProperties.get(VARIABLE_NAMING_CONVENTION)); + this.setParameterNamingConvention((String) additionalProperties + .get(VARIABLE_NAMING_CONVENTION)); } additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); @@ -301,22 +334,30 @@ public void processOpts() { // make test path available in mustache template additionalProperties.put("testBasePath", testBasePath); - supportingFiles.add(new SupportingFile("configuration.mustache", toPackagePath(invokerPackage, srcBasePath), "Configuration.php")); - supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiClient.php")); - supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiException.php")); - supportingFiles.add(new SupportingFile("ObjectSerializer.mustache", toPackagePath(invokerPackage, srcBasePath), "ObjectSerializer.php")); - supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), "composer.json")); - supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php")); + supportingFiles.add(new SupportingFile("configuration.mustache", toPackagePath( + invokerPackage, srcBasePath), "Configuration.php")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, + srcBasePath), "ApiClient.php")); + supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath( + invokerPackage, srcBasePath), "ApiException.php")); + supportingFiles.add(new SupportingFile("ObjectSerializer.mustache", toPackagePath( + invokerPackage, srcBasePath), "ObjectSerializer.php")); + supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), + "composer.json")); + supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), + "autoload.php")); supportingFiles.add(new SupportingFile("README.mustache", getPackagePath(), "README.md")); - supportingFiles.add(new SupportingFile("phpunit.xml.mustache", getPackagePath(), "phpunit.xml.dist")); + supportingFiles.add(new SupportingFile("phpunit.xml.mustache", getPackagePath(), + "phpunit.xml.dist")); supportingFiles.add(new SupportingFile(".travis.yml", getPackagePath(), ".travis.yml")); supportingFiles.add(new SupportingFile(".php_cs", getPackagePath(), ".php_cs")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", getPackagePath(), "git_push.sh")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", getPackagePath(), + "git_push.sh")); } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -374,8 +415,8 @@ public String getTypeDeclaration(Property p) { return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; } else if (p instanceof RefProperty) { String type = super.getTypeDeclaration(p); - return (!languageSpecificPrimitives.contains(type)) - ? "\\" + modelPackage + "\\" + type : type; + return (!languageSpecificPrimitives.contains(type)) ? "\\" + modelPackage + "\\" + type + : type; } return super.getTypeDeclaration(p); } @@ -439,16 +480,17 @@ public void setComposerProjectName(String composerProjectName) { @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'. + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. if ("camelCase".equals(variableNamingConvention)) { - // return the name in camelCase style - // phone_number => phoneNumber - name = camelize(name, true); + // return the name in camelCase style + // phone_number => phoneNumber + name = camelize(name, true); } else { // default to snake case - // return the name in underscore style - // PhoneNumber => phone_number - name = underscore(name); + // return the name in underscore style + // PhoneNumber => phone_number + name = underscore(name); } // parameter name starting with number won't compile @@ -472,20 +514,25 @@ public String toModelName(String name) { name = name.replaceAll("\\]", ""); // Note: backslash ("\\") is allowed for e.g. "\\DateTime" - name = name.replaceAll("[^\\w\\\\]+", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = name.replaceAll("[^\\w\\\\]+", "_"); // FIXME: a parameter should not be assigned. + // Also declare the methods parameters as + // 'final'. // remove dollar sign name = name.replaceAll("$", ""); // model name cannot use reserved keyword if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -526,7 +573,8 @@ public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + camelize(sanitizeName("call_" + operationId), true)); operationId = "call_" + operationId; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index 38e4a75491c..dcce99c7a26 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -1,638 +1,663 @@ -package io.swagger.codegen.languages; - -import io.swagger.codegen.CliOption; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.CodegenModel; -import io.swagger.codegen.CodegenParameter; -import io.swagger.codegen.CodegenProperty; -import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; -import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.*; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; - -public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig { - public static final String PACKAGE_URL = "packageUrl"; - - protected String packageName; - protected String packageVersion; - protected String packageUrl; - protected String apiDocPath = "docs/"; - protected String modelDocPath = "docs/"; - - protected Map regexModifiers; - - private String testFolder; - - public PythonClientCodegen() { - super(); - - // clear import mapping (from default generator) as python does not use it - // at the moment - importMapping.clear(); - - modelPackage = "models"; - apiPackage = "api"; - outputFolder = "generated-code" + File.separatorChar + "python"; - - modelTemplateFiles.put("model.mustache", ".py"); - apiTemplateFiles.put("api.mustache", ".py"); - - modelTestTemplateFiles.put("model_test.mustache", ".py"); - apiTestTemplateFiles.put("api_test.mustache", ".py"); - - embeddedTemplateDir = templateDir = "python"; - - modelDocTemplateFiles.put("model_doc.mustache", ".md"); - apiDocTemplateFiles.put("api_doc.mustache", ".md"); - - testFolder = "test"; - - languageSpecificPrimitives.clear(); - languageSpecificPrimitives.add("int"); - languageSpecificPrimitives.add("float"); - languageSpecificPrimitives.add("list"); - languageSpecificPrimitives.add("bool"); - languageSpecificPrimitives.add("str"); - languageSpecificPrimitives.add("datetime"); - languageSpecificPrimitives.add("date"); - languageSpecificPrimitives.add("object"); - - typeMapping.clear(); - typeMapping.put("integer", "int"); - typeMapping.put("float", "float"); - typeMapping.put("number", "float"); - typeMapping.put("long", "int"); - typeMapping.put("double", "float"); - typeMapping.put("array", "list"); - typeMapping.put("map", "dict"); - typeMapping.put("boolean", "bool"); - typeMapping.put("string", "str"); - typeMapping.put("date", "date"); - typeMapping.put("DateTime", "datetime"); - typeMapping.put("object", "object"); - typeMapping.put("file", "file"); - // TODO binary should be mapped to byte array - // mapped to String as a workaround - typeMapping.put("binary", "str"); - typeMapping.put("ByteArray", "str"); - // map uuid to string for the time being - typeMapping.put("UUID", "str"); - - // from https://docs.python.org/release/2.5.4/ref/keywords.html - setReservedWordsLowerCase( - Arrays.asList( - // local variable name used in API methods (endpoints) - "all_params", "resource_path", "path_params", "query_params", - "header_params", "form_params", "local_var_files", "body_params", "auth_settings", - // @property - "property", - // python reserved words - "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", - "assert", "else", "if", "pass", "yield", "break", "except", "import", - "print", "class", "exec", "in", "raise", "continue", "finally", "is", - "return", "def", "for", "lambda", "try", "self")); - - regexModifiers = new HashMap(); - regexModifiers.put('i', "IGNORECASE"); - regexModifiers.put('l', "LOCALE"); - regexModifiers.put('m', "MULTILINE"); - regexModifiers.put('s', "DOTALL"); - regexModifiers.put('u', "UNICODE"); - regexModifiers.put('x', "VERBOSE"); - - cliOptions.clear(); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case).") - .defaultValue("swagger_client")); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "python package version.") - .defaultValue("1.0.0")); - cliOptions.add(new CliOption(PACKAGE_URL, "python package URL.")); - cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, - CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") - .defaultValue(Boolean.TRUE.toString())); - } - - @Override - public void processOpts() { - super.processOpts(); - Boolean excludeTests = false; - - if(additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) { - excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString()); - } - - if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { - setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); - } - else { - setPackageName("swagger_client"); - } - - if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { - setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); - } - else { - setPackageVersion("1.0.0"); - } - - // default HIDE_GENERATION_TIMESTAMP to true - if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); - } - - additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); - additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); - - // make api and model doc path available in mustache template - additionalProperties.put("apiDocPath", apiDocPath); - additionalProperties.put("modelDocPath", modelDocPath); - - if (additionalProperties.containsKey(PACKAGE_URL)) { - setPackageUrl((String) additionalProperties.get(PACKAGE_URL)); - } - - String swaggerFolder = packageName; - - modelPackage = swaggerFolder + File.separatorChar + "models"; - apiPackage = swaggerFolder + File.separatorChar + "apis"; - - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - - supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py")); - supportingFiles.add(new SupportingFile("tox.mustache", "", "tox.ini")); - supportingFiles.add(new SupportingFile("test-requirements.mustache", "", "test-requirements.txt")); - supportingFiles.add(new SupportingFile("requirements.mustache", "", "requirements.txt")); - - supportingFiles.add(new SupportingFile("api_client.mustache", swaggerFolder, "api_client.py")); - supportingFiles.add(new SupportingFile("rest.mustache", swaggerFolder, "rest.py")); - supportingFiles.add(new SupportingFile("configuration.mustache", swaggerFolder, "configuration.py")); - supportingFiles.add(new SupportingFile("__init__package.mustache", swaggerFolder, "__init__.py")); - supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py")); - supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py")); - - if(Boolean.FALSE.equals(excludeTests)) { - supportingFiles.add(new SupportingFile("__init__test.mustache", testFolder, "__init__.py")); - } - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml")); - } - - private static String dropDots(String str) { - return str.replaceAll("\\.", "_"); - } - - @Override - public void postProcessParameter(CodegenParameter parameter){ - postProcessPattern(parameter.pattern, parameter.vendorExtensions); - } - - @Override - public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { - postProcessPattern(property.pattern, property.vendorExtensions); - } - - /* - * The swagger pattern spec follows the Perl convention and style of modifiers. Python - * does not support this in as natural a way so it needs to convert it. See - * https://docs.python.org/2/howto/regex.html#compilation-flags for details. - */ - public void postProcessPattern(String pattern, Map vendorExtensions){ - if(pattern != null) { - int i = pattern.lastIndexOf('/'); - - //Must follow Perl /pattern/modifiers convention - if(pattern.charAt(0) != '/' || i < 2) { - throw new IllegalArgumentException("Pattern must follow the Perl " - + "/pattern/modifiers convention. "+pattern+" is not valid."); - } - - String regex = pattern.substring(1, i).replace("'", "\\'"); - List modifiers = new ArrayList(); - - for(char c : pattern.substring(i).toCharArray()) { - if(regexModifiers.containsKey(c)) { - String modifier = regexModifiers.get(c); - modifiers.add(modifier); - } - } - - vendorExtensions.put("x-regex", regex); - vendorExtensions.put("x-modifiers", modifiers); - } - } - - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - @Override - public String getName() { - return "python"; - } - - @Override - public String getHelp() { - return "Generates a Python client library."; - } - - @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { - return this.reservedWordsMappings().get(name); - } - return "_" + name; - } - - @Override - public String apiDocFileFolder() { - return (outputFolder + "/" + apiDocPath); - } - - @Override - public String modelDocFileFolder() { - return (outputFolder + "/" + modelDocPath); - } - - @Override - public String toModelDocFilename(String name) { - return toModelName(name); - } - - @Override - public String toApiDocFilename(String name) { - return toApiName(name); - } - - - @Override - public String apiFileFolder() { - return outputFolder + File.separatorChar + apiPackage().replace('.', File.separatorChar); - } - - @Override - public String modelFileFolder() { - return outputFolder + File.separatorChar + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String apiTestFileFolder() { - return outputFolder + File.separatorChar + testFolder; - } - - @Override - public String modelTestFileFolder() { - return outputFolder + File.separatorChar + testFolder; - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + "(str, " + getTypeDeclaration(inner) + ")"; - } - return super.getTypeDeclaration(p); - } - - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) { - return type; - } - } else { - type = toModelName(swaggerType); - } - return type; - } - - @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'. - - // remove dollar sign - name = name.replaceAll("$", ""); - - // if it's all uppper case, convert to lower case - if (name.matches("^[A-Z_]*$")) { - name = name.toLowerCase(); - } - - // underscore the variable name - // petId => pet_id - name = underscore(name); - - // remove leading underscore - name = name.replaceAll("^_*", ""); - - // for reserved word or word starting with number, append _ - if (isReservedWord(name) || name.matches("^\\d.*")) { - name = escapeReservedWord(name); - } - - return name; - } - - @Override - public String toParamName(String name) { - // to avoid conflicts with 'callback' parameter for async call - if ("callback".equals(name)) { - return "param_callback"; - } - - // should be the same as variable name - return toVarName(name); - } - - @Override - public String toModelName(String name) { - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - // remove dollar sign - name = name.replaceAll("$", ""); - - // model name cannot use reserved keyword, e.g. return - if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); - name = "model_" + name; // e.g. return => ModelReturn (after camelize) - } - - // model name starts with number - if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); - name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) - } - - if (!StringUtils.isEmpty(modelNamePrefix)) { - name = modelNamePrefix + "_" + name; - } - - if (!StringUtils.isEmpty(modelNameSuffix)) { - name = name + "_" + modelNameSuffix; - } - - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } - - @Override - public String toModelFilename(String name) { - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - // remove dollar sign - name = name.replaceAll("$", ""); - - // model name cannot use reserved keyword, e.g. return - if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + underscore(dropDots("model_" + name))); - name = "model_" + name; // e.g. return => ModelReturn (after camelize) - } - - // model name starts with number - if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + underscore("model_" + name)); - name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) - } - - if (!StringUtils.isEmpty(modelNamePrefix)) { - name = modelNamePrefix + "_" + name; - } - - if (!StringUtils.isEmpty(modelNameSuffix)) { - name = name + "_" + modelNameSuffix; - } - - // underscore the model file name - // PhoneNumber => phone_number - return underscore(dropDots(name)); - } - - @Override - public String toModelTestFilename(String name) { - return "test_" + toModelFilename(name); - }; - - @Override - public String toApiFilename(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); - - // e.g. PhoneNumberApi.rb => phone_number_api.rb - return underscore(name) + "_api"; - } - - @Override - public String toApiTestFilename(String name) { - return "test_" + toApiFilename(name); - } - - @Override - public String toApiName(String name) { - if (name.length() == 0) { - return "DefaultApi"; - } - // e.g. phone_number_api => PhoneNumberApi - return camelize(name) + "Api"; - } - - @Override - public String toApiVarName(String name) { - if (name.length() == 0) { - return "default_api"; - } - return underscore(name) + "_api"; - } - - @Override - public String toOperationId(String operationId) { - // throw exception if method name is empty (should not occur as an auto-generated method name will be used) - if (StringUtils.isEmpty(operationId)) { - throw new RuntimeException("Empty method name (operationId) not allowed"); - } - - // method name cannot use reserved keyword, e.g. return - if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); - operationId = "call_" + operationId; - } - - return underscore(sanitizeName(operationId)); - } - - public void setPackageName(String packageName) { - this.packageName = packageName; - } - - public void setPackageVersion(String packageVersion) { - this.packageVersion = packageVersion; - } - - public void setPackageUrl(String packageUrl) { - this.packageUrl = packageUrl; - } - - /** - * Generate Python package name from String `packageName` - * - * (PEP 0008) Python packages should also have short, all-lowercase names, - * although the use of underscores is discouraged. - * - * @param packageName Package name - * @return Python package name that conforms to PEP 0008 - */ - @SuppressWarnings("static-method") - public String generatePackageName(String packageName) { - return underscore(packageName.replaceAll("[^\\w]+", "")); - } - - /** - * Return the default value of the property - * - * @param p Swagger property object - * @return string presentation of the default value of the property - */ - @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - StringProperty dp = (StringProperty) p; - if (dp.getDefault() != null) { - return "'" + dp.getDefault() + "'"; - } - } else if (p instanceof BooleanProperty) { - BooleanProperty dp = (BooleanProperty) p; - if (dp.getDefault() != null) { - if (dp.getDefault().toString().equalsIgnoreCase("false")) - return "False"; - else - return "True"; - } - } else if (p instanceof DateProperty) { - // TODO - } else if (p instanceof DateTimeProperty) { - // TODO - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - } - - return null; - } - - @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".equalsIgnoreCase(type) || "str".equalsIgnoreCase(type)) { - if (example == null) { - example = p.paramName + "_example"; - } - example = "'" + escapeText(example) + "'"; - } else if ("Integer".equals(type) || "int".equals(type)) { - if (example == null) { - example = "56"; - } - } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) { - if (example == null) { - example = "3.4"; - } - } else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) { - if (example == null) { - example = "True"; - } - } else if ("file".equalsIgnoreCase(type)) { - if (example == null) { - example = "/path/to/file"; - } - example = "'" + escapeText(example) + "'"; - } else if ("Date".equalsIgnoreCase(type)) { - if (example == null) { - example = "2013-10-20"; - } - example = "'" + escapeText(example) + "'"; - } else if ("DateTime".equalsIgnoreCase(type)) { - if (example == null) { - example = "2013-10-20T19:20:30+01:00"; - } - example = "'" + escapeText(example) + "'"; - } else if (!languageSpecificPrimitives.contains(type)) { - // type is a model class, e.g. User - example = this.packageName + "." + type + "()"; - } else { - LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); - } - - if (example == null) { - example = "NULL"; - } else if (Boolean.TRUE.equals(p.isListContainer)) { - example = "[" + example + "]"; - } else if (Boolean.TRUE.equals(p.isMapContainer)) { - example = "{'key': " + example + "}"; - } - - p.example = example; - } - - @Override - public String escapeQuotationMark(String input) { - // remove ' to avoid code injection - return input.replace("'", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - // remove multiline comment - return input.replace("'''", "'_'_'"); - } - -} +package io.swagger.codegen.languages; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; +import io.swagger.models.properties.*; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; + +public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig { + public static final String PACKAGE_URL = "packageUrl"; + + protected String packageName; + protected String packageVersion; + protected String packageUrl; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; + + protected Map regexModifiers; + + private String testFolder; + + public PythonClientCodegen() { + super(); + + // clear import mapping (from default generator) as python does not use it + // at the moment + importMapping.clear(); + + modelPackage = "models"; + apiPackage = "api"; + outputFolder = "generated-code" + File.separatorChar + "python"; + + modelTemplateFiles.put("model.mustache", ".py"); + apiTemplateFiles.put("api.mustache", ".py"); + + modelTestTemplateFiles.put("model_test.mustache", ".py"); + apiTestTemplateFiles.put("api_test.mustache", ".py"); + + embeddedTemplateDir = templateDir = "python"; + + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + + testFolder = "test"; + + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("int"); + languageSpecificPrimitives.add("float"); + languageSpecificPrimitives.add("list"); + languageSpecificPrimitives.add("bool"); + languageSpecificPrimitives.add("str"); + languageSpecificPrimitives.add("datetime"); + languageSpecificPrimitives.add("date"); + languageSpecificPrimitives.add("object"); + + typeMapping.clear(); + typeMapping.put("integer", "int"); + typeMapping.put("float", "float"); + typeMapping.put("number", "float"); + typeMapping.put("long", "int"); + typeMapping.put("double", "float"); + typeMapping.put("array", "list"); + typeMapping.put("map", "dict"); + typeMapping.put("boolean", "bool"); + typeMapping.put("string", "str"); + typeMapping.put("date", "date"); + typeMapping.put("DateTime", "datetime"); + typeMapping.put("object", "object"); + typeMapping.put("file", "file"); + // TODO binary should be mapped to byte array + // mapped to String as a workaround + typeMapping.put("binary", "str"); + typeMapping.put("ByteArray", "str"); + // map uuid to string for the time being + typeMapping.put("UUID", "str"); + + // from https://docs.python.org/release/2.5.4/ref/keywords.html + setReservedWordsLowerCase(Arrays.asList( + // local variable name used in API methods (endpoints) + "all_params", "resource_path", "path_params", "query_params", + "header_params", + "form_params", + "local_var_files", + "body_params", + "auth_settings", + // @property + "property", + // python reserved words + "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", + "assert", "else", "if", "pass", "yield", "break", "except", "import", "print", + "class", "exec", "in", "raise", "continue", "finally", "is", "return", "def", + "for", "lambda", "try", "self")); + + regexModifiers = new HashMap(); + regexModifiers.put('i', "IGNORECASE"); + regexModifiers.put('l', "LOCALE"); + regexModifiers.put('m', "MULTILINE"); + regexModifiers.put('s', "DOTALL"); + regexModifiers.put('u', "UNICODE"); + regexModifiers.put('x', "VERBOSE"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, + "python package name (convention: snake_case).").defaultValue("swagger_client")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "python package version.") + .defaultValue("1.0.0")); + cliOptions.add(new CliOption(PACKAGE_URL, "python package URL.")); + cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, + CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue( + Boolean.TRUE.toString())); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + "hides the timestamp when files were generated").defaultValue(Boolean.TRUE + .toString())); + } + + @Override + public void processOpts() { + super.processOpts(); + Boolean excludeTests = false; + + if (additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) { + excludeTests = + Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS) + .toString()); + } + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } else { + setPackageName("swagger_client"); + } + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); + } else { + setPackageVersion("1.0.0"); + } + + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.TRUE.toString()); + } else { + additionalProperties.put( + CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get( + CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } + + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); + + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + + if (additionalProperties.containsKey(PACKAGE_URL)) { + setPackageUrl((String) additionalProperties.get(PACKAGE_URL)); + } + + String swaggerFolder = packageName; + + modelPackage = swaggerFolder + File.separatorChar + "models"; + apiPackage = swaggerFolder + File.separatorChar + "apis"; + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + + supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py")); + supportingFiles.add(new SupportingFile("tox.mustache", "", "tox.ini")); + supportingFiles.add(new SupportingFile("test-requirements.mustache", "", + "test-requirements.txt")); + supportingFiles.add(new SupportingFile("requirements.mustache", "", "requirements.txt")); + + supportingFiles.add(new SupportingFile("api_client.mustache", swaggerFolder, + "api_client.py")); + supportingFiles.add(new SupportingFile("rest.mustache", swaggerFolder, "rest.py")); + supportingFiles.add(new SupportingFile("configuration.mustache", swaggerFolder, + "configuration.py")); + supportingFiles.add(new SupportingFile("__init__package.mustache", swaggerFolder, + "__init__.py")); + supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, + "__init__.py")); + supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py")); + + if (Boolean.FALSE.equals(excludeTests)) { + supportingFiles.add(new SupportingFile("__init__test.mustache", testFolder, + "__init__.py")); + } + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml")); + } + + private static String dropDots(String str) { + return str.replaceAll("\\.", "_"); + } + + @Override + public void postProcessParameter(CodegenParameter parameter) { + postProcessPattern(parameter.pattern, parameter.vendorExtensions); + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + postProcessPattern(property.pattern, property.vendorExtensions); + } + + /* + * The swagger pattern spec follows the Perl convention and style of modifiers. Python + * does not support this in as natural a way so it needs to convert it. See + * https://docs.python.org/2/howto/regex.html#compilation-flags for details. + */ + public void postProcessPattern(String pattern, Map vendorExtensions) { + if (pattern != null) { + int i = pattern.lastIndexOf('/'); + + // Must follow Perl /pattern/modifiers convention + if (pattern.charAt(0) != '/' || i < 2) { + throw new IllegalArgumentException("Pattern must follow the Perl " + + "/pattern/modifiers convention. " + pattern + " is not valid."); + } + + String regex = pattern.substring(1, i).replace("'", "\\'"); + List modifiers = new ArrayList(); + + for (char c : pattern.substring(i).toCharArray()) { + if (regexModifiers.containsKey(c)) { + String modifier = regexModifiers.get(c); + modifiers.add(modifier); + } + } + + vendorExtensions.put("x-regex", regex); + vendorExtensions.put("x-modifiers", modifiers); + } + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String getName() { + return "python"; + } + + @Override + public String getHelp() { + return "Generates a Python client library."; + } + + @Override + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath); + } + + @Override + public String toModelDocFilename(String name) { + return toModelName(name); + } + + @Override + public String toApiDocFilename(String name) { + return toApiName(name); + } + + + @Override + public String apiFileFolder() { + return outputFolder + File.separatorChar + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separatorChar + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String apiTestFileFolder() { + return outputFolder + File.separatorChar + testFolder; + } + + @Override + public String modelTestFileFolder() { + return outputFolder + File.separatorChar + testFolder; + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "(str, " + getTypeDeclaration(inner) + ")"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return type; + } + } else { + type = toModelName(swaggerType); + } + return type; + } + + @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'. + + // remove dollar sign + name = name.replaceAll("$", ""); + + // if it's all uppper case, convert to lower case + if (name.matches("^[A-Z_]*$")) { + name = name.toLowerCase(); + } + + // underscore the variable name + // petId => pet_id + name = underscore(name); + + // remove leading underscore + name = name.replaceAll("^_*", ""); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toParamName(String name) { + // to avoid conflicts with 'callback' parameter for async call + if ("callback".equals(name)) { + return "param_callback"; + } + + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. + // remove dollar sign + name = name.replaceAll("$", ""); + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + camelize("model_" + name)); + name = "model_" + name; // e.g. return => ModelReturn (after camelize) + } + + // model name starts with number + if (name.matches("^\\d.*")) { + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + camelize("model_" + name)); + name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) + } + + if (!StringUtils.isEmpty(modelNamePrefix)) { + name = modelNamePrefix + "_" + name; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + name = name + "_" + modelNameSuffix; + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. + // remove dollar sign + name = name.replaceAll("$", ""); + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + + underscore(dropDots("model_" + name))); + name = "model_" + name; // e.g. return => ModelReturn (after camelize) + } + + // model name starts with number + if (name.matches("^\\d.*")) { + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + underscore("model_" + name)); + name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) + } + + if (!StringUtils.isEmpty(modelNamePrefix)) { + name = modelNamePrefix + "_" + name; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + name = name + "_" + modelNameSuffix; + } + + // underscore the model file name + // PhoneNumber => phone_number + return underscore(dropDots(name)); + } + + @Override + public String toModelTestFilename(String name) { + return "test_" + toModelFilename(name); + }; + + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // e.g. PhoneNumberApi.rb => phone_number_api.rb + return underscore(name) + "_api"; + } + + @Override + public String toApiTestFilename(String name) { + return "test_" + toApiFilename(name); + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + // e.g. phone_number_api => PhoneNumberApi + return camelize(name) + "Api"; + } + + @Override + public String toApiVarName(String name) { + if (name.length() == 0) { + return "default_api"; + } + return underscore(name) + "_api"; + } + + @Override + public String toOperationId(String operationId) { + // throw exception if method name is empty (should not occur as an auto-generated method + // name will be used) + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + underscore(sanitizeName("call_" + operationId))); + operationId = "call_" + operationId; + } + + return underscore(sanitizeName(operationId)); + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + + public void setPackageUrl(String packageUrl) { + this.packageUrl = packageUrl; + } + + /** + * Generate Python package name from String `packageName` + * + * (PEP 0008) Python packages should also have short, all-lowercase names, although the use of + * underscores is discouraged. + * + * @param packageName Package name + * @return Python package name that conforms to PEP 0008 + */ + @SuppressWarnings("static-method") + public String generatePackageName(String packageName) { + return underscore(packageName.replaceAll("[^\\w]+", "")); + } + + /** + * Return the default value of the property + * + * @param p Swagger property object + * @return string presentation of the default value of the property + */ + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + StringProperty dp = (StringProperty) p; + if (dp.getDefault() != null) { + return "'" + dp.getDefault() + "'"; + } + } else if (p instanceof BooleanProperty) { + BooleanProperty dp = (BooleanProperty) p; + if (dp.getDefault() != null) { + if (dp.getDefault().toString().equalsIgnoreCase("false")) + return "False"; + else + return "True"; + } + } else if (p instanceof DateProperty) { + // TODO + } else if (p instanceof DateTimeProperty) { + // TODO + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof IntegerProperty) { + IntegerProperty dp = (IntegerProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } + + return null; + } + + @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".equalsIgnoreCase(type) || "str".equalsIgnoreCase(type)) { + if (example == null) { + example = p.paramName + "_example"; + } + example = "'" + escapeText(example) + "'"; + } else if ("Integer".equals(type) || "int".equals(type)) { + if (example == null) { + example = "56"; + } + } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) { + if (example == null) { + example = "3.4"; + } + } else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) { + if (example == null) { + example = "True"; + } + } else if ("file".equalsIgnoreCase(type)) { + if (example == null) { + example = "/path/to/file"; + } + example = "'" + escapeText(example) + "'"; + } else if ("Date".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20"; + } + example = "'" + escapeText(example) + "'"; + } else if ("DateTime".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20T19:20:30+01:00"; + } + example = "'" + escapeText(example) + "'"; + } else if (!languageSpecificPrimitives.contains(type)) { + // type is a model class, e.g. User + example = this.packageName + "." + type + "()"; + } else { + LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); + } + + if (example == null) { + example = "NULL"; + } else if (Boolean.TRUE.equals(p.isListContainer)) { + example = "[" + example + "]"; + } else if (Boolean.TRUE.equals(p.isMapContainer)) { + example = "{'key': " + example + "}"; + } + + p.example = example; + } + + @Override + public String escapeQuotationMark(String input) { + // remove ' to avoid code injection + return input.replace("'", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + // remove multiline comment + return input.replace("'''", "'_'_'"); + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java index 18ae0170d52..f4f76e50b4b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java @@ -47,26 +47,20 @@ public Qt5CPPGenerator() { * for multiple files for model, just put another entry in the `modelTemplateFiles` with * a different extension */ - modelTemplateFiles.put( - "model-header.mustache", - ".h"); + modelTemplateFiles.put("model-header.mustache", ".h"); - modelTemplateFiles.put( - "model-body.mustache", - ".cpp"); + modelTemplateFiles.put("model-body.mustache", ".cpp"); /* * Api classes. You can write classes for each Api file with the apiTemplateFiles map. * as with models, add multiple entries with different extensions for multiple files per * class */ - apiTemplateFiles.put( - "api-header.mustache", // the template to use - ".h"); // the extension for each file to write + apiTemplateFiles.put("api-header.mustache", // the template to use + ".h"); // the extension for each file to write - apiTemplateFiles.put( - "api-body.mustache", // the template to use - ".cpp"); // the extension for each file to write + apiTemplateFiles.put("api-body.mustache", // the template to use + ".cpp"); // the extension for each file to write /* * Template Location. This is the location which templates will be read from. The generator @@ -77,11 +71,8 @@ public Qt5CPPGenerator() { /* * Reserved words. Override this with reserved words specific to your language */ - setReservedWordsLowerCase( - Arrays.asList( - "sample1", // replace with static values - "sample2") - ); + setReservedWordsLowerCase(Arrays.asList("sample1", // replace with static values + "sample2")); /* * Additional Properties. These values can be passed to the templates and @@ -94,21 +85,21 @@ public Qt5CPPGenerator() { * Language Specific Primitives. These types will not trigger imports by * the client generator */ - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "bool", - "qint32", - "qint64", - "float", - "double") - ); - - supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h")); - supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp")); - supportingFiles.add(new SupportingFile("HttpRequest.h.mustache", sourceFolder, PREFIX + "HttpRequest.h")); - supportingFiles.add(new SupportingFile("HttpRequest.cpp.mustache", sourceFolder, PREFIX + "HttpRequest.cpp")); - supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h")); - supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h")); + languageSpecificPrimitives = + new HashSet(Arrays.asList("bool", "qint32", "qint64", "float", "double")); + + supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + + "Helpers.h")); + supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + + "Helpers.cpp")); + supportingFiles.add(new SupportingFile("HttpRequest.h.mustache", sourceFolder, PREFIX + + "HttpRequest.h")); + supportingFiles.add(new SupportingFile("HttpRequest.cpp.mustache", sourceFolder, PREFIX + + "HttpRequest.cpp")); + supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + + "ModelFactory.h")); + supportingFiles + .add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h")); super.typeMapping = new HashMap(); @@ -122,14 +113,15 @@ public Qt5CPPGenerator() { typeMapping.put("map", "QMap"); typeMapping.put("file", "SWGHttpRequestInputFileElement"); typeMapping.put("object", PREFIX + "Object"); - //TODO binary should be mapped to byte array + // TODO binary should be mapped to byte array // mapped to String as a workaround typeMapping.put("binary", "QString"); typeMapping.put("ByteArray", "QByteArray"); importMapping = new HashMap(); - importMapping.put("SWGHttpRequestInputFileElement", "#include \"" + PREFIX + "HttpRequest.h\""); + importMapping.put("SWGHttpRequestInputFileElement", "#include \"" + PREFIX + + "HttpRequest.h\""); namespaces = new HashMap(); @@ -155,8 +147,8 @@ public CodegenType getTag() { } /** - * Configures a friendly name for the generator. This will be used by the generator - * to select the library with the -l flag. + * Configures a friendly name for the generator. This will be used by the generator to select + * the library with the -l flag. * * @return the friendly name for the generator */ @@ -166,8 +158,8 @@ public String getName() { } /** - * Returns human-friendly help for the generator. Provide the consumer with help - * tips, parameters here + * Returns human-friendly help for the generator. Provide the consumer with help tips, + * parameters here * * @return A string value for the help message */ @@ -192,30 +184,31 @@ public String toModelImport(String name) { } /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping - * those terms here. This logic is only called if a variable matches the reseved words + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping those terms + * here. This logic is only called if a variable matches the reseved words * * @return the escaped term */ @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; } /** - * Location to write model files. You can use the modelPackage() as defined when the class is + * Location to write model files. You can use the modelPackage() as defined when the class is * instantiated */ @Override public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace("::", File.separator); + return outputFolder + "/" + sourceFolder + "/" + + modelPackage().replace("::", File.separator); } /** - * Location to write api files. You can use the apiPackage() as defined when the class is + * Location to write api files. You can use the apiPackage() as defined when the class is * instantiated */ @Override @@ -234,10 +227,11 @@ public String toApiFilename(String name) { } /** - * Optional - type declaration. This is a String which is used by the templates to instantiate your - * types. There is typically special handling for different property types + * Optional - type declaration. This is a String which is used by the templates to instantiate + * your types. There is typically special handling for different property types * - * @return a string value used as the `dataType` field for model templates, `returnType` for api templates + * @return a string value used as the `dataType` field for model templates, `returnType` for api + * templates */ @Override public String getTypeDeclaration(Property p) { @@ -307,8 +301,9 @@ public String toDefaultValue(Property p) { /** - * Optional - swagger type conversion. This is used to map swagger types in a `Property` into - * either language specific types via `typeMapping` or into complex models if there is not a mapping. + * Optional - swagger type conversion. This is used to map swagger types in a `Property` into + * either language specific types via `typeMapping` or into complex models if there is not a + * mapping. * * @return a string value of the type or complex model for this property * @see io.swagger.models.properties.Property @@ -333,11 +328,9 @@ public String getSwaggerType(Property p) { @Override public String toModelName(String type) { - if (typeMapping.keySet().contains(type) || - typeMapping.values().contains(type) || - importMapping.values().contains(type) || - defaultIncludes.contains(type) || - languageSpecificPrimitives.contains(type)) { + if (typeMapping.keySet().contains(type) || typeMapping.values().contains(type) + || importMapping.values().contains(type) || defaultIncludes.contains(type) + || languageSpecificPrimitives.contains(type)) { return type; } else { return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1); @@ -347,7 +340,8 @@ public String toModelName(String type) { @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'. + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. // if it's all uppper case, convert to lower case if (name.matches("^[A-Z_]*$")) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java index dd35131cb74..a5dbb34b83c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java @@ -26,7 +26,8 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(Rails5ServerCodegen.class); - private static final SimpleDateFormat MIGRATE_FILE_NAME_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss"); + private static final SimpleDateFormat MIGRATE_FILE_NAME_FORMAT = new SimpleDateFormat( + "yyyyMMddHHmmss"); protected String gemName; protected String moduleName; @@ -72,14 +73,11 @@ public Rails5ServerCodegen() { typeMapping.clear(); languageSpecificPrimitives.clear(); - setReservedWordsLowerCase( - Arrays.asList( - "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", - "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", - "break", "do", "false", "next", "rescue", "then", "when", "END", "case", - "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", - "if", "not", "return", "undef", "yield") - ); + setReservedWordsLowerCase(Arrays.asList("__FILE__", "and", "def", "end", "in", "or", + "self", "unless", "__LINE__", "begin", "defined?", "ensure", "module", "redo", + "super", "until", "BEGIN", "break", "do", "false", "next", "rescue", "then", + "when", "END", "case", "else", "for", "nil", "retry", "true", "while", "alias", + "class", "elsif", "if", "not", "return", "undef", "yield")); typeMapping.put("string", "string"); typeMapping.put("char", "string"); @@ -106,7 +104,7 @@ public void processOpts() { super.processOpts(); // use constant model/api package (folder path) - //setModelPackage("models"); + // setModelPackage("models"); setApiPackage("app/controllers"); supportingFiles.add(new SupportingFile("Gemfile", "", "Gemfile")); @@ -114,30 +112,48 @@ public void processOpts() { supportingFiles.add(new SupportingFile("Rakefile", "", "Rakefile")); supportingFiles.add(new SupportingFile("config.ru", "", "config.ru")); supportingFiles.add(new SupportingFile("channel.rb", applicationCableFolder, "channel.rb")); - supportingFiles.add(new SupportingFile("connection.rb", applicationCableFolder, "connection.rb")); - supportingFiles.add(new SupportingFile("application_controller.rb", controllersFolder, "application_controller.rb")); - supportingFiles.add(new SupportingFile("application_job.rb", jobsFolder, "application_job.rb")); - supportingFiles.add(new SupportingFile("application_mailer.rb", mailersFolder, "application_mailer.rb")); - supportingFiles.add(new SupportingFile("application_record.rb", modelsFolder, "application_record.rb")); - supportingFiles.add(new SupportingFile("mailer.html.erb", layoutsFolder, "mailer.html.erb")); - supportingFiles.add(new SupportingFile("mailer.text.erb", layoutsFolder, "mailer.text.erb")); + supportingFiles.add(new SupportingFile("connection.rb", applicationCableFolder, + "connection.rb")); + supportingFiles.add(new SupportingFile("application_controller.rb", controllersFolder, + "application_controller.rb")); + supportingFiles.add(new SupportingFile("application_job.rb", jobsFolder, + "application_job.rb")); + supportingFiles.add(new SupportingFile("application_mailer.rb", mailersFolder, + "application_mailer.rb")); + supportingFiles.add(new SupportingFile("application_record.rb", modelsFolder, + "application_record.rb")); + supportingFiles + .add(new SupportingFile("mailer.html.erb", layoutsFolder, "mailer.html.erb")); + supportingFiles + .add(new SupportingFile("mailer.text.erb", layoutsFolder, "mailer.text.erb")); supportingFiles.add(new SupportingFile("bundle", binFolder, "bundle")); supportingFiles.add(new SupportingFile("rails", binFolder, "rails")); supportingFiles.add(new SupportingFile("rake", binFolder, "rake")); supportingFiles.add(new SupportingFile("setup", binFolder, "setup")); supportingFiles.add(new SupportingFile("update", binFolder, "update")); - supportingFiles.add(new SupportingFile("development.rb", environmentsFolder, "development.rb")); - supportingFiles.add(new SupportingFile("production.rb", environmentsFolder, "production.rb")); - supportingFiles.add(new SupportingFile("active_record_belongs_to_required_by_default.rb", initializersFolder, "active_record_belongs_to_required_by_default.rb")); - supportingFiles.add(new SupportingFile("application_controller_renderer.rb", initializersFolder, "application_controller_renderer.rb")); - supportingFiles.add(new SupportingFile("backtrace_silencers.rb", initializersFolder, "backtrace_silencers.rb")); - supportingFiles.add(new SupportingFile("callback_terminator.rb", initializersFolder, "callback_terminator.rb")); + supportingFiles.add(new SupportingFile("development.rb", environmentsFolder, + "development.rb")); + supportingFiles + .add(new SupportingFile("production.rb", environmentsFolder, "production.rb")); + supportingFiles.add(new SupportingFile("active_record_belongs_to_required_by_default.rb", + initializersFolder, "active_record_belongs_to_required_by_default.rb")); + supportingFiles.add(new SupportingFile("application_controller_renderer.rb", + initializersFolder, "application_controller_renderer.rb")); + supportingFiles.add(new SupportingFile("backtrace_silencers.rb", initializersFolder, + "backtrace_silencers.rb")); + supportingFiles.add(new SupportingFile("callback_terminator.rb", initializersFolder, + "callback_terminator.rb")); supportingFiles.add(new SupportingFile("cors.rb", initializersFolder, "cors.rb")); - supportingFiles.add(new SupportingFile("filter_parameter_logging.rb", initializersFolder, "filter_parameter_logging.rb")); - supportingFiles.add(new SupportingFile("inflections.rb", initializersFolder, "inflections.rb")); - supportingFiles.add(new SupportingFile("mime_types.rb", initializersFolder, "mime_types.rb")); - supportingFiles.add(new SupportingFile("ssl_options.rb", initializersFolder, "ssl_options.rb")); - supportingFiles.add(new SupportingFile("to_time_preserves_timezone.rb", initializersFolder, "to_time_preserves_timezone.rb")); + supportingFiles.add(new SupportingFile("filter_parameter_logging.rb", initializersFolder, + "filter_parameter_logging.rb")); + supportingFiles.add(new SupportingFile("inflections.rb", initializersFolder, + "inflections.rb")); + supportingFiles + .add(new SupportingFile("mime_types.rb", initializersFolder, "mime_types.rb")); + supportingFiles.add(new SupportingFile("ssl_options.rb", initializersFolder, + "ssl_options.rb")); + supportingFiles.add(new SupportingFile("to_time_preserves_timezone.rb", initializersFolder, + "to_time_preserves_timezone.rb")); supportingFiles.add(new SupportingFile("en.yml", localesFolder, "en.yml")); supportingFiles.add(new SupportingFile("application.rb", configFolder, "application.rb")); supportingFiles.add(new SupportingFile("boot.rb", configFolder, "boot.rb")); @@ -149,7 +165,8 @@ public void processOpts() { supportingFiles.add(new SupportingFile("secrets.yml", configFolder, "secrets.yml")); supportingFiles.add(new SupportingFile("spring.rb", configFolder, "spring.rb")); supportingFiles.add(new SupportingFile(".keep", migrateFolder, ".keep")); - supportingFiles.add(new SupportingFile("migrate.mustache", migrateFolder, "0_init_tables.rb")); + supportingFiles.add(new SupportingFile("migrate.mustache", migrateFolder, + "0_init_tables.rb")); supportingFiles.add(new SupportingFile("schema.rb", dbFolder, "schema.rb")); supportingFiles.add(new SupportingFile("seeds.rb", dbFolder, "seeds.rb")); supportingFiles.add(new SupportingFile(".keep", tasksFolder, ".keep")); @@ -157,8 +174,10 @@ public void processOpts() { supportingFiles.add(new SupportingFile("404.html", publicFolder, "404.html")); supportingFiles.add(new SupportingFile("422.html", publicFolder, "422.html")); supportingFiles.add(new SupportingFile("500.html", publicFolder, "500.html")); - supportingFiles.add(new SupportingFile("apple-touch-icon-precomposed.png", publicFolder, "apple-touch-icon-precomposed.png")); - supportingFiles.add(new SupportingFile("apple-touch-icon.png", publicFolder, "apple-touch-icon.png")); + supportingFiles.add(new SupportingFile("apple-touch-icon-precomposed.png", publicFolder, + "apple-touch-icon-precomposed.png")); + supportingFiles.add(new SupportingFile("apple-touch-icon.png", publicFolder, + "apple-touch-icon.png")); supportingFiles.add(new SupportingFile("favicon.ico", publicFolder, "favicon.ico")); supportingFiles.add(new SupportingFile("robots.txt", publicFolder, "robots.txt")); supportingFiles.add(new SupportingFile("robots.txt", publicFolder, "robots.txt")); @@ -186,8 +205,8 @@ public String getHelp() { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -220,7 +239,8 @@ public String toDefaultValue(Property p) { @Override public String toVarName(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare + // the methods parameters as 'final'. // if it's all uppper case, convert to lower case if (name.matches("^[A-Z_]*$")) { @@ -282,7 +302,8 @@ public String toModelFilename(String name) { @Override public String toApiFilename(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare + // the methods parameters as 'final'. // e.g. DefaultController => defaults_controller.rb return underscore(name) + "s_controller"; @@ -301,7 +322,8 @@ public String toApiName(String name) { public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + throw new RuntimeException(operationId + + " (reserved word) cannot be used as method name"); } return underscore(operationId); @@ -309,8 +331,8 @@ public String toOperationId(String operationId) { @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { + Swagger swagger = (Swagger) objs.get("swagger"); + if (swagger != null) { try { objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); } catch (JsonProcessingException e) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index cab74966da1..648a7b264ed 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -73,18 +73,20 @@ public RubyClientCodegen() { modelTestTemplateFiles.put("model_test.mustache", ".rb"); apiTestTemplateFiles.put("api_test.mustache", ".rb"); - setReservedWordsLowerCase( - Arrays.asList( - // local variable names used in API methods (endpoints) - "local_var_path", "query_params", "header_params", "_header_accept", "_header_accept_result", - "_header_content_type", "form_params", "post_body", "auth_names", - // ruby reserved keywords - "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", - "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", - "break", "do", "false", "next", "rescue", "then", "when", "END", "case", - "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", - "if", "not", "return", "undef", "yield") - ); + setReservedWordsLowerCase(Arrays.asList( + // local variable names used in API methods (endpoints) + "local_var_path", "query_params", "header_params", "_header_accept", + "_header_accept_result", + "_header_content_type", + "form_params", + "post_body", + "auth_names", + // ruby reserved keywords + "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", "begin", + "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", "break", "do", + "false", "next", "rescue", "then", "when", "END", "case", "else", "for", "nil", + "retry", "true", "while", "alias", "class", "elsif", "if", "not", "return", + "undef", "yield")); typeMapping.clear(); languageSpecificPrimitives.clear(); @@ -131,38 +133,40 @@ public RubyClientCodegen() { Iterator itr = cliOptions.iterator(); while (itr.hasNext()) { CliOption opt = itr.next(); - if (CodegenConstants.MODEL_PACKAGE.equals(opt.getOpt()) || - CodegenConstants.API_PACKAGE.equals(opt.getOpt())) { + if (CodegenConstants.MODEL_PACKAGE.equals(opt.getOpt()) + || CodegenConstants.API_PACKAGE.equals(opt.getOpt())) { itr.remove(); } } - cliOptions.add(new CliOption(GEM_NAME, "gem name (convention: underscore_case)."). - defaultValue("swagger_client")); - cliOptions.add(new CliOption(MODULE_NAME, "top module name (convention: CamelCase, usually corresponding" + - " to gem name).").defaultValue("SwaggerClient")); + cliOptions.add(new CliOption(GEM_NAME, "gem name (convention: underscore_case).") + .defaultValue("swagger_client")); + cliOptions.add(new CliOption(MODULE_NAME, + "top module name (convention: CamelCase, usually corresponding" + " to gem name).") + .defaultValue("SwaggerClient")); cliOptions.add(new CliOption(GEM_VERSION, "gem version.").defaultValue("1.0.0")); - cliOptions.add(new CliOption(GEM_LICENSE, "gem license. "). - defaultValue("proprietary")); + cliOptions.add(new CliOption(GEM_LICENSE, "gem license. ").defaultValue("proprietary")); - cliOptions.add(new CliOption(GEM_REQUIRED_RUBY_VERSION, "gem required Ruby version. "). - defaultValue(">= 1.9")); + cliOptions.add(new CliOption(GEM_REQUIRED_RUBY_VERSION, "gem required Ruby version. ") + .defaultValue(">= 1.9")); - cliOptions.add(new CliOption(GEM_HOMEPAGE, "gem homepage. "). - defaultValue("http://swagger.io")); + cliOptions.add(new CliOption(GEM_HOMEPAGE, "gem homepage. ") + .defaultValue("http://swagger.io")); - cliOptions.add(new CliOption(GEM_SUMMARY, "gem summary. "). - defaultValue("A ruby wrapper for the swagger APIs")); + cliOptions.add(new CliOption(GEM_SUMMARY, "gem summary. ") + .defaultValue("A ruby wrapper for the swagger APIs")); - cliOptions.add(new CliOption(GEM_DESCRIPTION, "gem description. "). - defaultValue("This gem maps to a swagger API")); + cliOptions.add(new CliOption(GEM_DESCRIPTION, "gem description. ") + .defaultValue("This gem maps to a swagger API")); cliOptions.add(new CliOption(GEM_AUTHOR, "gem author (only one is supported).")); - cliOptions.add(new CliOption(GEM_AUTHOR_EMAIL, "gem author email (only one is supported).")); + cliOptions + .add(new CliOption(GEM_AUTHOR_EMAIL, "gem author email (only one is supported).")); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated"). - defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + "hides the timestamp when files were generated").defaultValue(Boolean.TRUE + .toString())); } @@ -172,10 +176,13 @@ public void processOpts() { // default HIDE_GENERATION_TIMESTAMP to true if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.TRUE.toString()); + } else { + additionalProperties.put( + CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get( + CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } if (additionalProperties.containsKey(GEM_NAME)) { @@ -199,7 +206,7 @@ public void processOpts() { if (additionalProperties.containsKey(GEM_VERSION)) { setGemVersion((String) additionalProperties.get(GEM_VERSION)); - }else { + } else { // not set, pass the default value to template additionalProperties.put(GEM_VERSION, gemVersion); } @@ -245,7 +252,8 @@ public void processOpts() { String gemFolder = libFolder + File.separator + gemName; supportingFiles.add(new SupportingFile("api_client.mustache", gemFolder, "api_client.rb")); supportingFiles.add(new SupportingFile("api_error.mustache", gemFolder, "api_error.rb")); - supportingFiles.add(new SupportingFile("configuration.mustache", gemFolder, "configuration.rb")); + supportingFiles.add(new SupportingFile("configuration.mustache", gemFolder, + "configuration.rb")); supportingFiles.add(new SupportingFile("version.mustache", gemFolder, "version.rb")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); @@ -255,20 +263,26 @@ public void processOpts() { // test files should not be overwritten writeOptional(outputFolder, new SupportingFile("rspec.mustache", "", ".rspec")); - writeOptional(outputFolder, new SupportingFile("spec_helper.mustache", specFolder, "spec_helper.rb")); - writeOptional(outputFolder, new SupportingFile("configuration_spec.mustache", specFolder, "configuration_spec.rb")); - writeOptional(outputFolder, new SupportingFile("api_client_spec.mustache", specFolder, "api_client_spec.rb")); + writeOptional(outputFolder, new SupportingFile("spec_helper.mustache", specFolder, + "spec_helper.rb")); + writeOptional(outputFolder, new SupportingFile("configuration_spec.mustache", specFolder, + "configuration_spec.rb")); + writeOptional(outputFolder, new SupportingFile("api_client_spec.mustache", specFolder, + "api_client_spec.rb")); // not including base object test as the moment as not all API has model - //writeOptional(outputFolder, new SupportingFile("base_object_spec.mustache", specFolder, "base_object_spec.rb")); + // writeOptional(outputFolder, new SupportingFile("base_object_spec.mustache", specFolder, + // "base_object_spec.rb")); } @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, + Map definitions, Swagger swagger) { + CodegenOperation op = + super.fromOperation(path, httpMethod, operation, definitions, swagger); // Set vendor-extension to be used in template: - // x-codegen-hasMoreRequired - // x-codegen-hasMoreOptional - // x-codegen-hasRequiredParams + // x-codegen-hasMoreRequired + // x-codegen-hasMoreOptional + // x-codegen-hasRequiredParams CodegenParameter lastRequired = null; CodegenParameter lastOptional = null; for (CodegenParameter p : op.allParams) { @@ -321,7 +335,7 @@ public String generateModuleName(String gemName) { /** * Generate Ruby gem name from the module name, e.g. use "swagger_client" for "SwaggerClient". * - * @param moduleName Ruby module naame + * @param moduleName Ruby module naame * @return Ruby gem name */ @SuppressWarnings("static-method") @@ -330,8 +344,8 @@ public String generateGemName(String moduleName) { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -339,22 +353,26 @@ public String escapeReservedWord(String name) { @Override public String apiFileFolder() { - return outputFolder + File.separator + libFolder + File.separator + gemName + File.separator + apiPackage.replace("/", File.separator); + return outputFolder + File.separator + libFolder + File.separator + gemName + + File.separator + apiPackage.replace("/", File.separator); } @Override public String modelFileFolder() { - return outputFolder + File.separator + libFolder + File.separator + gemName + File.separator + modelPackage.replace("/", File.separator); + return outputFolder + File.separator + libFolder + File.separator + gemName + + File.separator + modelPackage.replace("/", File.separator); } @Override public String apiTestFileFolder() { - return outputFolder + File.separator + specFolder + File.separator + apiPackage.replace("/", File.separator); + return outputFolder + File.separator + specFolder + File.separator + + apiPackage.replace("/", File.separator); } @Override public String modelTestFileFolder() { - return outputFolder + File.separator + specFolder + File.separator + modelPackage.replace("/", File.separator); + return outputFolder + File.separator + specFolder + File.separator + + modelPackage.replace("/", File.separator); } @Override @@ -439,7 +457,8 @@ public String getSwaggerType(Property p) { @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'. + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. // if it's all uppper case, convert to lower case if (name.matches("^[A-Z_]*$")) { name = name.toLowerCase(); @@ -465,7 +484,8 @@ public String toParamName(String name) { @Override public String toModelName(String name) { - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. if (!StringUtils.isEmpty(modelNamePrefix)) { name = modelNamePrefix + "_" + name; @@ -478,13 +498,16 @@ public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { String modelName = camelize("Model" + name); - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + modelName); return modelName; } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -495,7 +518,8 @@ public String toModelName(String name) { @Override public String toModelFilename(String name) { - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. if (!StringUtils.isEmpty(modelNamePrefix)) { name = modelNamePrefix + "_" + name; @@ -507,13 +531,16 @@ public String toModelFilename(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { String filename = underscore("model_" + name); - LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + filename); + LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + + filename); return filename; } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + underscore("model_" + name)); + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + underscore("model_" + name)); name = "model_" + name; // e.g. 200Response => model_200_response } @@ -530,7 +557,8 @@ public String toModelDocFilename(String name) { @Override public String toApiFilename(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare + // the methods parameters as 'final'. // e.g. PhoneNumberApi.rb => phone_number_api.rb return underscore(name) + "_api"; @@ -627,7 +655,8 @@ public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = underscore("call_" + operationId); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + newOperationId); return newOperationId; } @@ -747,7 +776,7 @@ public boolean shouldOverwrite(String filename) { // skip spec file as the file might have been updated with new test cases return !(skipOverwrite && new File(filename).exists()); // - //return super.shouldOverwrite(filename) && !filename.endsWith("_spec.rb"); + // return super.shouldOverwrite(filename) && !filename.endsWith("_spec.rb"); } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java index ea4539133af..5b15378feaa 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java @@ -30,19 +30,20 @@ public ScalaClientCodegen() { apiPackage = "io.swagger.client.api"; modelPackage = "io.swagger.client.model"; - setReservedWordsLowerCase( - Arrays.asList( - // local variable names used in API methods (endpoints) - "path", "contentTypes", "contentType", "queryParams", "headerParams", - "formParams", "postBody", "mp", "basePath", "apiInvoker", - - // scala reserved words - "abstract", "case", "catch", "class", "def", "do", "else", "extends", - "false", "final", "finally", "for", "forSome", "if", "implicit", - "import", "lazy", "match", "new", "null", "object", "override", "package", - "private", "protected", "return", "sealed", "super", "this", "throw", - "trait", "try", "true", "type", "val", "var", "while", "with", "yield") - ); + setReservedWordsLowerCase(Arrays.asList( + // local variable names used in API methods (endpoints) + "path", "contentTypes", "contentType", "queryParams", "headerParams", "formParams", + "postBody", + "mp", + "basePath", + "apiInvoker", + + // scala reserved words + "abstract", "case", "catch", "class", "def", "do", "else", "extends", "false", + "final", "finally", "for", "forSome", "if", "implicit", "import", "lazy", "match", + "new", "null", "object", "override", "package", "private", "protected", "return", + "sealed", "super", "this", "throw", "trait", "try", "true", "type", "val", "var", + "while", "with", "yield")); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.GROUP_ID, groupId); @@ -53,21 +54,23 @@ public ScalaClientCodegen() { additionalProperties.put("authPreemptive", authPreemptive); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - supportingFiles.add(new SupportingFile("apiInvoker.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.scala")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", (sourceFolder + + File.separator + invokerPackage).replace(".", java.io.File.separator), + "ApiInvoker.scala")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); // gradle settings supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); - supportingFiles.add(new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); + supportingFiles.add(new SupportingFile("gradle.properties.mustache", "", + "gradle.properties")); // gradleWrapper files - supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew") ); - supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") ); - supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache", - gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") ); - supportingFiles.add(new SupportingFile( "gradle-wrapper.jar", - gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") ); + supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); + supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat")); + supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache", + gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties")); + supportingFiles.add(new SupportingFile("gradle-wrapper.jar", gradleWrapperPackage.replace( + ".", File.separator), "gradle-wrapper.jar")); supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); @@ -94,7 +97,7 @@ public ScalaClientCodegen() { typeMapping.put("double", "Double"); typeMapping.put("object", "Any"); typeMapping.put("file", "File"); - //TODO binary should be mapped to byte array + // TODO binary should be mapped to byte array // mapped to String as a workaround typeMapping.put("binary", "String"); typeMapping.put("ByteArray", "String"); @@ -102,53 +105,56 @@ public ScalaClientCodegen() { instantiationTypes.put("array", "ListBuffer"); instantiationTypes.put("map", "HashMap"); - cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase")); + cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, + CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase")); } @Override public void processOpts() { super.processOpts(); - + if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) { - setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); + setModelPropertyNaming((String) additionalProperties + .get(CodegenConstants.MODEL_PROPERTY_NAMING)); } } - + public void setModelPropertyNaming(String naming) { - if ("original".equals(naming) || "camelCase".equals(naming) || - "PascalCase".equals(naming) || "snake_case".equals(naming)) { + if ("original".equals(naming) || "camelCase".equals(naming) || "PascalCase".equals(naming) + || "snake_case".equals(naming)) { this.modelPropertyNaming = naming; } else { - throw new IllegalArgumentException("Invalid model property naming '" + - naming + "'. Must be 'original', 'camelCase', " + - "'PascalCase' or 'snake_case'"); + throw new IllegalArgumentException("Invalid model property naming '" + naming + + "'. Must be 'original', 'camelCase', " + "'PascalCase' or 'snake_case'"); } } public String getModelPropertyNaming() { return this.modelPropertyNaming; } + @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("_".equals(name)) { - name = "_u"; + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. + + if ("_".equals(name)) { + name = "_u"; } - + // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) { return name; } - + name = getNameUsingModelPropertyNaming(name); - + // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { name = escapeReservedWord(name); } - + return name; } @@ -160,13 +166,17 @@ public String toParamName(String name) { public String getNameUsingModelPropertyNaming(String name) { switch (CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.valueOf(getModelPropertyNaming())) { - case original: return name; - case camelCase: return camelize(name, true); - case PascalCase: return camelize(name); - case snake_case: return underscore(name); - default: throw new IllegalArgumentException("Invalid model property naming '" + - name + "'. Must be 'original', 'camelCase', " + - "'PascalCase' or 'snake_case'"); + case original: + return name; + case camelCase: + return camelize(name, true); + case PascalCase: + return camelize(name); + case snake_case: + return underscore(name); + default: + throw new IllegalArgumentException("Invalid model property naming '" + name + + "'. Must be 'original', 'camelCase', " + "'PascalCase' or 'snake_case'"); } } @@ -195,7 +205,8 @@ public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + throw new RuntimeException(operationId + + " (reserved word) cannot be used as method name"); } return camelize(operationId, true); @@ -204,25 +215,29 @@ public String toOperationId(String operationId) { @Override public String toModelName(final String name) { final String sanitizedName = sanitizeName(modelNamePrefix + name + modelNameSuffix); - + // camelize the model name // phone_number => PhoneNumber final String camelizedName = camelize(sanitizedName); - + // 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); + LOGGER.warn(camelizedName + + " (reserved word) cannot be used as model name. Renamed to " + modelName); return modelName; } - + // model name starts with number if (name.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); + 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; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java index 065dd8409b5..1519652576d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java @@ -28,40 +28,22 @@ public ScalatraServerCodegen() { apiPackage = "com.wordnik.client.api"; modelPackage = "com.wordnik.client.model"; - setReservedWordsLowerCase( - Arrays.asList( - "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", "type") - ); - - defaultIncludes = new HashSet( - Arrays.asList("double", - "Int", - "Long", - "Float", - "Double", - "char", - "float", - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "List", - "Set", - "Map") - ); + setReservedWordsLowerCase(Arrays.asList("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", "type")); + + defaultIncludes = + new HashSet(Arrays.asList("double", "Int", "Long", "Float", "Double", + "char", "float", "String", "boolean", "Boolean", "Double", "Integer", + "Long", "Float", "List", "Set", "Map")); typeMapping.put("integer", "Int"); typeMapping.put("long", "Long"); - //TODO binary should be mapped to byte array + // TODO binary should be mapped to byte array // mapped to String as a workaround typeMapping.put("binary", "String"); @@ -79,10 +61,14 @@ public ScalatraServerCodegen() { supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt")); supportingFiles.add(new SupportingFile("web.xml", "/src/main/webapp/WEB-INF", "web.xml")); - supportingFiles.add(new SupportingFile("JettyMain.mustache", sourceFolder, "JettyMain.scala")); - supportingFiles.add(new SupportingFile("Bootstrap.mustache", sourceFolder, "ScalatraBootstrap.scala")); - supportingFiles.add(new SupportingFile("ServletApp.mustache", sourceFolder, "ServletApp.scala")); - supportingFiles.add(new SupportingFile("project/build.properties", "project", "build.properties")); + supportingFiles.add(new SupportingFile("JettyMain.mustache", sourceFolder, + "JettyMain.scala")); + supportingFiles.add(new SupportingFile("Bootstrap.mustache", sourceFolder, + "ScalatraBootstrap.scala")); + supportingFiles.add(new SupportingFile("ServletApp.mustache", sourceFolder, + "ServletApp.scala")); + supportingFiles.add(new SupportingFile("project/build.properties", "project", + "build.properties")); supportingFiles.add(new SupportingFile("project/plugins.sbt", "project", "plugins.sbt")); supportingFiles.add(new SupportingFile("sbt", "", "sbt")); @@ -127,7 +113,7 @@ public Map postProcessOperations(Map objs) { for (CodegenOperation op : operationList) { // force http method to lower case op.httpMethod = op.httpMethod.toLowerCase(); - + String[] items = op.path.split("/", -1); String scalaPath = ""; int pathParamIndex = 0; @@ -140,7 +126,7 @@ public Map postProcessOperations(Map objs) { scalaPath = scalaPath + items[i]; } - if (i != items.length -1) { + if (i != items.length - 1) { scalaPath = scalaPath + "/"; } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java index 9fe6eb2b34a..62af79dc18c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java @@ -37,10 +37,15 @@ public SilexServerCodegen() { embeddedTemplateDir = templateDir = "silex"; - setReservedWordsLowerCase( - Arrays.asList( - "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor") - ); + setReservedWordsLowerCase(Arrays.asList("__halt_compiler", "abstract", "and", "array", + "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", + "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", + "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", + "extends", "final", "for", "foreach", "function", "global", "goto", "if", + "implements", "include", "include_once", "instanceof", "insteadof", "interface", + "isset", "list", "namespace", "new", "or", "print", "private", "protected", + "public", "require", "require_once", "return", "static", "switch", "throw", + "trait", "try", "unset", "use", "var", "while", "xor")); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.GROUP_ID, groupId); @@ -48,19 +53,9 @@ public SilexServerCodegen() { additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); // ref: http://php.net/manual/en/language.types.intro.php - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "boolean", - "int", - "integer", - "double", - "float", - "string", - "object", - "DateTime", - "mixed", - "number") - ); + languageSpecificPrimitives = + new HashSet(Arrays.asList("boolean", "int", "integer", "double", "float", + "string", "object", "DateTime", "mixed", "number")); instantiationTypes.put("array", "array"); instantiationTypes.put("map", "map"); @@ -81,14 +76,18 @@ public SilexServerCodegen() { typeMapping.put("array", "array"); typeMapping.put("list", "array"); typeMapping.put("object", "object"); - //TODO binary should be mapped to byte array + // TODO binary should be mapped to byte array // mapped to String as a workaround typeMapping.put("binary", "string"); - supportingFiles.add(new SupportingFile("README.mustache", packagePath.replace('/', File.separatorChar), "README.md")); - supportingFiles.add(new SupportingFile("composer.json", packagePath.replace('/', File.separatorChar), "composer.json")); - supportingFiles.add(new SupportingFile("index.mustache", packagePath.replace('/', File.separatorChar), "index.php")); - supportingFiles.add(new SupportingFile(".htaccess", packagePath.replace('/', File.separatorChar), ".htaccess")); + supportingFiles.add(new SupportingFile("README.mustache", packagePath.replace('/', + File.separatorChar), "README.md")); + supportingFiles.add(new SupportingFile("composer.json", packagePath.replace('/', + File.separatorChar), "composer.json")); + supportingFiles.add(new SupportingFile("index.mustache", packagePath.replace('/', + File.separatorChar), "index.php")); + supportingFiles.add(new SupportingFile(".htaccess", packagePath.replace('/', + File.separatorChar), ".htaccess")); } @Override @@ -107,13 +106,13 @@ public String getHelp() { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; } - + @Override public String apiFileFolder() { return (outputFolder + "/" + apiPackage()).replace('/', File.separatorChar); @@ -168,7 +167,8 @@ public String toDefaultValue(Property p) { public String toVarName(String name) { // return the name in underscore style // PhoneNumber => phone_number - name = underscore(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = underscore(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. // parameter name starting with number won't compile // need to escape it by appending _ at the beginning diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java index 32506898bcf..8b03fd1053a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java @@ -43,14 +43,11 @@ public SinatraServerCodegen() { typeMapping.clear(); languageSpecificPrimitives.clear(); - setReservedWordsLowerCase( - Arrays.asList( - "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", - "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", - "break", "do", "false", "next", "rescue", "then", "when", "END", "case", - "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", - "if", "not", "return", "undef", "yield") - ); + setReservedWordsLowerCase(Arrays.asList("__FILE__", "and", "def", "end", "in", "or", + "self", "unless", "__LINE__", "begin", "defined?", "ensure", "module", "redo", + "super", "until", "BEGIN", "break", "do", "false", "next", "rescue", "then", + "when", "END", "case", "else", "for", "nil", "retry", "true", "while", "alias", + "class", "elsif", "if", "not", "return", "undef", "yield")); languageSpecificPrimitives.add("int"); languageSpecificPrimitives.add("array"); @@ -64,7 +61,7 @@ public SinatraServerCodegen() { typeMapping.put("String", "string"); typeMapping.put("List", "array"); typeMapping.put("map", "map"); - //TODO binary should be mapped to byte array + // TODO binary should be mapped to byte array // mapped to String as a workaround typeMapping.put("binary", "string"); @@ -77,7 +74,7 @@ public void processOpts() { super.processOpts(); // use constant model/api package (folder path) - //setModelPackage("models"); + // setModelPackage("models"); setApiPackage("api"); supportingFiles.add(new SupportingFile("my_app.mustache", "", "my_app.rb")); @@ -85,7 +82,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("config.ru", "", "config.ru")); supportingFiles.add(new SupportingFile("Gemfile", "", "Gemfile")); supportingFiles.add(new SupportingFile("README.md", "", "README.md")); - supportingFiles.add(new SupportingFile("swagger.mustache","","swagger.yaml")); + supportingFiles.add(new SupportingFile("swagger.mustache", "", "swagger.yaml")); } @Override @@ -104,8 +101,8 @@ public String getHelp() { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -156,7 +153,8 @@ public String toDefaultValue(Property p) { @Override public String toVarName(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare + // the methods parameters as 'final'. // if it's all uppper case, convert to lower case if (name.matches("^[A-Z_]*$")) { @@ -185,7 +183,8 @@ public String toParamName(String name) { public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + + camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } @@ -198,7 +197,8 @@ public String toModelName(String name) { public String toModelFilename(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + underscore("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + + underscore("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } @@ -210,7 +210,8 @@ public String toModelFilename(String name) { @Override public String toApiFilename(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare + // the methods parameters as 'final'. // e.g. PhoneNumberApi.rb => phone_number_api.rb return underscore(name) + "_api"; @@ -230,7 +231,8 @@ public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = underscore("call_" + operationId); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + newOperationId); return newOperationId; } @@ -239,8 +241,8 @@ public String toOperationId(String operationId) { @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); - if(swagger != null) { + Swagger swagger = (Swagger) objs.get("swagger"); + if (swagger != null) { try { objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); } catch (JsonProcessingException e) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java index 042dd6b1bb0..8db85c4db6f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java @@ -36,7 +36,7 @@ public SlimFrameworkServerCodegen() { invokerPackage = camelize("SwaggerServer"); - //String packagePath = "SwaggerServer"; + // String packagePath = "SwaggerServer"; modelPackage = packagePath + "\\Models"; apiPackage = packagePath; @@ -48,10 +48,15 @@ public SlimFrameworkServerCodegen() { embeddedTemplateDir = templateDir = "slim"; - setReservedWordsLowerCase( - Arrays.asList( - "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor") - ); + setReservedWordsLowerCase(Arrays.asList("__halt_compiler", "abstract", "and", "array", + "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", + "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", + "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", + "extends", "final", "for", "foreach", "function", "global", "goto", "if", + "implements", "include", "include_once", "instanceof", "insteadof", "interface", + "isset", "list", "namespace", "new", "or", "print", "private", "protected", + "public", "require", "require_once", "return", "static", "switch", "throw", + "trait", "try", "unset", "use", "var", "while", "xor")); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.GROUP_ID, groupId); @@ -59,19 +64,9 @@ public SlimFrameworkServerCodegen() { additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); // ref: http://php.net/manual/en/language.types.intro.php - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "boolean", - "int", - "integer", - "double", - "float", - "string", - "object", - "DateTime", - "mixed", - "number") - ); + languageSpecificPrimitives = + new HashSet(Arrays.asList("boolean", "int", "integer", "double", "float", + "string", "object", "DateTime", "mixed", "number")); instantiationTypes.put("array", "array"); instantiationTypes.put("map", "map"); @@ -92,14 +87,18 @@ public SlimFrameworkServerCodegen() { typeMapping.put("array", "array"); typeMapping.put("list", "array"); typeMapping.put("object", "object"); - //TODO binary should be mapped to byte array + // TODO binary should be mapped to byte array // mapped to String as a workaround typeMapping.put("binary", "string"); - supportingFiles.add(new SupportingFile("README.mustache", packagePath.replace('/', File.separatorChar), "README.md")); - supportingFiles.add(new SupportingFile("composer.json", packagePath.replace('/', File.separatorChar), "composer.json")); - supportingFiles.add(new SupportingFile("index.mustache", packagePath.replace('/', File.separatorChar), "index.php")); - supportingFiles.add(new SupportingFile(".htaccess", packagePath.replace('/', File.separatorChar), ".htaccess")); + supportingFiles.add(new SupportingFile("README.mustache", packagePath.replace('/', + File.separatorChar), "README.md")); + supportingFiles.add(new SupportingFile("composer.json", packagePath.replace('/', + File.separatorChar), "composer.json")); + supportingFiles.add(new SupportingFile("index.mustache", packagePath.replace('/', + File.separatorChar), "index.php")); + supportingFiles.add(new SupportingFile(".htaccess", packagePath.replace('/', + File.separatorChar), ".htaccess")); } @Override @@ -118,8 +117,8 @@ public String getHelp() { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -147,8 +146,8 @@ public String getTypeDeclaration(Property p) { return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; } else if (p instanceof RefProperty) { String type = super.getTypeDeclaration(p); - return (!languageSpecificPrimitives.contains(type)) - ? "\\" + modelPackage + "\\" + type : type; + return (!languageSpecificPrimitives.contains(type)) ? "\\" + modelPackage + "\\" + type + : type; } return super.getTypeDeclaration(p); } @@ -192,16 +191,17 @@ public void setParameterNamingConvention(String variableNamingConvention) { @Override public String toVarName(String name) { - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. if ("camelCase".equals(variableNamingConvention)) { // return the name in camelCase style // phone_number => phoneNumber - name = camelize(name, true); + name = camelize(name, true); } else { // default to snake case // return the name in underscore style // PhoneNumber => phone_number - name = underscore(name); + name = underscore(name); } // parameter name starting with number won't compile @@ -238,9 +238,18 @@ public String toModelFilename(String name) { } public String toPackagePath(String packageName, String basePath) { - packageName = packageName.replace(invokerPackage, ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + packageName = packageName.replace(invokerPackage, ""); // FIXME: a parameter should not be + // assigned. Also declare the methods + // parameters as 'final'. if (basePath != null && basePath.length() > 0) { - basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar; // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar; // FIXME: a + // parameter + // should not be + // assigned. Also + // declare the + // methods + // parameters as + // 'final'. } String regFirstPathSeparator; @@ -258,12 +267,12 @@ public String toPackagePath(String packageName, String basePath) { } return (getPackagePath() + File.separatorChar + basePath - // Replace period, backslash, forward slash with file separator in package name - + packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement(File.separator)) - // Trim prefix file separators from package path - .replaceAll(regFirstPathSeparator, "")) - // Trim trailing file separators from the overall path - .replaceAll(regLastPathSeparator+ "$", ""); + // Replace period, backslash, forward slash with file separator in package name + + packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement(File.separator)) + // Trim prefix file separators from package path + .replaceAll(regFirstPathSeparator, "")) + // Trim trailing file separators from the overall path + .replaceAll(regLastPathSeparator + "$", ""); } public String getPackagePath() { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java index f735ef7d555..81153129975 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java @@ -34,7 +34,7 @@ public class SpringCodegen extends AbstractJavaCodegen implements BeanValidation protected boolean async = false; protected String responseWrapper = ""; protected boolean useTags = false; - protected boolean useBeanValidation = true; + protected boolean useBeanValidation = true; public SpringCodegen() { super(); @@ -55,21 +55,33 @@ public SpringCodegen() { cliOptions.add(new CliOption(TITLE, "server title name or client service name")); cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code")); cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code")); - cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files.")); - cliOptions.add(CliOption.newBoolean(DELEGATE_PATTERN, "Whether to generate the server files using the delegate pattern")); - cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation.")); + cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, + "Whether to generate only API interface stubs without the server files.")); + cliOptions.add(CliOption.newBoolean(DELEGATE_PATTERN, + "Whether to generate the server files using the delegate pattern")); + cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, + "Whether to select only one produces/consumes content-type by operation.")); cliOptions.add(CliOption.newBoolean(JAVA_8, "use java8 default interface")); cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers")); - cliOptions.add(new CliOption(RESPONSE_WRAPPER, "wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)")); - cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames")); - cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); - - supportedLibraries.put(DEFAULT_LIBRARY, "Spring-boot Server application using the SpringFox integration."); - supportedLibraries.put(SPRING_MVC_LIBRARY, "Spring-MVC Server application using the SpringFox integration."); - supportedLibraries.put(SPRING_CLOUD_LIBRARY, "Spring-Cloud-Feign client with Spring-Boot auto-configured settings."); + cliOptions + .add(new CliOption( + RESPONSE_WRAPPER, + "wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)")); + cliOptions.add(CliOption.newBoolean(USE_TAGS, + "use tags for creating interface and controller classnames")); + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, + "Use BeanValidation API annotations")); + + supportedLibraries.put(DEFAULT_LIBRARY, + "Spring-boot Server application using the SpringFox integration."); + supportedLibraries.put(SPRING_MVC_LIBRARY, + "Spring-MVC Server application using the SpringFox integration."); + supportedLibraries.put(SPRING_CLOUD_LIBRARY, + "Spring-Cloud-Feign client with Spring-Boot auto-configured settings."); setLibrary(DEFAULT_LIBRARY); - CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); + CliOption library = + new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); library.setDefault(DEFAULT_LIBRARY); library.setEnum(supportedLibraries); library.setDefault(DEFAULT_LIBRARY); @@ -97,7 +109,7 @@ public void processOpts() { // clear model and api doc template as this codegen // does not support auto-generated markdown doc at the moment - //TODO: add doc templates + // TODO: add doc templates modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); @@ -114,15 +126,18 @@ public void processOpts() { } if (additionalProperties.containsKey(INTERFACE_ONLY)) { - this.setInterfaceOnly(Boolean.valueOf(additionalProperties.get(INTERFACE_ONLY).toString())); + this.setInterfaceOnly(Boolean.valueOf(additionalProperties.get(INTERFACE_ONLY) + .toString())); } if (additionalProperties.containsKey(DELEGATE_PATTERN)) { - this.setDelegatePattern(Boolean.valueOf(additionalProperties.get(DELEGATE_PATTERN).toString())); + this.setDelegatePattern(Boolean.valueOf(additionalProperties.get(DELEGATE_PATTERN) + .toString())); } if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) { - this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString())); + this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get( + SINGLE_CONTENT_TYPES).toString())); } if (additionalProperties.containsKey(JAVA_8)) { @@ -140,7 +155,7 @@ public void processOpts() { if (additionalProperties.containsKey(USE_TAGS)) { this.setUseTags(Boolean.valueOf(additionalProperties.get(USE_TAGS).toString())); } - + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION)); } @@ -153,38 +168,50 @@ public void processOpts() { supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); if (this.interfaceOnly && this.delegatePattern) { - throw new IllegalArgumentException( - String.format("Can not generate code with `%s` and `%s` both true.", DELEGATE_PATTERN, INTERFACE_ONLY)); + throw new IllegalArgumentException(String.format( + "Can not generate code with `%s` and `%s` both true.", DELEGATE_PATTERN, + INTERFACE_ONLY)); } if (!this.interfaceOnly) { if (library.equals(DEFAULT_LIBRARY)) { - supportingFiles.add(new SupportingFile("homeController.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java")); - supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache", - (sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java")); - supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", - (sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java")); + supportingFiles.add(new SupportingFile("homeController.mustache", (sourceFolder + + File.separator + configPackage).replace(".", java.io.File.separator), + "HomeController.java")); + supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache", (sourceFolder + + File.separator + basePackage).replace(".", java.io.File.separator), + "Swagger2SpringBoot.java")); + supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", (sourceFolder + + File.separator + basePackage).replace(".", java.io.File.separator), + "RFC3339DateFormat.java")); supportingFiles.add(new SupportingFile("application.mustache", - ("src.main.resources").replace(".", java.io.File.separator), "application.properties")); + ("src.main.resources").replace(".", java.io.File.separator), + "application.properties")); } if (library.equals(SPRING_MVC_LIBRARY)) { - supportingFiles.add(new SupportingFile("webApplication.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebApplication.java")); + supportingFiles.add(new SupportingFile("webApplication.mustache", (sourceFolder + + File.separator + configPackage).replace(".", java.io.File.separator), + "WebApplication.java")); supportingFiles.add(new SupportingFile("webMvcConfiguration.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebMvcConfiguration.java")); + (sourceFolder + File.separator + configPackage).replace(".", + java.io.File.separator), "WebMvcConfiguration.java")); supportingFiles.add(new SupportingFile("swaggerUiConfiguration.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerUiConfiguration.java")); - supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java")); + (sourceFolder + File.separator + configPackage).replace(".", + java.io.File.separator), "SwaggerUiConfiguration.java")); + supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", (sourceFolder + + File.separator + configPackage).replace(".", java.io.File.separator), + "RFC3339DateFormat.java")); supportingFiles.add(new SupportingFile("application.properties", - ("src.main.resources").replace(".", java.io.File.separator), "swagger.properties")); + ("src.main.resources").replace(".", java.io.File.separator), + "swagger.properties")); } if (library.equals(SPRING_CLOUD_LIBRARY)) { supportingFiles.add(new SupportingFile("apiKeyRequestInterceptor.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ApiKeyRequestInterceptor.java")); + (sourceFolder + File.separator + configPackage).replace(".", + java.io.File.separator), "ApiKeyRequestInterceptor.java")); supportingFiles.add(new SupportingFile("clientConfiguration.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ClientConfiguration.java")); + (sourceFolder + File.separator + configPackage).replace(".", + java.io.File.separator), "ClientConfiguration.java")); apiTemplateFiles.put("apiClient.mustache", "Client.java"); if (!additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) { additionalProperties.put(SINGLE_CONTENT_TYPES, "true"); @@ -194,16 +221,21 @@ public void processOpts() { } else { apiTemplateFiles.put("apiController.mustache", "Controller.java"); - supportingFiles.add(new SupportingFile("apiException.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java")); - supportingFiles.add(new SupportingFile("apiResponseMessage.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java")); - supportingFiles.add(new SupportingFile("notFoundException.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java")); - supportingFiles.add(new SupportingFile("apiOriginFilter.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java")); + supportingFiles.add(new SupportingFile("apiException.mustache", (sourceFolder + + File.separator + apiPackage).replace(".", java.io.File.separator), + "ApiException.java")); + supportingFiles.add(new SupportingFile("apiResponseMessage.mustache", (sourceFolder + + File.separator + apiPackage).replace(".", java.io.File.separator), + "ApiResponseMessage.java")); + supportingFiles.add(new SupportingFile("notFoundException.mustache", (sourceFolder + + File.separator + apiPackage).replace(".", java.io.File.separator), + "NotFoundException.java")); + supportingFiles.add(new SupportingFile("apiOriginFilter.mustache", (sourceFolder + + File.separator + apiPackage).replace(".", java.io.File.separator), + "ApiOriginFilter.java")); supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java")); + (sourceFolder + File.separator + configPackage).replace(".", + java.io.File.separator), "SwaggerDocumentationConfig.java")); } } @@ -236,13 +268,16 @@ public void processOpts() { case "Future": case "Callable": case "CompletableFuture": - additionalProperties.put(RESPONSE_WRAPPER, "java.util.concurrent" + this.responseWrapper); + additionalProperties.put(RESPONSE_WRAPPER, "java.util.concurrent" + + this.responseWrapper); break; case "ListenableFuture": - additionalProperties.put(RESPONSE_WRAPPER, "org.springframework.util.concurrent.ListenableFuture"); + additionalProperties.put(RESPONSE_WRAPPER, + "org.springframework.util.concurrent.ListenableFuture"); break; case "DeferredResult": - additionalProperties.put(RESPONSE_WRAPPER, "org.springframework.web.context.request.DeferredResult"); + additionalProperties.put(RESPONSE_WRAPPER, + "org.springframework.web.context.request.DeferredResult"); break; case "HystrixCommand": additionalProperties.put(RESPONSE_WRAPPER, "com.netflix.hystrix.HystrixCommand"); @@ -260,8 +295,9 @@ public void processOpts() { } @Override - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { - if((library.equals(DEFAULT_LIBRARY) || library.equals(SPRING_MVC_LIBRARY)) && !useTags) { + public void addOperationToGroup(String tag, String resourcePath, Operation operation, + CodegenOperation co, Map> operations) { + if ((library.equals(DEFAULT_LIBRARY) || library.equals(SPRING_MVC_LIBRARY)) && !useTags) { String basePath = resourcePath; if (basePath.startsWith("/")) { basePath = basePath.substring(1); @@ -295,7 +331,7 @@ public void preprocessSwagger(Swagger swagger) { swagger.setBasePath(""); } - if(!additionalProperties.containsKey(TITLE)) { + if (!additionalProperties.containsKey(TITLE)) { // From the title, compute a reasonable name for the package and the API String title = swagger.getInfo().getTitle(); @@ -377,7 +413,8 @@ public Map postProcessOperations(Map objs) { String rt = operation.returnType; int end = rt.lastIndexOf(">"); if (end > 0) { - operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim(); + operation.returnType = + rt.substring("Map<".length(), end).split(",")[1].trim(); operation.returnContainer = "Map"; } } else if (operation.returnType.startsWith("Set")) { @@ -396,7 +433,7 @@ public Map postProcessOperations(Map objs) { @Override public Map postProcessSupportingFileData(Map objs) { - if(library.equals(SPRING_CLOUD_LIBRARY)) { + if (library.equals(SPRING_CLOUD_LIBRARY)) { List authMethods = (List) objs.get("authMethods"); if (authMethods != null) { for (CodegenSecurity authMethod : authMethods) { @@ -428,19 +465,29 @@ public void setBasePackage(String configPackage) { this.basePackage = configPackage; } - public void setInterfaceOnly(boolean interfaceOnly) { this.interfaceOnly = interfaceOnly; } + public void setInterfaceOnly(boolean interfaceOnly) { + this.interfaceOnly = interfaceOnly; + } - public void setDelegatePattern(boolean delegatePattern) { this.delegatePattern = delegatePattern; } + public void setDelegatePattern(boolean delegatePattern) { + this.delegatePattern = delegatePattern; + } public void setSingleContentTypes(boolean singleContentTypes) { this.singleContentTypes = singleContentTypes; } - public void setJava8(boolean java8) { this.java8 = java8; } + public void setJava8(boolean java8) { + this.java8 = java8; + } - public void setAsync(boolean async) { this.async = async; } + public void setAsync(boolean async) { + this.async = async; + } - public void setResponseWrapper(String responseWrapper) { this.responseWrapper = responseWrapper; } + public void setResponseWrapper(String responseWrapper) { + this.responseWrapper = responseWrapper; + } public void setUseTags(boolean useTags) { this.useTags = useTags; @@ -454,7 +501,7 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert property.example = null; } - //Add imports for Jackson + // Add imports for Jackson if (!Boolean.TRUE.equals(model.isEnum)) { model.imports.add("JsonProperty"); @@ -462,7 +509,7 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert model.imports.add("JsonValue"); } } else { // enum class - //Needed imports for Jackson's JsonCreator + // Needed imports for Jackson's JsonCreator if (additionalProperties.containsKey("jackson")) { model.imports.add("JsonCreator"); } @@ -473,8 +520,8 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert public Map postProcessModelsEnum(Map objs) { objs = super.postProcessModelsEnum(objs); - //Add imports for Jackson - List> imports = (List>)objs.get("imports"); + // Add imports for Jackson + List> imports = (List>) objs.get("imports"); List models = (List) objs.get("models"); for (Object _mo : models) { Map mo = (Map) _mo; @@ -490,9 +537,9 @@ public Map postProcessModelsEnum(Map objs) { return objs; } - + public void setUseBeanValidation(boolean useBeanValidation) { this.useBeanValidation = useBeanValidation; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java index b2eb5e099b7..9ff762d9d29 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java @@ -28,10 +28,13 @@ public StaticDocCodegen() { apiTemplateFiles.put("operation.mustache", ".html"); embeddedTemplateDir = templateDir = "swagger-static"; - cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_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_ID, + CodegenConstants.ARTIFACT_ID_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, + CodegenConstants.ARTIFACT_VERSION_DESC)); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.GROUP_ID, groupId); @@ -40,22 +43,21 @@ public StaticDocCodegen() { supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("main.mustache", "", "main.js")); - supportingFiles.add(new SupportingFile("assets/css/bootstrap-responsive.css", - outputFolder + "/assets/css", "bootstrap-responsive.css")); - supportingFiles.add(new SupportingFile("assets/css/bootstrap.css", - outputFolder + "/assets/css", "bootstrap.css")); + supportingFiles.add(new SupportingFile("assets/css/bootstrap-responsive.css", outputFolder + + "/assets/css", "bootstrap-responsive.css")); + supportingFiles.add(new SupportingFile("assets/css/bootstrap.css", outputFolder + + "/assets/css", "bootstrap.css")); supportingFiles.add(new SupportingFile("assets/css/style.css", outputFolder + "/assets/css", "style.css")); - supportingFiles.add(new SupportingFile("assets/images/logo.png", - outputFolder + "/assets/images", "logo.png")); - supportingFiles.add(new SupportingFile("assets/js/bootstrap.js", - outputFolder + "/assets/js", "bootstrap.js")); - supportingFiles.add(new SupportingFile("assets/js/jquery-1.8.3.min.js", - outputFolder + "/assets/js", "jquery-1.8.3.min.js")); - supportingFiles.add(new SupportingFile("assets/js/main.js", - outputFolder + "/assets/js", "main.js")); - supportingFiles.add(new SupportingFile("index.mustache", - outputFolder, "index.html")); + supportingFiles.add(new SupportingFile("assets/images/logo.png", outputFolder + + "/assets/images", "logo.png")); + supportingFiles.add(new SupportingFile("assets/js/bootstrap.js", outputFolder + + "/assets/js", "bootstrap.js")); + supportingFiles.add(new SupportingFile("assets/js/jquery-1.8.3.min.js", outputFolder + + "/assets/js", "jquery-1.8.3.min.js")); + supportingFiles.add(new SupportingFile("assets/js/main.js", outputFolder + "/assets/js", + "main.js")); + supportingFiles.add(new SupportingFile("index.mustache", outputFolder, "index.html")); instantiationTypes.put("array", "ArrayList"); instantiationTypes.put("map", "HashMap"); @@ -77,8 +79,8 @@ public String getHelp() { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -104,5 +106,5 @@ public String escapeQuotationMark(String input) { public String escapeUnsafeCharacters(String input) { // just return the original string return input; - } + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java index 3fbfd90e5e0..2cc82caa06c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java @@ -36,19 +36,27 @@ public StaticHtml2Generator() { cliOptions.add(new CliOption("appName", "short name of the application")); cliOptions.add(new CliOption("appDescription", "description of the application")); - cliOptions.add(new CliOption("infoUrl", "a URL where users can get more information about the application")); - cliOptions.add(new CliOption("infoEmail", "an email address to contact for inquiries about the application")); + cliOptions.add(new CliOption("infoUrl", + "a URL where users can get more information about the application")); + cliOptions.add(new CliOption("infoEmail", + "an email address to contact for inquiries about the application")); cliOptions.add(new CliOption("licenseInfo", "a short description of the license")); cliOptions.add(new CliOption("licenseUrl", "a URL pointing to the full license")); - cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.PHP_INVOKER_PACKAGE, CodegenConstants.PHP_INVOKER_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.PERL_MODULE_NAME, CodegenConstants.PERL_MODULE_NAME_DESC)); - cliOptions.add(new CliOption(CodegenConstants.PYTHON_PACKAGE_NAME, CodegenConstants.PYTHON_PACKAGE_NAME_DESC)); + cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, + CodegenConstants.INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.PHP_INVOKER_PACKAGE, + CodegenConstants.PHP_INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.PERL_MODULE_NAME, + CodegenConstants.PERL_MODULE_NAME_DESC)); + cliOptions.add(new CliOption(CodegenConstants.PYTHON_PACKAGE_NAME, + CodegenConstants.PYTHON_PACKAGE_NAME_DESC)); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name")); cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC)); - cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC)); - cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC)); - + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, + CodegenConstants.ARTIFACT_ID_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, + CodegenConstants.ARTIFACT_VERSION_DESC)); + additionalProperties.put("appName", "Swagger Sample"); additionalProperties.put("appDescription", "A sample swagger server"); additionalProperties.put("infoUrl", "https://helloreverb.com"); @@ -142,19 +150,21 @@ public void preprocessSwagger(Swagger swagger) { } @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, + Map definitions, Swagger swagger) { + CodegenOperation op = + super.fromOperation(path, httpMethod, operation, definitions, swagger); if (op.returnType != null) { op.returnType = normalizeType(op.returnType); } - //path is an unescaped variable in the mustache template api.mustache line 82 '<&path>' + // path is an unescaped variable in the mustache template api.mustache line 82 '<&path>' op.path = sanitizePath(op.path); // Set vendor-extension to be used in template: - // x-codegen-hasMoreRequired - // x-codegen-hasMoreOptional - // x-codegen-hasRequiredParams + // x-codegen-hasMoreRequired + // x-codegen-hasMoreOptional + // x-codegen-hasRequiredParams CodegenParameter lastRequired = null; CodegenParameter lastOptional = null; for (CodegenParameter p : op.allParams) { @@ -181,7 +191,7 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation private String sanitizePath(String p) { - //prefer replace a ', instead of a fuLL URL encode for readability + // prefer replace a ', instead of a fuLL URL encode for readability return p.replaceAll("'", "%27"); } @@ -205,5 +215,5 @@ public String escapeQuotationMark(String input) { public String escapeUnsafeCharacters(String input) { // just return the original string return input; - } + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java index 2fe4cd7b665..9547098c44c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java @@ -33,15 +33,20 @@ public StaticHtmlGenerator() { cliOptions.add(new CliOption("appName", "short name of the application")); cliOptions.add(new CliOption("appDescription", "description of the application")); - cliOptions.add(new CliOption("infoUrl", "a URL where users can get more information about the application")); - cliOptions.add(new CliOption("infoEmail", "an email address to contact for inquiries about the application")); + cliOptions.add(new CliOption("infoUrl", + "a URL where users can get more information about the application")); + cliOptions.add(new CliOption("infoEmail", + "an email address to contact for inquiries about the application")); cliOptions.add(new CliOption("licenseInfo", "a short description of the license")); cliOptions.add(new CliOption("licenseUrl", "a URL pointing to the full license")); - cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.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_ID, + CodegenConstants.ARTIFACT_ID_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, + CodegenConstants.ARTIFACT_VERSION_DESC)); + additionalProperties.put("appName", "Swagger Sample"); additionalProperties.put("appDescription", "A sample swagger server"); additionalProperties.put("infoUrl", "https://helloreverb.com"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java index 23935e4c557..5a07af388b1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java @@ -54,14 +54,14 @@ public void processSwagger(Swagger swagger) { } @Override - public String escapeQuotationMark(String input) { + public String escapeQuotationMark(String input) { // just return the original string return input; - } + } @Override - public String escapeUnsafeCharacters(String input) { + public String escapeUnsafeCharacters(String input) { // just return the original string return input; - } + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java index ad89a02e269..269b5e87cc1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java @@ -45,7 +45,7 @@ public String getHelp() { @Override public void processOpts() { super.processOpts(); - if(additionalProperties.containsKey(OUTPUT_NAME)) { + if (additionalProperties.containsKey(OUTPUT_NAME)) { this.outputFile = additionalProperties.get(OUTPUT_NAME).toString(); } } @@ -72,6 +72,6 @@ public String escapeQuotationMark(String input) { public String escapeUnsafeCharacters(String input) { // just return the original string return input; - } + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java index 626af3f8265..5565408125e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java @@ -72,49 +72,29 @@ public Swift3Codegen() { apiPackage = File.separator + "APIs"; modelPackage = File.separator + "Models"; - languageSpecificPrimitives = new HashSet<>( - Arrays.asList( - "Int", - "Int32", - "Int64", - "Float", - "Double", - "Bool", - "Void", - "String", - "Character", - "AnyObject", - "Any") - ); - defaultIncludes = new HashSet<>( - Arrays.asList( - "Data", - "Date", - "URL", // for file - "UUID", - "Array", - "Dictionary", - "Set", - "Any", - "Empty", - "AnyObject", - "Any") - ); - reservedWords = new HashSet<>( - Arrays.asList( - // name used by swift client - "ErrorResponse", - - // swift keywords - "Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", "Any", "Error", "URL", - "class", "Class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", - "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", - "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if", - "true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol", - "switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional", - "struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol", - "required", "right", "set", "Type", "unowned", "weak") - ); + languageSpecificPrimitives = + new HashSet<>(Arrays.asList("Int", "Int32", "Int64", "Float", "Double", "Bool", + "Void", "String", "Character", "AnyObject", "Any")); + defaultIncludes = new HashSet<>(Arrays.asList("Data", "Date", "URL", // for file + "UUID", "Array", "Dictionary", "Set", "Any", "Empty", "AnyObject", "Any")); + reservedWords = + new HashSet<>(Arrays.asList( + // name used by swift client + "ErrorResponse", + + // swift keywords + "Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", + "String", "Character", "AnyObject", "Any", "Error", "URL", "class", + "Class", "break", "as", "associativity", "deinit", "case", "dynamicType", + "convenience", "enum", "continue", "false", "dynamic", "extension", + "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", + "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", + "super", "inout", "let", "if", "true", "lazy", "operator", "in", "COLUMN", + "left", "private", "return", "FILE", "mutating", "protocol", "switch", + "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", + "while", "optional", "struct", "override", "subscript", "postfix", + "typealias", "precedence", "var", "prefix", "Protocol", "required", + "right", "set", "Type", "unowned", "weak")); typeMapping = new HashMap<>(); typeMapping.put("array", "Array"); @@ -143,10 +123,14 @@ public Swift3Codegen() { importMapping = new HashMap<>(); cliOptions.add(new CliOption(PROJECT_NAME, "Project name in Xcode")); - cliOptions.add(new CliOption(RESPONSE_AS, "Optionally use libraries to manage response. Currently " + - StringUtils.join(RESPONSE_LIBRARIES, ", ") + " are available.")); - cliOptions.add(new CliOption(UNWRAP_REQUIRED, "Treat 'required' properties in response as non-optional " + - "(which would crash the app if api returns null as opposed to required option specified in json schema")); + cliOptions.add(new CliOption(RESPONSE_AS, + "Optionally use libraries to manage response. Currently " + + StringUtils.join(RESPONSE_LIBRARIES, ", ") + " are available.")); + cliOptions + .add(new CliOption( + UNWRAP_REQUIRED, + "Treat 'required' properties in response as non-optional " + + "(which would crash the app if api returns null as opposed to required option specified in json schema")); cliOptions.add(new CliOption(POD_SOURCE, "Source information used for Podspec")); cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "Version used for Podspec")); cliOptions.add(new CliOption(POD_AUTHORS, "Authors used for Podspec")); @@ -158,9 +142,11 @@ public Swift3Codegen() { cliOptions.add(new CliOption(POD_DESCRIPTION, "Description used for Podspec")); cliOptions.add(new CliOption(POD_SCREENSHOTS, "Screenshots used for Podspec")); cliOptions.add(new CliOption(POD_DOCUMENTATION_URL, "Documentation URL used for Podspec")); - cliOptions.add(new CliOption(SWIFT_USE_API_NAMESPACE, "Flag to make all the API classes inner-class of {{projectName}}API")); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") - .defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(SWIFT_USE_API_NAMESPACE, + "Flag to make all the API classes inner-class of {{projectName}}API")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + "hides the timestamp when files were generated").defaultValue(Boolean.TRUE + .toString())); } @@ -169,10 +155,13 @@ public void processOpts() { super.processOpts(); // default HIDE_GENERATION_TIMESTAMP to true if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.TRUE.toString()); + } else { + additionalProperties.put( + CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get( + CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } // Setup project name @@ -185,7 +174,8 @@ public void processOpts() { // Setup unwrapRequired option, which makes all the properties with "required" non-optional if (additionalProperties.containsKey(UNWRAP_REQUIRED)) { - setUnwrapRequired(Boolean.parseBoolean(String.valueOf(additionalProperties.get(UNWRAP_REQUIRED)))); + setUnwrapRequired(Boolean.parseBoolean(String.valueOf(additionalProperties + .get(UNWRAP_REQUIRED)))); } additionalProperties.put(UNWRAP_REQUIRED, unwrapRequired); @@ -206,9 +196,12 @@ public void processOpts() { additionalProperties.put("useRxSwift", true); } - // Setup swiftUseApiNamespace option, which makes all the API classes inner-class of {{projectName}}API + // Setup swiftUseApiNamespace option, which makes all the API classes inner-class of + // {{projectName}}API if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) { - swiftUseApiNamespace = Boolean.parseBoolean(String.valueOf(additionalProperties.get(SWIFT_USE_API_NAMESPACE))); + swiftUseApiNamespace = + Boolean.parseBoolean(String.valueOf(additionalProperties + .get(SWIFT_USE_API_NAMESPACE))); } additionalProperties.put(SWIFT_USE_API_NAMESPACE, swiftUseApiNamespace); @@ -218,10 +211,12 @@ public void processOpts() { supportingFiles.add(new SupportingFile("Podspec.mustache", "", projectName + ".podspec")); supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); - supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); + supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, + "APIHelper.swift")); supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, "AlamofireImplementations.swift")); - supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); + supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, + "Extensions.swift")); supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift")); supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); @@ -231,25 +226,27 @@ public void processOpts() { @Override protected boolean isReservedWord(String word) { - return word != null && reservedWords.contains(word); //don't lowercase as super does + return word != null && reservedWords.contains(word); // don't lowercase as super does } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } - return "_" + name; // add an underscore to the name + return "_" + name; // add an underscore to the name } - + @Override public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder + modelPackage().replace('.', File.separatorChar); + return outputFolder + File.separator + sourceFolder + + modelPackage().replace('.', File.separatorChar); } @Override public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder + apiPackage().replace('.', File.separatorChar); + return outputFolder + File.separator + sourceFolder + + apiPackage().replace('.', File.separatorChar); } @Override @@ -292,7 +289,8 @@ public boolean isDataTypeBinary(final String dataType) { */ @Override public String toModelName(String name) { - name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as "final" + name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as + // "final" if (!StringUtils.isEmpty(modelNameSuffix)) { // set model suffix name = name + "_" + modelNameSuffix; @@ -309,14 +307,18 @@ public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { String modelName = "Model" + name; - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + modelName); return modelName; } // model name starts with number if (name.matches("^\\d.*")) { - String modelName = "Model" + name; // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + String modelName = "Model" + name; // e.g. 200Response => Model200Response (after + // camelize) + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + modelName); return modelName; } @@ -366,7 +368,8 @@ public String toApiName(String name) { public String toOperationId(String operationId) { operationId = camelize(sanitizeName(operationId), true); - // throw exception if method name is empty. This should not happen but keep the check just in case + // throw exception if method name is empty. This should not happen but keep the check just + // in case if (StringUtils.isEmpty(operationId)) { throw new RuntimeException("Empty method name (operationId) not allowed"); } @@ -374,7 +377,8 @@ public String toOperationId(String operationId) { // 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); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + newOperationId); return newOperationId; } @@ -431,29 +435,32 @@ public String toParamName(String name) { @Override public CodegenModel fromModel(String name, Model model, Map allDefinitions) { CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); - if(codegenModel.description != null) { + if (codegenModel.description != null) { codegenModel.imports.add("ApiModel"); } if (allDefinitions != null) { - String parentSchema = codegenModel.parentSchema; + String parentSchema = codegenModel.parentSchema; - // multilevel inheritance: reconcile properties of all the parents - while (parentSchema != null) { - final Model parentModel = allDefinitions.get(parentSchema); - final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel, allDefinitions); - codegenModel = Swift3Codegen.reconcileProperties(codegenModel, parentCodegenModel); + // multilevel inheritance: reconcile properties of all the parents + while (parentSchema != null) { + final Model parentModel = allDefinitions.get(parentSchema); + final CodegenModel parentCodegenModel = + super.fromModel(codegenModel.parent, parentModel, allDefinitions); + codegenModel = Swift3Codegen.reconcileProperties(codegenModel, parentCodegenModel); - // get the next parent - parentSchema = parentCodegenModel.parentSchema; - } + // get the next parent + parentSchema = parentCodegenModel.parentSchema; + } } return codegenModel; } @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { - path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, + Map definitions, Swagger swagger) { + path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. // issue 3914 - removed logic designed to remove any parameter of type HeaderParameter return super.fromOperation(path, httpMethod, operation, definitions, swagger); } @@ -470,10 +477,7 @@ private static String normalizePath(String path) { String group = matcher.group().substring(1, matcher.group().length() - 1); group = camelize(group, true); - builder - .append("{") - .append(group) - .append("}"); + builder.append("{").append(group).append("}"); cursor = matcher.end(); found = matcher.find(); @@ -532,8 +536,8 @@ public String toEnumVarName(String name, String datatype) { } // Check for numerical conversions - if ("Int".equals(datatype) || "Int32".equals(datatype) || "Int64".equals(datatype) || - "Float".equals(datatype) || "Double".equals(datatype)) { + if ("Int".equals(datatype) || "Int32".equals(datatype) || "Int64".equals(datatype) + || "Float".equals(datatype) || "Double".equals(datatype)) { String varName = "number" + camelize(name); varName = varName.replaceAll("-", "minus"); varName = varName.replaceAll("\\+", "plus"); @@ -548,7 +552,8 @@ public String toEnumVarName(String name, String datatype) { } char[] separators = {'-', '_', ' ', ':', '(', ')'}; - return camelize(WordUtils.capitalizeFully(StringUtils.lowerCase(name), separators).replaceAll("[-_ :\\(\\)]", ""), true); + return camelize(WordUtils.capitalizeFully(StringUtils.lowerCase(name), separators) + .replaceAll("[-_ :\\(\\)]", ""), true); } @Override @@ -558,11 +563,13 @@ public String toEnumName(CodegenProperty property) { // Ensure that the enum type doesn't match a reserved word or // the variable name doesn't match the generated enum type or the // Swift compiler will generate an error - if (isReservedWord(property.datatypeWithEnum) || toVarName(property.name).equals(property.datatypeWithEnum)) { + if (isReservedWord(property.datatypeWithEnum) + || toVarName(property.name).equals(property.datatypeWithEnum)) { enumName = property.datatypeWithEnum + "Enum"; } - // TODO: toModelName already does something for names starting with number, so this code is probably never called + // TODO: toModelName already does something for names starting with number, so this code is + // probably never called if (enumName.matches("\\d.*")) { // starts with number return "_" + enumName; } else { @@ -587,11 +594,13 @@ public String escapeUnsafeCharacters(String input) { return input.replace("*/", "*_/").replace("/*", "/_*"); } - private static CodegenModel reconcileProperties(CodegenModel codegenModel, CodegenModel parentCodegenModel) { + private static CodegenModel reconcileProperties(CodegenModel codegenModel, + CodegenModel parentCodegenModel) { // To support inheritance in this generator, we will analyze // the parent and child models, look for properties that match, and remove // them from the child models and leave them in the parent. - // Because the child models extend the parents, the properties will be available via the parent. + // Because the child models extend the parents, the properties will be available via the + // parent. // Get the properties for the parent and child models final List parentModelCodegenProperties = parentCodegenModel.vars; @@ -603,24 +612,24 @@ private static CodegenModel reconcileProperties(CodegenModel codegenModel, Codeg boolean removedChildProperty = false; for (CodegenProperty parentModelCodegenProperty : parentModelCodegenProperties) { - // Now that we have found a prop in the parent class, - // and search the child class for the same prop. - Iterator iterator = codegenProperties.iterator(); - while (iterator.hasNext()) { - CodegenProperty codegenProperty = iterator.next(); - if (codegenProperty.baseName == parentModelCodegenProperty.baseName) { - // We found a property in the child class that is - // a duplicate of the one in the parent, so remove it. - iterator.remove(); - removedChildProperty = true; - } - } - } - - if(removedChildProperty) { + // Now that we have found a prop in the parent class, + // and search the child class for the same prop. + Iterator iterator = codegenProperties.iterator(); + while (iterator.hasNext()) { + CodegenProperty codegenProperty = iterator.next(); + if (codegenProperty.baseName == parentModelCodegenProperty.baseName) { + // We found a property in the child class that is + // a duplicate of the one in the parent, so remove it. + iterator.remove(); + removedChildProperty = true; + } + } + } + + if (removedChildProperty) { // 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) { + for (CodegenProperty codegenProperty : codegenProperties) { count += 1; codegenProperty.hasMore = (count < numVars) ? true : false; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 01fce85c3db..289962297c1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -41,7 +41,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { public static final String DEFAULT_POD_AUTHORS = "Swagger Codegen"; protected static final String LIBRARY_PROMISE_KIT = "PromiseKit"; protected static final String LIBRARY_RX_SWIFT = "RxSwift"; - protected static final String[] RESPONSE_LIBRARIES = { LIBRARY_PROMISE_KIT, LIBRARY_RX_SWIFT }; + protected static final String[] RESPONSE_LIBRARIES = {LIBRARY_PROMISE_KIT, LIBRARY_RX_SWIFT}; protected String projectName = "SwaggerClient"; protected boolean unwrapRequired; protected boolean swiftUseApiNamespace; @@ -73,47 +73,29 @@ public SwiftCodegen() { apiPackage = File.separator + "APIs"; modelPackage = File.separator + "Models"; - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "Int", - "Int32", - "Int64", - "Float", - "Double", - "Bool", - "Void", - "String", - "Character", - "AnyObject") - ); - defaultIncludes = new HashSet( - Arrays.asList( - "NSData", - "NSDate", - "NSURL", // for file - "NSUUID", - "Array", - "Dictionary", - "Set", - "Any", - "Empty", - "AnyObject") - ); - reservedWords = new HashSet( - Arrays.asList( - // name used by swift client - "ErrorResponse", - - // swift keywords - "Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", - "class", "Class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", - "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", - "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if", - "true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol", - "switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional", - "struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol", - "required", "right", "set", "Type", "unowned", "weak") - ); + languageSpecificPrimitives = + new HashSet(Arrays.asList("Int", "Int32", "Int64", "Float", "Double", + "Bool", "Void", "String", "Character", "AnyObject")); + defaultIncludes = new HashSet(Arrays.asList("NSData", "NSDate", "NSURL", // for file + "NSUUID", "Array", "Dictionary", "Set", "Any", "Empty", "AnyObject")); + reservedWords = + new HashSet(Arrays.asList( + // name used by swift client + "ErrorResponse", + + // swift keywords + "Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", + "String", "Character", "AnyObject", "class", "Class", "break", "as", + "associativity", "deinit", "case", "dynamicType", "convenience", "enum", + "continue", "false", "dynamic", "extension", "default", "is", "didSet", + "func", "do", "nil", "final", "import", "else", "self", "get", "init", + "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", + "if", "true", "lazy", "operator", "in", "COLUMN", "left", "private", + "return", "FILE", "mutating", "protocol", "switch", "FUNCTION", "none", + "public", "where", "LINE", "nonmutating", "static", "while", "optional", + "struct", "override", "subscript", "postfix", "typealias", "precedence", + "var", "prefix", "Protocol", "required", "right", "set", "Type", "unowned", + "weak")); typeMapping = new HashMap(); typeMapping.put("array", "Array"); @@ -142,10 +124,14 @@ public SwiftCodegen() { importMapping = new HashMap(); cliOptions.add(new CliOption(PROJECT_NAME, "Project name in Xcode")); - cliOptions.add(new CliOption(RESPONSE_AS, "Optionally use libraries to manage response. Currently " + - StringUtils.join(RESPONSE_LIBRARIES, ", ") + " are available.")); - cliOptions.add(new CliOption(UNWRAP_REQUIRED, "Treat 'required' properties in response as non-optional " + - "(which would crash the app if api returns null as opposed to required option specified in json schema")); + cliOptions.add(new CliOption(RESPONSE_AS, + "Optionally use libraries to manage response. Currently " + + StringUtils.join(RESPONSE_LIBRARIES, ", ") + " are available.")); + cliOptions + .add(new CliOption( + UNWRAP_REQUIRED, + "Treat 'required' properties in response as non-optional " + + "(which would crash the app if api returns null as opposed to required option specified in json schema")); cliOptions.add(new CliOption(POD_SOURCE, "Source information used for Podspec")); cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "Version used for Podspec")); cliOptions.add(new CliOption(POD_AUTHORS, "Authors used for Podspec")); @@ -157,9 +143,11 @@ public SwiftCodegen() { cliOptions.add(new CliOption(POD_DESCRIPTION, "Description used for Podspec")); cliOptions.add(new CliOption(POD_SCREENSHOTS, "Screenshots used for Podspec")); cliOptions.add(new CliOption(POD_DOCUMENTATION_URL, "Documentation URL used for Podspec")); - cliOptions.add(new CliOption(SWIFT_USE_API_NAMESPACE, "Flag to make all the API classes inner-class of {{projectName}}API")); - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") - .defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(SWIFT_USE_API_NAMESPACE, + "Flag to make all the API classes inner-class of {{projectName}}API")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + "hides the timestamp when files were generated").defaultValue(Boolean.TRUE + .toString())); } @@ -168,10 +156,13 @@ public void processOpts() { super.processOpts(); // default HIDE_GENERATION_TIMESTAMP to true if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { - additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); - } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.TRUE.toString()); + } else { + additionalProperties.put( + CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get( + CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } // Setup project name @@ -184,7 +175,8 @@ public void processOpts() { // Setup unwrapRequired option, which makes all the properties with "required" non-optional if (additionalProperties.containsKey(UNWRAP_REQUIRED)) { - setUnwrapRequired(Boolean.parseBoolean(String.valueOf(additionalProperties.get(UNWRAP_REQUIRED)))); + setUnwrapRequired(Boolean.parseBoolean(String.valueOf(additionalProperties + .get(UNWRAP_REQUIRED)))); } additionalProperties.put(UNWRAP_REQUIRED, unwrapRequired); @@ -192,7 +184,7 @@ public void processOpts() { if (additionalProperties.containsKey(RESPONSE_AS)) { Object responseAsObject = additionalProperties.get(RESPONSE_AS); if (responseAsObject instanceof String) { - setResponseAs(((String)responseAsObject).split(",")); + setResponseAs(((String) responseAsObject).split(",")); } else { setResponseAs((String[]) responseAsObject); } @@ -205,9 +197,12 @@ public void processOpts() { additionalProperties.put("useRxSwift", true); } - // Setup swiftUseApiNamespace option, which makes all the API classes inner-class of {{projectName}}API + // Setup swiftUseApiNamespace option, which makes all the API classes inner-class of + // {{projectName}}API if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) { - swiftUseApiNamespace = Boolean.parseBoolean(String.valueOf(additionalProperties.get(SWIFT_USE_API_NAMESPACE))); + swiftUseApiNamespace = + Boolean.parseBoolean(String.valueOf(additionalProperties + .get(SWIFT_USE_API_NAMESPACE))); } additionalProperties.put(SWIFT_USE_API_NAMESPACE, swiftUseApiNamespace); @@ -217,10 +212,12 @@ public void processOpts() { supportingFiles.add(new SupportingFile("Podspec.mustache", "", projectName + ".podspec")); supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); - supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); + supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, + "APIHelper.swift")); supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, - "AlamofireImplementations.swift")); - supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); + "AlamofireImplementations.swift")); + supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, + "Extensions.swift")); supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift")); supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); @@ -230,25 +227,27 @@ public void processOpts() { @Override protected boolean isReservedWord(String word) { - return word != null && reservedWords.contains(word); //don't lowercase as super does + return word != null && reservedWords.contains(word); // don't lowercase as super does } - + @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; // add an underscore to the name - } + } @Override public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder + modelPackage().replace('.', File.separatorChar); + return outputFolder + File.separator + sourceFolder + + modelPackage().replace('.', File.separatorChar); } @Override public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder + apiPackage().replace('.', File.separatorChar); + return outputFolder + File.separator + sourceFolder + + apiPackage().replace('.', File.separatorChar); } @Override @@ -280,7 +279,7 @@ public String getSwaggerType(Property p) { @Override public boolean isDataTypeBinary(final String dataType) { - return dataType != null && dataType.equals("NSData"); + return dataType != null && dataType.equals("NSData"); } /** @@ -291,7 +290,8 @@ public boolean isDataTypeBinary(final String dataType) { */ @Override public String toModelName(String name) { - name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as "final" + name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as + // "final" if (!StringUtils.isEmpty(modelNameSuffix)) { // set model suffix name = name + "_" + modelNameSuffix; @@ -308,14 +308,18 @@ public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { String modelName = "Model" + name; - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + + modelName); return modelName; } // model name starts with number if (name.matches("^\\d.*")) { - String modelName = "Model" + name; // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + String modelName = "Model" + name; // e.g. 200Response => Model200Response (after + // camelize) + LOGGER.warn(name + + " (model name starts with number) cannot be used as model name. Renamed to " + + modelName); return modelName; } @@ -367,7 +371,7 @@ public CodegenProperty fromProperty(String name, Property p) { if (codegenProperty.isEnum) { List> swiftEnums = new ArrayList>(); List values = (List) codegenProperty.allowableValues.get("values"); - + for (Object value : values) { Map map = new HashMap(); map.put("enum", toSwiftyEnumName(String.valueOf(value))); @@ -376,13 +380,15 @@ public CodegenProperty fromProperty(String name, Property p) { } codegenProperty.allowableValues.put("values", swiftEnums); codegenProperty.datatypeWithEnum = toEnumName(codegenProperty); - //codegenProperty.datatypeWithEnum = - // StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length()); - + // codegenProperty.datatypeWithEnum = + // StringUtils.left(codegenProperty.datatypeWithEnum, + // codegenProperty.datatypeWithEnum.length() - "Enum".length()); + // Ensure that the enum type doesn't match a reserved word or // the variable name doesn't match the generated enum type or the // Swift compiler will generate an error - if (isReservedWord(codegenProperty.datatypeWithEnum) || toVarName(name).equals(codegenProperty.datatypeWithEnum)) { + if (isReservedWord(codegenProperty.datatypeWithEnum) + || toVarName(name).equals(codegenProperty.datatypeWithEnum)) { codegenProperty.datatypeWithEnum = codegenProperty.datatypeWithEnum + "Enum"; } } @@ -401,29 +407,31 @@ public String toSwiftyEnumName(String value) { value = value.replaceAll("\\+", "Plus"); value = value.replaceAll("\\.", "Dot"); } - + // Prevent from breaking properly cased identifier if (value.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) { return value; } char[] separators = {'-', '_', ' ', ':', '/'}; - return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ :/]", ""); + return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll( + "[-_ :/]", ""); } @Override public String toApiName(String name) { - if(name.length() == 0) + if (name.length() == 0) return "DefaultAPI"; return initialCaps(name) + "API"; } @Override public String toOperationId(String operationId) { - operationId = camelize(sanitizeName(operationId), true); + operationId = camelize(sanitizeName(operationId), true); - // throw exception if method name is empty. This should not happen but keep the check just in case + // throw exception if method name is empty. This should not happen but keep the check just + // in case if (StringUtils.isEmpty(operationId)) { throw new RuntimeException("Empty method name (operationId) not allowed"); } @@ -431,7 +439,8 @@ public String toOperationId(String operationId) { // 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); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + + newOperationId); return newOperationId; } @@ -486,8 +495,10 @@ public String toParamName(String name) { } @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { - path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, + Map definitions, Swagger swagger) { + path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the + // methods parameters as 'final'. // issue 3914 - removed logic designed to remove any parameter of type HeaderParameter return super.fromOperation(path, httpMethod, operation, definitions, swagger); } @@ -504,10 +515,7 @@ private static String normalizePath(String path) { String group = matcher.group().substring(1, matcher.group().length() - 1); group = camelize(group, true); - builder - .append("{") - .append(group) - .append("}"); + builder.append("{").append(group).append("}"); cursor = matcher.end(); found = matcher.find(); @@ -547,7 +555,8 @@ public String toEnumDefaultValue(String value, String datatype) { @Override public String toEnumVarName(String name, String datatype) { - // TODO: this code is probably useless, because the var name is computed from the value in map.put("enum", toSwiftyEnumName(value)); + // TODO: this code is probably useless, because the var name is computed from the value in + // map.put("enum", toSwiftyEnumName(value)); // number if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { String varName = name; @@ -573,7 +582,8 @@ public String toEnumVarName(String name, String datatype) { public String toEnumName(CodegenProperty property) { String enumName = toModelName(property.name); - // TODO: toModelName already does something for names starting with number, so this code is probably never called + // TODO: toModelName already does something for names starting with number, so this code is + // probably never called if (enumName.matches("\\d.*")) { // starts with number return "_" + enumName; } else { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java index 5b25ecb44e0..5f7930352be 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java @@ -43,24 +43,16 @@ public TizenClientCodegen() { embeddedTemplateDir = templateDir = "tizen"; modelPackage = ""; - defaultIncludes = new HashSet( - Arrays.asList( - "bool", - "int", - "long") - ); + defaultIncludes = new HashSet(Arrays.asList("bool", "int", "long")); languageSpecificPrimitives = new HashSet(); additionalProperties().put("prefix", PREFIX); setReservedWordsLowerCase( - // VERIFY - Arrays.asList( - "void", "char", "short", "int", "void", "char", "short", "int", - "long", "float", "double", "signed", "unsigned", "id", "const", - "volatile", "in", "out", "inout", "bycopy", "byref", "oneway", - "self", "super" - )); + // VERIFY + Arrays.asList("void", "char", "short", "int", "void", "char", "short", "int", "long", + "float", "double", "signed", "unsigned", "id", "const", "volatile", "in", "out", + "inout", "bycopy", "byref", "oneway", "self", "super")); super.typeMapping = new HashMap(); @@ -76,7 +68,7 @@ public TizenClientCodegen() { typeMapping.put("map", "HashMap"); typeMapping.put("number", "Long"); typeMapping.put("object", PREFIX + "Object"); - //TODO binary should be mapped to byte array + // TODO binary should be mapped to byte array // mapped to String as a workaround typeMapping.put("binary", "String"); @@ -96,21 +88,24 @@ public TizenClientCodegen() { namespaces.put("JsonNumber", "Tizen::Web::Json"); namespaces.put("JsonString", "Tizen::Web::Json"); - foundationClasses = new HashSet( - Arrays.asList( - "String", - "Integer", - "Float") - ); + foundationClasses = new HashSet(Arrays.asList("String", "Integer", "Float")); supportingFiles.clear(); - supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h")); - supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h")); - supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp")); - supportingFiles.add(new SupportingFile("apiclient-header.mustache", sourceFolder, PREFIX + "ApiClient.h")); - supportingFiles.add(new SupportingFile("apiclient-body.mustache", sourceFolder, PREFIX + "ApiClient.cpp")); - supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h")); - supportingFiles.add(new SupportingFile("error-header.mustache", sourceFolder, PREFIX + "Error.h")); - supportingFiles.add(new SupportingFile("error-body.mustache", sourceFolder, PREFIX + "Error.cpp")); + supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + + "ModelFactory.h")); + supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + + "Helpers.h")); + supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + + "Helpers.cpp")); + supportingFiles.add(new SupportingFile("apiclient-header.mustache", sourceFolder, PREFIX + + "ApiClient.h")); + supportingFiles.add(new SupportingFile("apiclient-body.mustache", sourceFolder, PREFIX + + "ApiClient.cpp")); + supportingFiles + .add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h")); + supportingFiles.add(new SupportingFile("error-header.mustache", sourceFolder, PREFIX + + "Error.h")); + supportingFiles.add(new SupportingFile("error-body.mustache", sourceFolder, PREFIX + + "Error.cpp")); } @Override @@ -166,7 +161,8 @@ public String getSwaggerType(Property p) { @Override public String getTypeDeclaration(Property p) { String swaggerType = getSwaggerType(p); - if (languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType)) { + if (languageSpecificPrimitives.contains(swaggerType) + && !foundationClasses.contains(swaggerType)) { return toModelName(swaggerType); } else { return swaggerType + "*"; @@ -175,12 +171,9 @@ public String getTypeDeclaration(Property p) { @Override public String toModelName(String type) { - if (typeMapping.keySet().contains(type) || - typeMapping.values().contains(type) || - foundationClasses.contains(type) || - importMapping.values().contains(type) || - defaultIncludes.contains(type) || - languageSpecificPrimitives.contains(type)) { + if (typeMapping.keySet().contains(type) || typeMapping.values().contains(type) + || foundationClasses.contains(type) || importMapping.values().contains(type) + || defaultIncludes.contains(type) || languageSpecificPrimitives.contains(type)) { return type; } else { return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1); @@ -261,8 +254,8 @@ public String toVarName(String name) { } @Override - public String escapeReservedWord(String name) { - if(this.reservedWordsMappings().containsKey(name)) { + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } return "_" + name; @@ -277,7 +270,8 @@ public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return$ if (isReservedWord(operationId)) { - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + throw new RuntimeException(operationId + + " (reserved word) cannot be used as method name"); } // add_pet_by_id => addPetById diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java index 91ed4f35f86..f8adb5584fe 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java @@ -20,7 +20,8 @@ import io.swagger.models.properties.Property; public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCodegen { - private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm"); + private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat( + "yyyyMMddHHmm"); public static final String NPM_NAME = "npmName"; public static final String NPM_VERSION = "npmVersion"; @@ -38,20 +39,28 @@ public TypeScriptAngular2ClientCodegen() { embeddedTemplateDir = templateDir = "typescript-angular2"; modelTemplateFiles.put("model.mustache", ".ts"); apiTemplateFiles.put("api.mustache", ".ts"); - typeMapping.put("Date","Date"); + typeMapping.put("Date", "Date"); 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_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(NPM_REPOSITORY, + "Use this property to set an url your private npmRepo in the package.json")); + this.cliOptions + .add(new CliOption( + SNAPSHOT, + "When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm", + BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString())); } @Override - protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) { - codegenModel.additionalPropertiesType = getSwaggerType(swaggerModel.getAdditionalProperties()); + protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, + ModelImpl swaggerModel) { + codegenModel.additionalPropertiesType = + getSwaggerType(swaggerModel.getAdditionalProperties()); addImport(codegenModel, codegenModel.additionalPropertiesType); } @@ -68,21 +77,25 @@ public String getHelp() { @Override public void processOpts() { super.processOpts(); - supportingFiles.add(new SupportingFile("models.mustache", modelPackage().replace('.', File.separatorChar), "models.ts")); - supportingFiles.add(new SupportingFile("apis.mustache", apiPackage().replace('.', File.separatorChar), "api.ts")); + supportingFiles.add(new SupportingFile("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("configuration.mustache", getIndexDirectory(), "configuration.ts")); - supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), "variables.ts")); + supportingFiles.add(new SupportingFile("configuration.mustache", getIndexDirectory(), + "configuration.ts")); + supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), + "variables.ts")); supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - if(additionalProperties.containsKey(NPM_NAME)) { + if (additionalProperties.containsKey(NPM_NAME)) { addNpmPackageGeneration(); } } private void addNpmPackageGeneration() { - if(additionalProperties.containsKey(NPM_NAME)) { + if (additionalProperties.containsKey(NPM_NAME)) { this.setNpmName(additionalProperties.get(NPM_NAME).toString()); } @@ -90,8 +103,10 @@ private void addNpmPackageGeneration() { 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())); + 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); @@ -99,11 +114,15 @@ private void addNpmPackageGeneration() { this.setNpmRepository(additionalProperties.get(NPM_REPOSITORY).toString()); } - //Files for building our lib - supportingFiles.add(new SupportingFile("README.mustache", getIndexDirectory(), "README.md")); - supportingFiles.add(new SupportingFile("package.mustache", getIndexDirectory(), "package.json")); - supportingFiles.add(new SupportingFile("typings.mustache", getIndexDirectory(), "typings.json")); - supportingFiles.add(new SupportingFile("tsconfig.mustache", getIndexDirectory(), "tsconfig.json")); + // Files for building our lib + supportingFiles + .add(new SupportingFile("README.mustache", getIndexDirectory(), "README.md")); + supportingFiles.add(new SupportingFile("package.mustache", getIndexDirectory(), + "package.json")); + supportingFiles.add(new SupportingFile("typings.mustache", getIndexDirectory(), + "typings.json")); + supportingFiles.add(new SupportingFile("tsconfig.mustache", getIndexDirectory(), + "tsconfig.json")); } private String getIndexDirectory() { @@ -114,15 +133,15 @@ private String getIndexDirectory() { @Override public String getTypeDeclaration(Property p) { Property inner; - if(p instanceof ArrayProperty) { - ArrayProperty mp1 = (ArrayProperty)p; + if (p instanceof ArrayProperty) { + ArrayProperty mp1 = (ArrayProperty) p; inner = mp1.getItems(); return this.getSwaggerType(p) + "<" + this.getTypeDeclaration(inner) + ">"; - } else if(p instanceof MapProperty) { - MapProperty mp = (MapProperty)p; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; inner = mp.getAdditionalProperties(); return "{ [key: string]: " + this.getTypeDeclaration(inner) + "; }"; - } else if(p instanceof FileProperty || p instanceof ObjectProperty) { + } else if (p instanceof FileProperty || p instanceof ObjectProperty) { return "any"; } else { return super.getTypeDeclaration(p); @@ -132,7 +151,7 @@ public String getTypeDeclaration(Property p) { @Override public String getSwaggerType(Property p) { String swaggerType = super.getSwaggerType(p); - if(isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) { + if (isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) { return swaggerType; } return addModelPrefix(swaggerType); @@ -157,8 +176,8 @@ private boolean isLanguagePrimitive(String type) { } private boolean isLanguageGenericType(String type) { - for (String genericType: languageGenericTypes) { - if (type.startsWith(genericType + "<")) { + for (String genericType : languageGenericTypes) { + if (type.startsWith(genericType + "<")) { return true; } } @@ -201,7 +220,8 @@ public Map postProcessOperations(Map operations) op.httpMethod = "RequestMethod.Patch"; break; default: - throw new RuntimeException("Unknown HTTP Method " + op.httpMethod + " not allowed"); + throw new RuntimeException("Unknown HTTP Method " + op.httpMethod + + " not allowed"); } // Convert path to TypeScript template string diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java index 18c6f72e9cb..2c5be9f19d0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java @@ -8,59 +8,62 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCodegen { - @Override - public String getName() { - return "typescript-angular"; - } + @Override + public String getName() { + return "typescript-angular"; + } - @Override - public String getHelp() { - return "Generates a TypeScript AngularJS client library."; - } + @Override + public String getHelp() { + return "Generates a TypeScript AngularJS client library."; + } - @Override - public void processOpts() { - super.processOpts(); - supportingFiles.add(new SupportingFile("models.mustache", modelPackage().replace('.', File.separatorChar), "models.ts")); - supportingFiles.add(new SupportingFile("apis.mustache", apiPackage().replace('.', File.separatorChar), "api.ts")); + @Override + public void processOpts() { + super.processOpts(); + supportingFiles.add(new SupportingFile("models.mustache", modelPackage().replace('.', + File.separatorChar), "models.ts")); + supportingFiles.add(new SupportingFile("apis.mustache", apiPackage().replace('.', + File.separatorChar), "api.ts")); supportingFiles.add(new SupportingFile("index.mustache", getIndexDirectory(), "index.ts")); - supportingFiles.add(new SupportingFile("api.module.mustache", getIndexDirectory(), "api.module.ts")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); + supportingFiles.add(new SupportingFile("api.module.mustache", getIndexDirectory(), + "api.module.ts")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); - } - - public TypeScriptAngularClientCodegen() { - super(); - outputFolder = "generated-code/typescript-angular"; - modelTemplateFiles.put("model.mustache", ".ts"); + } + + public TypeScriptAngularClientCodegen() { + super(); + outputFolder = "generated-code/typescript-angular"; + modelTemplateFiles.put("model.mustache", ".ts"); apiTemplateFiles.put("api.mustache", ".ts"); - embeddedTemplateDir = templateDir = "typescript-angular"; - apiPackage = "api"; + embeddedTemplateDir = templateDir = "typescript-angular"; + apiPackage = "api"; modelPackage = "model"; - } + } - @Override + @Override public String getSwaggerType(Property p) { String swaggerType = super.getSwaggerType(p); - if(isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) { + if (isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) { return swaggerType; } return addModelPrefix(swaggerType); } - @Override + @Override public void postProcessParameter(CodegenParameter parameter) { super.postProcessParameter(parameter); parameter.dataType = addModelPrefix(parameter.dataType); } - private String getIndexDirectory() { + private String getIndexDirectory() { String indexPackage = modelPackage.substring(0, Math.max(0, modelPackage.lastIndexOf('.'))); return indexPackage.replace('.', File.separatorChar); } - private String addModelPrefix(String swaggerType) { + private String addModelPrefix(String swaggerType) { String type = null; if (typeMapping.containsKey(swaggerType)) { type = typeMapping.get(swaggerType); @@ -74,13 +77,13 @@ private String addModelPrefix(String swaggerType) { return type; } - private boolean isLanguagePrimitive(String type) { + private boolean isLanguagePrimitive(String type) { return languageSpecificPrimitives.contains(type); } private boolean isLanguageGenericType(String type) { - for (String genericType: languageGenericTypes) { - if (type.startsWith(genericType + "<")) { + for (String genericType : languageGenericTypes) { + if (type.startsWith(genericType + "<")) { return true; } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java index a6449587ac3..45f57831528 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java @@ -27,7 +27,8 @@ public TypeScriptFetchClientCodegen() { outputFolder = "generated-code/typescript-fetch"; embeddedTemplateDir = templateDir = "TypeScript-Fetch"; - this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package")); + 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")); } @@ -43,7 +44,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("tslint.json.mustache", "", "tslint.json")); supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); - if(additionalProperties.containsKey(NPM_NAME)) { + if (additionalProperties.containsKey(NPM_NAME)) { this.setNpmName(additionalProperties.get(NPM_NAME).toString()); } @@ -89,7 +90,8 @@ public Map postProcessModels(Map objs) { for (CodegenProperty var : cm.vars) { // name enum with model name, e.g. StatuEnum => PetStatusEnum if (Boolean.TRUE.equals(var.isEnum)) { - var.datatypeWithEnum = var.datatypeWithEnum.replace(var.enumName, cm.classname + var.enumName); + var.datatypeWithEnum = + var.datatypeWithEnum.replace(var.enumName, cm.classname + var.enumName); var.enumName = cm.classname + var.enumName; } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java index 50662a26dd5..4808f4cc2d6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java @@ -15,7 +15,8 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptNodeClientCodegen.class); - private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm"); + private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat( + "yyyyMMddHHmm"); public static final String NPM_NAME = "npmName"; public static final String NPM_VERSION = "npmVersion"; @@ -38,10 +39,16 @@ public TypeScriptNodeClientCodegen() { outputFolder = "generated-code/typescript-node"; embeddedTemplateDir = templateDir = "typescript-node"; - this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package")); + 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(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())); } @@ -52,13 +59,13 @@ public void processOpts() { supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); - if(additionalProperties.containsKey(NPM_NAME)) { + if (additionalProperties.containsKey(NPM_NAME)) { addNpmPackageGeneration(); } } private void addNpmPackageGeneration() { - if(additionalProperties.containsKey(NPM_NAME)) { + if (additionalProperties.containsKey(NPM_NAME)) { this.setNpmName(additionalProperties.get(NPM_NAME).toString()); } @@ -66,8 +73,10 @@ private void addNpmPackageGeneration() { 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())); + 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); @@ -75,10 +84,13 @@ private void addNpmPackageGeneration() { this.setNpmRepository(additionalProperties.get(NPM_REPOSITORY).toString()); } - //Files for building our lib - supportingFiles.add(new SupportingFile("package.mustache", getPackageRootDirectory(), "package.json")); - supportingFiles.add(new SupportingFile("typings.mustache", getPackageRootDirectory(), "typings.json")); - supportingFiles.add(new SupportingFile("tsconfig.mustache", getPackageRootDirectory(), "tsconfig.json")); + // Files for building our lib + supportingFiles.add(new SupportingFile("package.mustache", getPackageRootDirectory(), + "package.json")); + supportingFiles.add(new SupportingFile("typings.mustache", getPackageRootDirectory(), + "typings.json")); + supportingFiles.add(new SupportingFile("tsconfig.mustache", getPackageRootDirectory(), + "tsconfig.json")); } private String getPackageRootDirectory() { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/UndertowCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/UndertowCodegen.java index b212e42a316..ad6b9402846 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/UndertowCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/UndertowCodegen.java @@ -20,6 +20,7 @@ public class UndertowCodegen extends AbstractJavaCodegen { protected String title = "Swagger Undertow Server"; protected String implFolder = "src/main/java"; + public UndertowCodegen() { super(); @@ -28,17 +29,19 @@ public UndertowCodegen() { embeddedTemplateDir = templateDir = "undertow"; invokerPackage = "io.swagger.handler"; artifactId = "swagger-undertow-server"; - dateLibrary = "legacy"; //TODO: add joda support + dateLibrary = "legacy"; // TODO: add joda support // clear model and api doc template as this codegen // does not support auto-generated markdown doc at the moment - //TODO: add doc templates + // TODO: add doc templates modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); - apiPackage = System.getProperty("swagger.codegen.undertow.apipackage", "io.swagger.handler"); - modelPackage = System.getProperty("swagger.codegen.undertow.modelpackage", "io.swagger.model"); + apiPackage = + System.getProperty("swagger.codegen.undertow.apipackage", "io.swagger.handler"); + modelPackage = + System.getProperty("swagger.codegen.undertow.modelpackage", "io.swagger.model"); additionalProperties.put("title", title); } @@ -68,14 +71,22 @@ public void processOpts() { writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); // keep the yaml in config folder for framework validation. - supportingFiles.add(new SupportingFile("swagger.mustache", ("src.main.resources.config").replace(".", java.io.File.separator), "swagger.json")); - supportingFiles.add(new SupportingFile("handler.mustache", ("src.main.java.io.swagger.handler").replace(".", java.io.File.separator), "PathHandlerProvider.java")); - supportingFiles.add(new SupportingFile("service.mustache", ("src.main.resources.META-INF.services").replace(".", java.io.File.separator), "com.networknt.server.HandlerProvider")); + supportingFiles.add(new SupportingFile("swagger.mustache", ("src.main.resources.config") + .replace(".", java.io.File.separator), "swagger.json")); + supportingFiles.add(new SupportingFile("handler.mustache", + ("src.main.java.io.swagger.handler").replace(".", java.io.File.separator), + "PathHandlerProvider.java")); + supportingFiles.add(new SupportingFile("service.mustache", + ("src.main.resources.META-INF.services").replace(".", java.io.File.separator), + "com.networknt.server.HandlerProvider")); // configuration files - supportingFiles.add(new SupportingFile("server.json", ("src.main.resources.config").replace(".", java.io.File.separator), "server.json")); - supportingFiles.add(new SupportingFile("security.json", ("src.main.resources.config").replace(".", java.io.File.separator), "security.json")); - supportingFiles.add(new SupportingFile("primary.crt", ("src.main.resources.config.oauth").replace(".", java.io.File.separator), "primary.crt")); + supportingFiles.add(new SupportingFile("server.json", ("src.main.resources.config") + .replace(".", java.io.File.separator), "server.json")); + supportingFiles.add(new SupportingFile("security.json", ("src.main.resources.config") + .replace(".", java.io.File.separator), "security.json")); + supportingFiles.add(new SupportingFile("primary.crt", ("src.main.resources.config.oauth") + .replace(".", java.io.File.separator), "primary.crt")); } @@ -148,11 +159,11 @@ public Map postProcessOperations(Map objs) { public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); - //Add imports for Jackson - if(!BooleanUtils.toBoolean(model.isEnum)) { + // Add imports for Jackson + if (!BooleanUtils.toBoolean(model.isEnum)) { model.imports.add("JsonProperty"); - if(BooleanUtils.toBoolean(model.hasEnums)) { + if (BooleanUtils.toBoolean(model.hasEnums)) { model.imports.add("JsonValue"); } } @@ -162,8 +173,8 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert public Map postProcessModelsEnum(Map objs) { objs = super.postProcessModelsEnum(objs); - //Add imports for Jackson - List> imports = (List>)objs.get("imports"); + // Add imports for Jackson + List> imports = (List>) objs.get("imports"); List models = (List) objs.get("models"); for (Object _mo : models) { Map mo = (Map) _mo; @@ -183,7 +194,7 @@ public Map postProcessModelsEnum(Map objs) { public String apiFilename(String templateName, String tag) { String result = super.apiFilename(templateName, tag); - if ( templateName.endsWith("api.mustache") ) { + if (templateName.endsWith("api.mustache")) { int ix = result.indexOf(sourceFolder); String beg = result.substring(0, ix); String end = result.substring(ix + sourceFolder.length()); @@ -195,11 +206,11 @@ public String apiFilename(String templateName, String tag) { @Override public Map postProcessSupportingFileData(Map objs) { - Swagger swagger = (Swagger)objs.get("swagger"); + Swagger swagger = (Swagger) objs.get("swagger"); System.out.println("swagger" + swagger.toString()); - if(swagger != null) { + if (swagger != null) { try { - //objs.put("swagger-json", Json.mapper().writeValueAsString(swagger)); + // objs.put("swagger-json", Json.mapper().writeValueAsString(swagger)); objs.put("swagger-json", Json.pretty().writeValueAsString(swagger)); } catch (JsonProcessingException e) { LOGGER.error(e.getMessage(), e); @@ -213,7 +224,9 @@ public String toApiName(String name) { if (name.length() == 0) { return "DefaultHandler"; } - name = name.replaceAll("[^a-zA-Z0-9]+", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - return camelize(name)+ "Handler"; + name = name.replaceAll("[^a-zA-Z0-9]+", "_"); // FIXME: a parameter should not be assigned. + // Also declare the methods parameters as + // 'final'. + return camelize(name) + "Handler"; } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ZendExpressivePathHandlerServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ZendExpressivePathHandlerServerCodegen.java index 12328c64d58..e299ac8cc62 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ZendExpressivePathHandlerServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ZendExpressivePathHandlerServerCodegen.java @@ -4,7 +4,6 @@ import io.swagger.models.Operation; import org.apache.commons.lang3.StringUtils; - import java.io.File; import java.util.ArrayList; import java.util.HashMap; @@ -45,39 +44,50 @@ public ZendExpressivePathHandlerServerCodegen() { modelDocTemplateFiles.clear(); supportingFiles.add(new SupportingFile("README.md.mustache", packagePath, "README.md")); - supportingFiles.add(new SupportingFile("composer.json.mustache", packagePath, "composer.json")); - supportingFiles.add(new SupportingFile("index.php", packagePath + File.separator + "public", "index.php")); - supportingFiles.add(new SupportingFile("container.php", packagePath + File.separator + "application", "container.php")); - supportingFiles.add(new SupportingFile("config.yml", packagePath + File.separator + "application", "config.yml")); - supportingFiles.add(new SupportingFile("app.yml.mustache", packagePath + File.separator + "application" + File.separator + "config", "app.yml")); - supportingFiles.add(new SupportingFile("path_handler.yml.mustache", packagePath + File.separator + "application" + File.separator + "config", "path_handler.yml")); - supportingFiles.add(new SupportingFile("data_transfer.yml.mustache", packagePath + File.separator + "application" + File.separator + "config", "data_transfer.yml")); - supportingFiles.add(new SupportingFile("Date.php.mustache", packagePath + File.separator + srcBasePath + File.separator + "Strategy", "Date.php")); - supportingFiles.add(new SupportingFile("DateTime.php.mustache", packagePath + File.separator + srcBasePath + File.separator + "Strategy", "DateTime.php")); - supportingFiles.add(new SupportingFile("Type.php.mustache", packagePath + File.separator + srcBasePath + File.separator + "Validator", "Type.php")); - supportingFiles.add(new SupportingFile("ErrorMiddleware.php.mustache", packagePath + File.separator + srcBasePath, "ErrorMiddleware.php")); + supportingFiles.add(new SupportingFile("composer.json.mustache", packagePath, + "composer.json")); + supportingFiles.add(new SupportingFile("index.php", + packagePath + File.separator + "public", "index.php")); + supportingFiles.add(new SupportingFile("container.php", packagePath + File.separator + + "application", "container.php")); + supportingFiles.add(new SupportingFile("config.yml", packagePath + File.separator + + "application", "config.yml")); + supportingFiles.add(new SupportingFile("app.yml.mustache", packagePath + File.separator + + "application" + File.separator + "config", "app.yml")); + supportingFiles.add(new SupportingFile("path_handler.yml.mustache", packagePath + + File.separator + "application" + File.separator + "config", "path_handler.yml")); + supportingFiles.add(new SupportingFile("data_transfer.yml.mustache", packagePath + + File.separator + "application" + File.separator + "config", "data_transfer.yml")); + supportingFiles.add(new SupportingFile("Date.php.mustache", packagePath + File.separator + + srcBasePath + File.separator + "Strategy", "Date.php")); + supportingFiles.add(new SupportingFile("DateTime.php.mustache", packagePath + + File.separator + srcBasePath + File.separator + "Strategy", "DateTime.php")); + supportingFiles.add(new SupportingFile("Type.php.mustache", packagePath + File.separator + + srcBasePath + File.separator + "Validator", "Type.php")); + supportingFiles.add(new SupportingFile("ErrorMiddleware.php.mustache", packagePath + + File.separator + srcBasePath, "ErrorMiddleware.php")); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, "1.0.0"); } /** - * Add operation to group - * Override of default grouping - group by resource path, not tag + * Add operation to group Override of default grouping - group by resource path, not tag * - * @param tag name of the tag + * @param tag name of the tag * @param resourcePath path of the resource - * @param operation Swagger Operation object - * @param co Codegen Operation object - * @param operations map of Codegen operations + * @param operation Swagger Operation object + * @param co Codegen Operation object + * @param operations map of Codegen operations */ @Override - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + public void addOperationToGroup(String tag, String resourcePath, Operation operation, + CodegenOperation co, Map> operations) { List opList = operations.get(resourcePath); if (opList == null) { opList = new ArrayList(); operations.put(resourcePath, opList); } - //ignore duplicate operation ids - that means that operation has several tags + // ignore duplicate operation ids - that means that operation has several tags int counter = 0; for (CodegenOperation op : opList) { if (co.operationId.equals(op.operationId)) { @@ -103,15 +113,15 @@ public String toApiFilename(String name) { } /** - * Output the API (class) name (capitalized) ending with "Api" - * Return DefaultApi if name is empty + * Output the API (class) name (capitalized) ending with "Api" Return DefaultApi if name is + * empty * * @param name the name of the Api * @return capitalized Api name ending with "Api" */ @Override public String toApiName(String name) { - //Remove } + // Remove } name = name.replaceAll("[\\}]", ""); return super.toModelName(name); } @@ -147,7 +157,8 @@ public Map postProcessOperations(Map objs) { classMethod = "handleDelete"; break; default: - throw new RuntimeException("Unknown HTTP Method " + op.httpMethod + " not allowed"); + throw new RuntimeException("Unknown HTTP Method " + op.httpMethod + + " not allowed"); } if (interfacesToImplement.length() > 0) { interfacesToImplement.append(", "); @@ -181,10 +192,11 @@ public Map postProcessSupportingFileData(Map obj return objs; } - private void insertRoute(List> routes, String[] urlParts, int currentUrlPartIndex, String handler) { + private void insertRoute(List> routes, String[] urlParts, + int currentUrlPartIndex, String handler) { if (urlParts.length > currentUrlPartIndex) { String urlPart = urlParts[currentUrlPartIndex]; - //List> subRoutes = null; + // List> subRoutes = null; Map currentRoute = null; for (Map route : routes) { if (urlPart.equals(route.get("name"))) { @@ -208,7 +220,8 @@ private void insertRoute(List> routes, String[] urlParts, in routes.add(currentRoute); } - List> subRoutes = (List>) currentRoute.get("children"); + List> subRoutes = + (List>) currentRoute.get("children"); insertRoute(subRoutes, urlParts, currentUrlPartIndex + 1, handler); currentRoute.put("hasChildren", !subRoutes.isEmpty()); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/BeanValidationExtendedFeatures.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/BeanValidationExtendedFeatures.java index 274ce720efc..2a83d021ce9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/BeanValidationExtendedFeatures.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/BeanValidationExtendedFeatures.java @@ -4,8 +4,8 @@ public interface BeanValidationExtendedFeatures { // Language (implementing Client/Server) supports automatic BeanValidation (1.1) public static final String USE_BEANVALIDATION_FEATURE = "useBeanValidationFeature"; - + public void setUseBeanValidationFeature(boolean useBeanValidationFeature); - + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/BeanValidationFeatures.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/BeanValidationFeatures.java index 6818c29059d..69ef207da0f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/BeanValidationFeatures.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/BeanValidationFeatures.java @@ -4,7 +4,7 @@ public interface BeanValidationFeatures { // Language supports generating BeanValidation-Annotations public static final String USE_BEANVALIDATION = "useBeanValidation"; - + public void setUseBeanValidation(boolean useBeanValidation); - + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/CXFServerFeatures.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/CXFServerFeatures.java index 78e4f3decc9..b996a274622 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/CXFServerFeatures.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/CXFServerFeatures.java @@ -1,32 +1,30 @@ -package io.swagger.codegen.languages.features; - -/** - * Features supported by CXF 3 server - * - */ -public interface CXFServerFeatures - extends CXFFeatures, SwaggerFeatures, SpringFeatures, JbossFeature, BeanValidationExtendedFeatures, - SwaggerUIFeatures -{ - - public static final String USE_WADL_FEATURE = "useWadlFeature"; - - public static final String USE_MULTIPART_FEATURE = "useMultipartFeature"; - - public static final String ADD_CONSUMES_PRODUCES_JSON = "addConsumesProducesJson"; - - public static final String USE_ANNOTATED_BASE_PATH = "useAnnotatedBasePath"; - - public static final String GENERATE_NON_SPRING_APPLICATION = "generateNonSpringApplication"; - - public void setUseWadlFeature(boolean useWadlFeature); - - public void setUseMultipartFeature(boolean useMultipartFeature); - - public void setAddConsumesProducesJson(boolean addConsumesProducesJson); - - public void setUseAnnotatedBasePath(boolean useAnnotatedBasePath); - - public void setGenerateNonSpringApplication(boolean generateNonSpringApplication); - -} +package io.swagger.codegen.languages.features; + +/** + * Features supported by CXF 3 server + * + */ +public interface CXFServerFeatures extends CXFFeatures, SwaggerFeatures, SpringFeatures, + JbossFeature, BeanValidationExtendedFeatures, SwaggerUIFeatures { + + public static final String USE_WADL_FEATURE = "useWadlFeature"; + + public static final String USE_MULTIPART_FEATURE = "useMultipartFeature"; + + public static final String ADD_CONSUMES_PRODUCES_JSON = "addConsumesProducesJson"; + + public static final String USE_ANNOTATED_BASE_PATH = "useAnnotatedBasePath"; + + public static final String GENERATE_NON_SPRING_APPLICATION = "generateNonSpringApplication"; + + public void setUseWadlFeature(boolean useWadlFeature); + + public void setUseMultipartFeature(boolean useMultipartFeature); + + public void setAddConsumesProducesJson(boolean addConsumesProducesJson); + + public void setUseAnnotatedBasePath(boolean useAnnotatedBasePath); + + public void setGenerateNonSpringApplication(boolean generateNonSpringApplication); + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/GzipFeatures.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/GzipFeatures.java index 4cb9955187e..873cc4e6280 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/GzipFeatures.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/GzipFeatures.java @@ -1,7 +1,7 @@ package io.swagger.codegen.languages.features; public interface GzipFeatures { - + public static final String USE_GZIP_FEATURE = "useGzipFeature"; public void setUseGzipFeature(boolean useGzipFeature); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/JbossFeature.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/JbossFeature.java index 9cbbd34be81..75870b9926a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/JbossFeature.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/JbossFeature.java @@ -2,7 +2,8 @@ public interface JbossFeature { - public static final String GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR = "generateJbossDeploymentDescriptor"; + public static final String GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR = + "generateJbossDeploymentDescriptor"; public void setGenerateJbossDeploymentDescriptor(boolean generateJbossDeploymentDescriptor); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/LoggingFeatures.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/LoggingFeatures.java index 0d370a44ced..e42a3b830f4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/LoggingFeatures.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/LoggingFeatures.java @@ -3,7 +3,7 @@ public interface LoggingFeatures extends BeanValidationFeatures { public static final String USE_LOGGING_FEATURE = "useLoggingFeature"; - + public void setUseLoggingFeature(boolean useLoggingFeature); - + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/PerformBeanValidationFeatures.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/PerformBeanValidationFeatures.java index 3f30fb075f3..607888945e8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/PerformBeanValidationFeatures.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/PerformBeanValidationFeatures.java @@ -4,7 +4,7 @@ public interface PerformBeanValidationFeatures { // Language supports performing BeanValidation public static final String PERFORM_BEANVALIDATION = "performBeanValidation"; - + public void setPerformBeanValidation(boolean performBeanValidation); - + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/SpringFeatures.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/SpringFeatures.java index 0a3fad4202a..6e9ec849caf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/SpringFeatures.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/SpringFeatures.java @@ -3,16 +3,16 @@ public interface SpringFeatures extends BeanValidationFeatures { public static final String GENERATE_SPRING_APPLICATION = "generateSpringApplication"; - + public static final String GENERATE_SPRING_BOOT_APPLICATION = "generateSpringBootApplication"; public static final String USE_SPRING_ANNOTATION_CONFIG = "useSpringAnnotationConfig"; public void setGenerateSpringApplication(boolean useGenerateSpringApplication); - + public void setGenerateSpringBootApplication(boolean generateSpringBootApplication); public void setUseSpringAnnotationConfig(boolean useSpringAnnotationConfig); - + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/utils/OptionUtils.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/utils/OptionUtils.java index 27322b4554f..3d0f1e9bf2f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/utils/OptionUtils.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/utils/OptionUtils.java @@ -19,22 +19,23 @@ public static List> parseCommaSeparatedTuples(String input) for (String tuple : tuples) { int ix = tuple.indexOf('='); if (ix > 0 && ix < tuple.length() - 1) { - final Pair pair = Pair.of(tuple.substring(0, ix), tuple.substring(ix + 1)); + final Pair pair = + Pair.of(tuple.substring(0, ix), tuple.substring(ix + 1)); results.add(pair); } } - //Strings.isNullOrEmpty(input) + // Strings.isNullOrEmpty(input) return results; } - + public static List splitCommaSeparatedList(String input) { List results = new ArrayList(); - if(input != null && !input.isEmpty()) { + if (input != null && !input.isEmpty()) { for (String value : input.split(",")) { - if(isNotEmpty(value)) - results.add(value); + if (isNotEmpty(value)) + results.add(value); } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractIntegrationTest.java index 8aaa127c6d8..685fc41615e 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractIntegrationTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractIntegrationTest.java @@ -34,13 +34,12 @@ public void generatesCorrectDirectoryStructure() throws IOException { ClientOpts clientOpts = new ClientOpts(); clientOpts.setProperties(configProperties()); - ClientOptInput opts = new ClientOptInput() - .config(codegenConfig) - .opts(clientOpts) - .swagger(swagger); + ClientOptInput opts = + new ClientOptInput().config(codegenConfig).opts(clientOpts).swagger(swagger); codeGen.opts(opts).generate(); - assertPathEqualsRecursively(integrationTestPathsConfig.getExpectedPath(), integrationTestPathsConfig.getOutputPath()); + assertPathEqualsRecursively(integrationTestPathsConfig.getExpectedPath(), + integrationTestPathsConfig.getOutputPath()); } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractOptionsTest.java index ede3feb50b4..09a9ef4296f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractOptionsTest.java @@ -30,23 +30,29 @@ public void checkOptionsProcessing() { getCodegenConfig().processOpts(); - new FullVerifications() {{ - }}; + new FullVerifications() { + { + } + }; } - @Test(description = "check if all options described in documentation are presented in test case") + @Test( + description = "check if all options described in documentation are presented in test case") public void checkOptionsHelp() { - final List cliOptions = Lists.transform(getCodegenConfig().cliOptions(), getCliOptionTransformer()); + final List cliOptions = + Lists.transform(getCodegenConfig().cliOptions(), getCliOptionTransformer()); final Set testOptions = optionsProvider.createOptions().keySet(); final Set skipped = new HashSet(cliOptions); skipped.removeAll(testOptions); if (!skipped.isEmpty()) { - Assert.fail(String.format("These options weren't checked: %s.", StringUtils.join(skipped, ", "))); + Assert.fail(String.format("These options weren't checked: %s.", + StringUtils.join(skipped, ", "))); } final Set undocumented = new HashSet(testOptions); undocumented.removeAll(cliOptions); if (!undocumented.isEmpty()) { - Assert.fail(String.format("These options weren't documented: %s.", StringUtils.join(undocumented, ", "))); + Assert.fail(String.format("These options weren't documented: %s.", + StringUtils.join(undocumented, ", "))); } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ClientAuthInputTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ClientAuthInputTest.java index 490affe0764..b26bd1933f3 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ClientAuthInputTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ClientAuthInputTest.java @@ -14,7 +14,8 @@ public class ClientAuthInputTest { public void clientAuthInputTest() { final ClientOptInput input = new ClientOptInput(); - final String header = "api_key:special-key,api_key:hello,X-AUTHORIZATION:0e6c11d79a,Authorization:Basic 1jz0"; + final String header = + "api_key:special-key,api_key:hello,X-AUTHORIZATION:0e6c11d79a,Authorization:Basic 1jz0"; input.setAuth(header); final List authValues = input.getAuthorizationValues(); Assert.assertEquals(authValues.size(), 4); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenConfigLoaderTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenConfigLoaderTest.java index cf4e4a201fb..2f9922d2330 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenConfigLoaderTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenConfigLoaderTest.java @@ -18,7 +18,8 @@ public class CodegenConfigLoaderTest { public Object[][] createCodegenConfigDataSet() throws Exception { Reflections reflections = new Reflections("io.swagger.codegen.languages"); - final Set> subTypesOf = reflections.getSubTypesOf(DefaultCodegen.class); + final Set> subTypesOf = + reflections.getSubTypesOf(DefaultCodegen.class); List codegenConfigList = new ArrayList(); @@ -32,7 +33,7 @@ public Object[][] createCodegenConfigDataSet() throws Exception { Object[][] result = new Object[codegenConfigList.size()][1]; for (int i = 0; i < codegenConfigList.size(); i++) { - result[i]= new Object[]{codegenConfigList.get(i)}; + result[i] = new Object[] {codegenConfigList.get(i)}; } return result; @@ -48,7 +49,8 @@ public void testLoadByName(CodegenConfig codegenConfig) throws Exception { @Test(dataProvider = "codegenConfig") public void testLoadByFullQualifiedName(CodegenConfig codegenConfig) throws Exception { - final CodegenConfig loadedConfig = CodegenConfigLoader.forName(codegenConfig.getClass().getName()); + final CodegenConfig loadedConfig = + CodegenConfigLoader.forName(codegenConfig.getClass().getName()); assertEquals(loadedConfig.getClass(), codegenConfig.getClass()); assertEquals(loadedConfig.getName(), codegenConfig.getName()); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java index b5079ead853..86ad38dc362 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java @@ -75,7 +75,8 @@ public void formParamTest() { Assert.assertEquals(op.httpMethod, "POST"); Assert.assertTrue(op.hasConsumes); Assert.assertEquals(op.consumes.size(), 1); - Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/x-www-form-urlencoded"); + Assert.assertEquals(op.consumes.get(0).get("mediaType"), + "application/x-www-form-urlencoded"); Assert.assertTrue(op.hasProduces); Assert.assertEquals(op.produces.size(), 2); Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/json"); @@ -138,11 +139,12 @@ public void enumQueryParameterTest() { Assert.assertEquals(statusParam.datatypeWithEnum, "List"); Assert.assertEquals(statusParam.baseType, "String"); Assert.assertTrue(statusParam.isEnum); - Assert.assertEquals(((List)statusParam.allowableValues.get("values")).size(), 3); + Assert.assertEquals(((List) statusParam.allowableValues.get("values")).size(), 3); } - @Test(description = "handle required parameters from a 2.0 spec as required when figuring out Swagger types") + @Test( + description = "handle required parameters from a 2.0 spec as required when figuring out Swagger types") public void requiredParametersTest() { final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/requiredTest.json"); @@ -168,7 +170,8 @@ public String getSwaggerType(Property p) { @Test(description = "select main response from a 2.0 spec using the lowest 2XX code") public void responseSelectionTest1() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/responseSelectionTest.json"); + final Swagger model = + parseAndPrepareSwagger("src/test/resources/2_0/responseSelectionTest.json"); final DefaultCodegen codegen = new DefaultCodegen(); final String path = "/tests/withTwoHundredAndDefault"; final Operation p = model.getPaths().get(path).getGet(); @@ -177,9 +180,11 @@ public void responseSelectionTest1() { Assert.assertEquals(op.returnType, "String"); } - @Test(description = "select main response from a 2.0 spec using the default keyword when no 2XX code") + @Test( + description = "select main response from a 2.0 spec using the default keyword when no 2XX code") public void responseSelectionTest2() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/responseSelectionTest.json"); + final Swagger model = + parseAndPrepareSwagger("src/test/resources/2_0/responseSelectionTest.json"); final DefaultCodegen codegen = new DefaultCodegen(); final String path = "/tests/withoutTwoHundredButDefault"; final Operation p = model.getPaths().get(path).getGet(); @@ -204,7 +209,8 @@ public void binaryDataTest() { @Test(description = "return file when response format is file") public void fileResponeseTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/fileResponseTest.json"); + final Swagger model = + parseAndPrepareSwagger("src/test/resources/2_0/fileResponseTest.json"); final DefaultCodegen codegen = new DefaultCodegen(); final String path = "/tests/fileResponse"; final Operation p = model.getPaths().get(path).getGet(); @@ -214,10 +220,11 @@ public void fileResponeseTest() { Assert.assertTrue(op.responses.get(0).isFile); Assert.assertTrue(op.isResponseFile); } - + @Test(description = "discriminator is present") public void discriminatorTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/discriminatorTest.json"); + final Swagger model = + parseAndPrepareSwagger("src/test/resources/2_0/discriminatorTest.json"); final DefaultCodegen codegen = new DefaultCodegen(); final String path = "/pets"; final Operation p = model.getPaths().get(path).getGet(); @@ -227,12 +234,13 @@ public void discriminatorTest() { } @Test(description = "handle simple composition") - public void simpleCompositionTest() { + public void simpleCompositionTest() { final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); final DefaultCodegen codegen = new DefaultCodegen(); codegen.supportsInheritance = true; final Model model = swagger.getDefinitions().get("SimpleComposition"); - CodegenModel composed = codegen.fromModel("SimpleComposition", model, swagger.getDefinitions()); + CodegenModel composed = + codegen.fromModel("SimpleComposition", model, swagger.getDefinitions()); Assert.assertEquals(composed.vars.size(), 3); Assert.assertEquals(composed.vars.get(0).baseName, "modelOneProp"); @@ -242,12 +250,13 @@ public void simpleCompositionTest() { } @Test(description = "handle multi level composition") - public void multiCompositionTest() { + public void multiCompositionTest() { final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); final DefaultCodegen codegen = new DefaultCodegen(); codegen.supportsInheritance = true; final Model model = swagger.getDefinitions().get("CompositionOfSimpleComposition"); - CodegenModel composed = codegen.fromModel("CompositionOfSimpleComposition", model, swagger.getDefinitions()); + CodegenModel composed = + codegen.fromModel("CompositionOfSimpleComposition", model, swagger.getDefinitions()); Assert.assertEquals(composed.vars.size(), 5); Assert.assertEquals(composed.vars.get(0).baseName, "modelOneProp"); @@ -259,12 +268,13 @@ public void multiCompositionTest() { } @Test(description = "handle simple inheritance") - public void simpleInheritanceTest() { + public void simpleInheritanceTest() { final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); final DefaultCodegen codegen = new DefaultCodegen(); codegen.supportsInheritance = true; final Model model = swagger.getDefinitions().get("ChildOfSimpleParent"); - CodegenModel child = codegen.fromModel("ChildOfSimpleParent", model, swagger.getDefinitions()); + CodegenModel child = + codegen.fromModel("ChildOfSimpleParent", model, swagger.getDefinitions()); Assert.assertEquals(child.vars.size(), 2); Assert.assertEquals(child.vars.get(0).baseName, "modelOneProp"); @@ -273,24 +283,27 @@ public void simpleInheritanceTest() { } @Test(description = "handle multi level inheritance") - public void multiInheritanceTest() { + public void multiInheritanceTest() { final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); final DefaultCodegen codegen = new DefaultCodegen(); codegen.supportsInheritance = true; final Model model = swagger.getDefinitions().get("ChildOfChildOfSimpleParent"); - CodegenModel child = codegen.fromModel("ChildOfChildOfSimpleParent", model, swagger.getDefinitions()); + CodegenModel child = + codegen.fromModel("ChildOfChildOfSimpleParent", model, swagger.getDefinitions()); Assert.assertEquals(child.vars.size(), 1); Assert.assertEquals(child.vars.get(0).baseName, "childOfChildOfSimpleParentProp"); Assert.assertEquals(child.parent, "ChildOfSimpleParent"); } - @Test(description = "copy properties in multi level inheritance if supportsInheritance is false") - public void noSupportsInheritanceTest() { + @Test( + description = "copy properties in multi level inheritance if supportsInheritance is false") + public void noSupportsInheritanceTest() { final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); final DefaultCodegen codegen = new DefaultCodegen(); final Model model = swagger.getDefinitions().get("ChildOfChildOfSimpleParent"); - CodegenModel child = codegen.fromModel("ChildOfChildOfSimpleParent", model, swagger.getDefinitions()); + CodegenModel child = + codegen.fromModel("ChildOfChildOfSimpleParent", model, swagger.getDefinitions()); Assert.assertEquals(child.vars.size(), 5); Assert.assertEquals(child.vars.get(0).baseName, "modelOneProp"); @@ -302,13 +315,14 @@ public void noSupportsInheritanceTest() { } @Test(description = "don't copy interfaces properties if supportsMixins is true") - public void supportsMixinsTest() { + public void supportsMixinsTest() { final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); final DefaultCodegen codegen = new DefaultCodegen(); codegen.supportsInheritance = true; codegen.supportsMixins = true; final Model model = swagger.getDefinitions().get("ChildOfChildOfSimpleParent"); - CodegenModel child = codegen.fromModel("ChildOfChildOfSimpleParent", model, swagger.getDefinitions()); + CodegenModel child = + codegen.fromModel("ChildOfChildOfSimpleParent", model, swagger.getDefinitions()); Assert.assertEquals(child.vars.size(), 1); Assert.assertEquals(child.vars.get(0).baseName, "childOfChildOfSimpleParentProp"); @@ -323,12 +337,13 @@ public void supportsMixinsTest() { } @Test(description = "handle inheritance from composed model") - public void inheritanceOfComposedModelTest() { + public void inheritanceOfComposedModelTest() { final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); final DefaultCodegen codegen = new DefaultCodegen(); codegen.supportsInheritance = true; final Model model = swagger.getDefinitions().get("ChildOfComposedParent"); - CodegenModel child = codegen.fromModel("ChildOfComposedParent", model, swagger.getDefinitions()); + CodegenModel child = + codegen.fromModel("ChildOfComposedParent", model, swagger.getDefinitions()); Assert.assertEquals(child.vars.size(), 1); Assert.assertEquals(child.vars.get(0).baseName, "childOfComposedParentProp"); @@ -336,12 +351,13 @@ public void inheritanceOfComposedModelTest() { } @Test(description = "handle multi level inheritance from composed model") - public void multiInheritanceOfComposedModelTest() { + public void multiInheritanceOfComposedModelTest() { final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); final DefaultCodegen codegen = new DefaultCodegen(); codegen.supportsInheritance = true; final Model model = swagger.getDefinitions().get("ChildOfChildOfComposedParent"); - CodegenModel child = codegen.fromModel("ChildOfChildOfComposedParent", model, swagger.getDefinitions()); + CodegenModel child = + codegen.fromModel("ChildOfChildOfComposedParent", model, swagger.getDefinitions()); Assert.assertEquals(child.vars.size(), 1); Assert.assertEquals(child.vars.get(0).baseName, "childOfChildOfComposedParentProp"); @@ -351,12 +367,13 @@ public void multiInheritanceOfComposedModelTest() { @Test(description = "use operation consumes and produces") public void localConsumesAndProducesTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/globalConsumesAndProduces.json"); + final Swagger model = + parseAndPrepareSwagger("src/test/resources/2_0/globalConsumesAndProduces.json"); final DefaultCodegen codegen = new DefaultCodegen(); final String path = "/tests/localConsumesAndProduces"; final Operation p = model.getPaths().get(path).getGet(); CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); - + Assert.assertTrue(op.hasConsumes); Assert.assertEquals(op.consumes.size(), 1); Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/json"); @@ -364,15 +381,16 @@ public void localConsumesAndProducesTest() { Assert.assertEquals(op.produces.size(), 1); Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/json"); } - + @Test(description = "use spec consumes and produces") public void globalConsumesAndProducesTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/globalConsumesAndProduces.json"); + final Swagger model = + parseAndPrepareSwagger("src/test/resources/2_0/globalConsumesAndProduces.json"); final DefaultCodegen codegen = new DefaultCodegen(); final String path = "/tests/globalConsumesAndProduces"; final Operation p = model.getPaths().get(path).getGet(); CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); - + Assert.assertTrue(op.hasConsumes); Assert.assertEquals(op.consumes.size(), 1); Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/global_consumes"); @@ -380,15 +398,16 @@ public void globalConsumesAndProducesTest() { Assert.assertEquals(op.produces.size(), 1); Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/global_produces"); } - + @Test(description = "use operation consumes and produces (reset in operation with empty array)") public void localResetConsumesAndProducesTest() { - final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/globalConsumesAndProduces.json"); + final Swagger model = + parseAndPrepareSwagger("src/test/resources/2_0/globalConsumesAndProduces.json"); final DefaultCodegen codegen = new DefaultCodegen(); final String path = "/tests/localResetConsumesAndProduces"; final Operation p = model.getPaths().get(path).getGet(); CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); - + Assert.assertNotNull(op); Assert.assertFalse(op.hasConsumes); Assert.assertNull(op.consumes); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java index f05c0e32700..98874549559 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java @@ -27,7 +27,8 @@ public class DefaultGeneratorTest { private static final String TEST_SKIP_OVERWRITE = "testSkipOverwrite"; private static final String POM_FILE = "pom.xml"; - private static final String MODEL_ORDER_FILE = "/src/main/java/io/swagger/client/model/Order.java"; + private static final String MODEL_ORDER_FILE = + "/src/main/java/io/swagger/client/model/Order.java"; public TemporaryFolder folder = new TemporaryFolder(); @@ -46,7 +47,8 @@ public void testSecurityWithoutGlobal() throws Exception { final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/petstore.json"); CodegenConfig codegenConfig = new JavaClientCodegen(); - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); + ClientOptInput clientOptInput = + new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); DefaultGenerator gen = new DefaultGenerator(); gen.opts(clientOptInput); @@ -73,7 +75,8 @@ public void testSecurityWithoutGlobal() throws Exception { assertEquals(apiKey.type, "apiKey"); // security of "updatePetWithForm": petstore_auth - CodegenOperation updatePetWithForm = findCodegenOperationByOperationId(paths, "updatePetWithForm"); + CodegenOperation updatePetWithForm = + findCodegenOperationByOperationId(paths, "updatePetWithForm"); assertEquals(updatePetWithForm.authMethods.size(), 1); petstoreAuth = updatePetWithForm.authMethods.iterator().next(); assertEquals(petstoreAuth.name, "petstore_auth"); @@ -86,10 +89,12 @@ public void testSecurityWithoutGlobal() throws Exception { @Test public void testSecurityWithGlobal() throws Exception { - final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/globalSecurity.json"); + final Swagger swagger = + new SwaggerParser().read("src/test/resources/2_0/globalSecurity.json"); CodegenConfig codegenConfig = new JavaClientCodegen(); - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); + ClientOptInput clientOptInput = + new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); DefaultGenerator gen = new DefaultGenerator(); gen.opts(clientOptInput); @@ -114,7 +119,8 @@ public void testSecurityWithGlobal() throws Exception { assertEquals(apiKey.type, "apiKey"); // security of "updatePetWithForm": petstore_auth - CodegenOperation updatePetWithForm = findCodegenOperationByOperationId(paths, "updatePetWithForm"); + CodegenOperation updatePetWithForm = + findCodegenOperationByOperationId(paths, "updatePetWithForm"); assertEquals(updatePetWithForm.authMethods.size(), 1); petstoreAuth = updatePetWithForm.authMethods.iterator().next(); assertEquals(petstoreAuth.name, "petstore_auth"); @@ -166,56 +172,63 @@ public void testSkipOverwrite() throws Exception { codegenConfig.setLibrary("jersey1"); codegenConfig.setOutputDir(output.getAbsolutePath()); - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); + ClientOptInput clientOptInput = + new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); - //generate content first time without skipOverwrite flag, so all generated files should be recorded + // generate content first time without skipOverwrite flag, so all generated files should be + // recorded new DefaultGenerator().opts(clientOptInput).generate(); final File order = new File(output, MODEL_ORDER_FILE); assertTrue(order.exists()); - //change content of one file + // change content of one file changeContent(order); - //generate content second time without skipOverwrite flag, so changed file should be rewritten + // generate content second time without skipOverwrite flag, so changed file should be + // rewritten new DefaultGenerator().opts(clientOptInput).generate(); - assertTrue(!TEST_SKIP_OVERWRITE.equals(FileUtils.readFileToString(order, StandardCharsets.UTF_8))); + assertTrue(!TEST_SKIP_OVERWRITE.equals(FileUtils.readFileToString(order, + StandardCharsets.UTF_8))); - //change content again + // change content again changeContent(order); - //delete file + // delete file final File pom = new File(output, POM_FILE); if (pom.exists() && !pom.delete()) { fail("it doesn't delete"); } - //generate content third time with skipOverwrite flag, so changed file should not be rewritten - //and deleted file should be recorded + // generate content third time with skipOverwrite flag, so changed file should not be + // rewritten + // and deleted file should be recorded codegenConfig.setSkipOverwrite(true); new DefaultGenerator().opts(clientOptInput).generate(); assertEquals(FileUtils.readFileToString(order, StandardCharsets.UTF_8), TEST_SKIP_OVERWRITE); // Disabling this check, it's not valid with the DefaultCodegen.writeOptional(...) arg -// assertTrue(pom.exists()); + // assertTrue(pom.exists()); } @Test public void testGenerateUniqueOperationIds() { final File output = folder.getRoot(); - final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/duplicateOperationIds.yaml"); + final Swagger swagger = + new SwaggerParser().read("src/test/resources/2_0/duplicateOperationIds.yaml"); CodegenConfig codegenConfig = new JavaClientCodegen(); codegenConfig.setOutputDir(output.getAbsolutePath()); - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); + ClientOptInput clientOptInput = + new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); DefaultGenerator generator = new DefaultGenerator(); generator.opts(clientOptInput); Map> paths = generator.processPaths(swagger.getPaths()); Set opIds = new HashSet(); - for(String path : paths.keySet()) { + for (String path : paths.keySet()) { List ops = paths.get(path); - for(CodegenOperation op : ops) { + for (CodegenOperation op : ops) { assertFalse(opIds.contains(op.operationId)); opIds.add(op.operationId); } @@ -228,7 +241,8 @@ private static void changeContent(File file) throws IOException { out.close(); } - private static CodegenOperation findCodegenOperationByOperationId(Map> paths, String operationId) { + private static CodegenOperation findCodegenOperationByOperationId( + Map> paths, String operationId) { for (List ops : paths.values()) { for (CodegenOperation co : ops) { if (operationId.equals(co.operationId)) { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java index ab50384e883..2e50fc36b75 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java @@ -27,13 +27,18 @@ public void recursiveModelsTest() { final String XML = "application/xml"; final String nodeType = "Node"; final RefProperty ref = new RefProperty(nodeType); - final Model node = new ModelImpl().name(nodeType).property("name", new StringProperty()) - .property("parent", ref) - .property("children", new ArrayProperty(ref)) - .property("wrappedChildren", new ArrayProperty(ref).xml(new Xml().wrapped(true))); + final Model node = + new ModelImpl() + .name(nodeType) + .property("name", new StringProperty()) + .property("parent", ref) + .property("children", new ArrayProperty(ref)) + .property("wrappedChildren", + new ArrayProperty(ref).xml(new Xml().wrapped(true))); final String pairType = "Pair"; final ModelImpl pair = new ModelImpl().name(pairType); - for (Map.Entry item : ImmutableMap.of("first", "First", "second", "Second").entrySet()) { + for (Map.Entry item : ImmutableMap.of("first", "First", "second", "Second") + .entrySet()) { final RefProperty property = new RefProperty(nodeType); property.setXml(new Xml().name(item.getValue())); pair.property(item.getKey(), property); @@ -42,24 +47,17 @@ public void recursiveModelsTest() { final Set types = Sets.newHashSet(); final List expectedTypes = Arrays.asList(JSON, XML); - final ExampleGenerator eg = new ExampleGenerator(ImmutableMap.of(nodeType, node, pairType, pair)); + final ExampleGenerator eg = + new ExampleGenerator(ImmutableMap.of(nodeType, node, pairType, pair)); for (Map item : eg.generate(null, expectedTypes, new RefProperty(pairType))) { final String example = item.get("example"); final String contentType = item.get("contentType"); if (XML.equals(contentType)) { types.add(XML); - Assert.assertEquals(example, "\n" + - " \n" + - " aeiou\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " aeiou\n" + - " \n" + - " \n" + - " \n" + - ""); + Assert.assertEquals(example, "\n" + " \n" + " aeiou\n" + + " \n" + " \n" + " \n" + + " \n" + " aeiou\n" + " \n" + + " \n" + " \n" + ""); } else if (JSON.equals(contentType)) { types.add(JSON); // TODO - add JSON validation diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java index 6b9c3a3c5b1..81ed267a3a3 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java @@ -18,28 +18,27 @@ public class InlineModelResolverTest { public void resolveInlineModelTestWithoutTitle() throws Exception { Swagger swagger = new Swagger(); - swagger.addDefinition("User", new ModelImpl() - .name("user") - .description("a common user") - .property("name", new StringProperty()) - .property("address", new ObjectProperty() - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") - .property("street", new StringProperty()) - .property("city", new StringProperty()))); + swagger.addDefinition( + "User", + new ModelImpl() + .name("user") + .description("a common user") + .property("name", new StringProperty()) + .property( + "address", + new ObjectProperty()._default("default").access("access") + .readOnly(false).required(true).description("description") + .name("name").property("street", new StringProperty()) + .property("city", new StringProperty()))); new InlineModelResolver().flatten(swagger); - ModelImpl user = (ModelImpl)swagger.getDefinitions().get("User"); + ModelImpl user = (ModelImpl) swagger.getDefinitions().get("User"); assertNotNull(user); assertTrue(user.getProperties().get("address") instanceof RefProperty); - ModelImpl address = (ModelImpl)swagger.getDefinitions().get("User_address"); + ModelImpl address = (ModelImpl) swagger.getDefinitions().get("User_address"); assertNotNull(address); assertNotNull(address.getProperties().get("city")); assertNotNull(address.getProperties().get("street")); @@ -49,220 +48,218 @@ public void resolveInlineModelTestWithoutTitle() throws Exception { public void resolveInlineModelTestWithTitle() throws Exception { Swagger swagger = new Swagger(); - swagger.addDefinition("User", new ModelImpl() - .name("user") - .description("a common user") - .property("name", new StringProperty()) - .property("address", new ObjectProperty() - .title("UserAddressTitle") - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") - .property("street", new StringProperty()) - .property("city", new StringProperty()))); + swagger.addDefinition( + "User", + new ModelImpl() + .name("user") + .description("a common user") + .property("name", new StringProperty()) + .property( + "address", + new ObjectProperty().title("UserAddressTitle")._default("default") + .access("access").readOnly(false).required(true) + .description("description").name("name") + .property("street", new StringProperty()) + .property("city", new StringProperty()))); new InlineModelResolver().flatten(swagger); - ModelImpl user = (ModelImpl)swagger.getDefinitions().get("User"); + ModelImpl user = (ModelImpl) swagger.getDefinitions().get("User"); assertNotNull(user); assertTrue(user.getProperties().get("address") instanceof RefProperty); - ModelImpl address = (ModelImpl)swagger.getDefinitions().get("UserAddressTitle"); + ModelImpl address = (ModelImpl) swagger.getDefinitions().get("UserAddressTitle"); assertNotNull(address); assertNotNull(address.getProperties().get("city")); assertNotNull(address.getProperties().get("street")); - } - + } + @Test public void resolveInlineModel2EqualInnerModels() throws Exception { Swagger swagger = new Swagger(); - swagger.addDefinition("User", new ModelImpl() - .name("user") - .description("a common user") - .property("name", new StringProperty()) - .property("address", new ObjectProperty() - .title("UserAddressTitle") - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") - .property("street", new StringProperty()) - .property("city", new StringProperty()))); - - swagger.addDefinition("AnotherUser", new ModelImpl() - .name("user") - .description("a common user") - .property("name", new StringProperty()) - .property("lastName", new StringProperty()) - .property("address", new ObjectProperty() - .title("UserAddressTitle") - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") - .property("street", new StringProperty()) - .property("city", new StringProperty()))); + swagger.addDefinition( + "User", + new ModelImpl() + .name("user") + .description("a common user") + .property("name", new StringProperty()) + .property( + "address", + new ObjectProperty().title("UserAddressTitle")._default("default") + .access("access").readOnly(false).required(true) + .description("description").name("name") + .property("street", new StringProperty()) + .property("city", new StringProperty()))); + + swagger.addDefinition( + "AnotherUser", + new ModelImpl() + .name("user") + .description("a common user") + .property("name", new StringProperty()) + .property("lastName", new StringProperty()) + .property( + "address", + new ObjectProperty().title("UserAddressTitle")._default("default") + .access("access").readOnly(false).required(true) + .description("description").name("name") + .property("street", new StringProperty()) + .property("city", new StringProperty()))); new InlineModelResolver().flatten(swagger); - ModelImpl user = (ModelImpl)swagger.getDefinitions().get("User"); + ModelImpl user = (ModelImpl) swagger.getDefinitions().get("User"); assertNotNull(user); assertTrue(user.getProperties().get("address") instanceof RefProperty); - ModelImpl address = (ModelImpl)swagger.getDefinitions().get("UserAddressTitle"); + ModelImpl address = (ModelImpl) swagger.getDefinitions().get("UserAddressTitle"); assertNotNull(address); assertNotNull(address.getProperties().get("city")); assertNotNull(address.getProperties().get("street")); - ModelImpl duplicateAddress = (ModelImpl)swagger.getDefinitions().get("UserAddressTitle_0"); + ModelImpl duplicateAddress = (ModelImpl) swagger.getDefinitions().get("UserAddressTitle_0"); assertNull(duplicateAddress); - } + } @Test public void resolveInlineModel2DifferentInnerModelsWIthSameTitle() throws Exception { Swagger swagger = new Swagger(); - swagger.addDefinition("User", new ModelImpl() - .name("user") - .description("a common user") - .property("name", new StringProperty()) - .property("address", new ObjectProperty() - .title("UserAddressTitle") - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") - .property("street", new StringProperty()) - .property("city", new StringProperty()))); - - swagger.addDefinition("AnotherUser", new ModelImpl() - .name("AnotherUser") - .description("a common user") - .property("name", new StringProperty()) - .property("lastName", new StringProperty()) - .property("address", new ObjectProperty() - .title("UserAddressTitle") - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") - .property("street", new StringProperty()) - .property("city", new StringProperty()) - .property("apartment", new StringProperty()))); + swagger.addDefinition( + "User", + new ModelImpl() + .name("user") + .description("a common user") + .property("name", new StringProperty()) + .property( + "address", + new ObjectProperty().title("UserAddressTitle")._default("default") + .access("access").readOnly(false).required(true) + .description("description").name("name") + .property("street", new StringProperty()) + .property("city", new StringProperty()))); + + swagger.addDefinition( + "AnotherUser", + new ModelImpl() + .name("AnotherUser") + .description("a common user") + .property("name", new StringProperty()) + .property("lastName", new StringProperty()) + .property( + "address", + new ObjectProperty().title("UserAddressTitle")._default("default") + .access("access").readOnly(false).required(true) + .description("description").name("name") + .property("street", new StringProperty()) + .property("city", new StringProperty()) + .property("apartment", new StringProperty()))); new InlineModelResolver().flatten(swagger); - ModelImpl user = (ModelImpl)swagger.getDefinitions().get("User"); + ModelImpl user = (ModelImpl) swagger.getDefinitions().get("User"); assertNotNull(user); assertTrue(user.getProperties().get("address") instanceof RefProperty); - ModelImpl address = (ModelImpl)swagger.getDefinitions().get("UserAddressTitle"); + ModelImpl address = (ModelImpl) swagger.getDefinitions().get("UserAddressTitle"); assertNotNull(address); assertNotNull(address.getProperties().get("city")); assertNotNull(address.getProperties().get("street")); - ModelImpl duplicateAddress = (ModelImpl)swagger.getDefinitions().get("UserAddressTitle_1"); + ModelImpl duplicateAddress = (ModelImpl) swagger.getDefinitions().get("UserAddressTitle_1"); assertNotNull(duplicateAddress); assertNotNull(duplicateAddress.getProperties().get("city")); assertNotNull(duplicateAddress.getProperties().get("street")); assertNotNull(duplicateAddress.getProperties().get("apartment")); - } - - + } + + @Test public void testInlineResponseModel() throws Exception { Swagger swagger = new Swagger(); - swagger.path("/foo/bar", new Path() - .get(new Operation() - .response(200, new Response() - .description("it works!") - .schema(new ObjectProperty() - .property("name", new StringProperty()).vendorExtension("x-ext", "ext-prop"))))) - .path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() + swagger.path( + "/foo/bar", + new Path().get(new Operation().response( + 200, + new Response().description("it works!").schema( + new ObjectProperty().property("name", new StringProperty()) + .vendorExtension("x-ext", "ext-prop"))))).path( + "/foo/baz", + new Path().get(new Operation().response( + 200, + new Response() .vendorExtension("x-foo", "bar") .description("it works!") - .schema(new ObjectProperty() - .property("name", new StringProperty()).vendorExtension("x-ext", "ext-prop"))))); + .schema(new ObjectProperty().property("name", new StringProperty()) + .vendorExtension("x-ext", "ext-prop"))))); new InlineModelResolver().flatten(swagger); - Map responses = swagger.getPaths().get("/foo/bar").getGet().getResponses(); + Map responses = + swagger.getPaths().get("/foo/bar").getGet().getResponses(); Response response = responses.get("200"); assertNotNull(response); Property schema = response.getSchema(); - assertTrue(schema instanceof RefProperty); + assertTrue(schema instanceof RefProperty); assertEquals(1, schema.getVendorExtensions().size()); assertEquals("ext-prop", schema.getVendorExtensions().get("x-ext")); - ModelImpl model = (ModelImpl)swagger.getDefinitions().get("inline_response_200"); + ModelImpl model = (ModelImpl) swagger.getDefinitions().get("inline_response_200"); assertTrue(model.getProperties().size() == 1); assertNotNull(model.getProperties().get("name")); assertTrue(model.getProperties().get("name") instanceof StringProperty); } - + @Test public void testInlineResponseModelWithTitle() throws Exception { Swagger swagger = new Swagger(); String responseTitle = "GetBarResponse"; - swagger.path("/foo/bar", new Path() - .get(new Operation() - .response(200, new Response() - .description("it works!") - .schema(new ObjectProperty().title(responseTitle) - .property("name", new StringProperty()))))) - .path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .vendorExtension("x-foo", "bar") - .description("it works!") - .schema(new ObjectProperty() - .property("name", new StringProperty()))))); + swagger.path( + "/foo/bar", + new Path().get(new Operation().response( + 200, + new Response().description("it works!").schema( + new ObjectProperty().title(responseTitle).property("name", + new StringProperty()))))).path( + "/foo/baz", + new Path().get(new Operation() + .response( + 200, + new Response() + .vendorExtension("x-foo", "bar") + .description("it works!") + .schema(new ObjectProperty().property("name", + new StringProperty()))))); new InlineModelResolver().flatten(swagger); - Map responses = swagger.getPaths().get("/foo/bar").getGet().getResponses(); + Map responses = + swagger.getPaths().get("/foo/bar").getGet().getResponses(); Response response = responses.get("200"); assertNotNull(response); assertTrue(response.getSchema() instanceof RefProperty); - ModelImpl model = (ModelImpl)swagger.getDefinitions().get(responseTitle); + ModelImpl model = (ModelImpl) swagger.getDefinitions().get(responseTitle); assertTrue(model.getProperties().size() == 1); assertNotNull(model.getProperties().get("name")); assertTrue(model.getProperties().get("name") instanceof StringProperty); } - - + + @Test public void resolveInlineArrayModelWithTitle() throws Exception { Swagger swagger = new Swagger(); - swagger.addDefinition("User", new ArrayModel() - .items(new ObjectProperty() - .title("InnerUserTitle") - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") + swagger.addDefinition( + "User", + new ArrayModel().items(new ObjectProperty().title("InnerUserTitle") + ._default("default").access("access").readOnly(false).required(true) + .description("description").name("name") .property("street", new StringProperty()) .property("city", new StringProperty()))); @@ -275,19 +272,15 @@ public void resolveInlineArrayModelWithTitle() throws Exception { assertNotNull(user); assertEquals("description", user.getDescription()); } - + @Test public void resolveInlineArrayModelWithoutTitle() throws Exception { Swagger swagger = new Swagger(); - swagger.addDefinition("User", new ArrayModel() - .items(new ObjectProperty() - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") + swagger.addDefinition( + "User", + new ArrayModel().items(new ObjectProperty()._default("default").access("access") + .readOnly(false).required(true).description("description").name("name") .property("street", new StringProperty()) .property("city", new StringProperty()))); @@ -299,28 +292,24 @@ public void resolveInlineArrayModelWithoutTitle() throws Exception { Model user = swagger.getDefinitions().get("User_inner"); assertNotNull(user); assertEquals("description", user.getDescription()); - } - - - + } + + @Test public void resolveInlineBodyParameter() throws Exception { Swagger swagger = new Swagger(); - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(new ModelImpl() - .property("address", new ObjectProperty() - .property("street", new StringProperty())) - .property("name", new StringProperty()))))); + swagger.path("/hello", new Path().get(new Operation().parameter(new BodyParameter().name( + "body").schema( + new ModelImpl().property("address", + new ObjectProperty().property("street", new StringProperty())).property( + "name", new StringProperty()))))); new InlineModelResolver().flatten(swagger); Operation operation = swagger.getPaths().get("/hello").getGet(); - BodyParameter bp = (BodyParameter)operation.getParameters().get(0); + BodyParameter bp = (BodyParameter) operation.getParameters().get(0); assertTrue(bp.getSchema() instanceof RefModel); Model body = swagger.getDefinitions().get("body"); @@ -329,27 +318,24 @@ public void resolveInlineBodyParameter() throws Exception { ModelImpl impl = (ModelImpl) body; assertNotNull(impl.getProperties().get("address")); } - + @Test public void resolveInlineBodyParameterWithTitle() throws Exception { Swagger swagger = new Swagger(); ModelImpl addressModelItem = new ModelImpl(); String addressModelName = "DetailedAddress"; - addressModelItem.setTitle(addressModelName); - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(addressModelItem - .property("address", new ObjectProperty() - .property("street", new StringProperty())) - .property("name", new StringProperty()))))); + addressModelItem.setTitle(addressModelName); + swagger.path("/hello", new Path().get(new Operation().parameter(new BodyParameter().name( + "body").schema( + addressModelItem.property("address", + new ObjectProperty().property("street", new StringProperty())).property( + "name", new StringProperty()))))); new InlineModelResolver().flatten(swagger); Operation operation = swagger.getPaths().get("/hello").getGet(); - BodyParameter bp = (BodyParameter)operation.getParameters().get(0); + BodyParameter bp = (BodyParameter) operation.getParameters().get(0); assertTrue(bp.getSchema() instanceof RefModel); Model body = swagger.getDefinitions().get(addressModelName); @@ -357,24 +343,21 @@ public void resolveInlineBodyParameterWithTitle() throws Exception { ModelImpl impl = (ModelImpl) body; assertNotNull(impl.getProperties().get("address")); - } + } @Test public void notResolveNonModelBodyParameter() throws Exception { Swagger swagger = new Swagger(); - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(new ModelImpl() - .type("string") - .format("binary"))))); + swagger.path( + "/hello", + new Path().get(new Operation().parameter(new BodyParameter().name("body").schema( + new ModelImpl().type("string").format("binary"))))); new InlineModelResolver().flatten(swagger); Operation operation = swagger.getPaths().get("/hello").getGet(); - BodyParameter bp = (BodyParameter)operation.getParameters().get(0); + BodyParameter bp = (BodyParameter) operation.getParameters().get(0); assertTrue(bp.getSchema() instanceof ModelImpl); ModelImpl m = (ModelImpl) bp.getSchema(); assertEquals("string", m.getType()); @@ -385,14 +368,10 @@ public void notResolveNonModelBodyParameter() throws Exception { public void resolveInlineArrayBodyParameter() throws Exception { Swagger swagger = new Swagger(); - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(new ArrayModel() - .items(new ObjectProperty() - .property("address", new ObjectProperty() - .property("street", new StringProperty()))))))); + swagger.path("/hello", new Path().get(new Operation().parameter(new BodyParameter().name( + "body").schema( + new ArrayModel().items(new ObjectProperty().property("address", + new ObjectProperty().property("street", new StringProperty()))))))); new InlineModelResolver().flatten(swagger); @@ -436,16 +415,15 @@ public void resolveInlineArrayBodyParameter() throws Exception { public void resolveInlineArrayResponse() throws Exception { Swagger swagger = new Swagger(); - ArrayProperty schema = new ArrayProperty() - .items(new ObjectProperty() - .property("name", new StringProperty()) - .vendorExtension("x-ext", "ext-items")) - .vendorExtension("x-ext", "ext-prop"); - swagger.path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .vendorExtension("x-foo", "bar") - .description("it works!") + ArrayProperty schema = + new ArrayProperty().items( + new ObjectProperty().property("name", new StringProperty()) + .vendorExtension("x-ext", "ext-items")).vendorExtension("x-ext", + "ext-prop"); + swagger.path( + "/foo/baz", + new Path().get(new Operation().response(200, + new Response().vendorExtension("x-foo", "bar").description("it works!") .schema(schema)))); new InlineModelResolver().flatten(swagger); @@ -462,7 +440,7 @@ public void resolveInlineArrayResponse() throws Exception { ArrayProperty ap = (ArrayProperty) responseProperty; assertEquals(1, ap.getVendorExtensions().size()); assertEquals("ext-prop", ap.getVendorExtensions().get("x-ext")); - + Property p = ap.getItems(); assertNotNull(p); @@ -486,16 +464,15 @@ public void resolveInlineArrayResponse() throws Exception { public void resolveInlineArrayResponseWithTitle() throws Exception { Swagger swagger = new Swagger(); - swagger.path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() + swagger.path( + "/foo/baz", + new Path().get(new Operation().response( + 200, + new Response() .vendorExtension("x-foo", "bar") .description("it works!") - .schema(new ArrayProperty() - .items( - new ObjectProperty() - .title("FooBar") - .property("name", new StringProperty())))))); + .schema(new ArrayProperty().items(new ObjectProperty().title( + "FooBar").property("name", new StringProperty())))))); new InlineModelResolver().flatten(swagger); @@ -515,7 +492,7 @@ public void resolveInlineArrayResponseWithTitle() throws Exception { RefProperty rp = (RefProperty) p; assertEquals(rp.getType(), "ref"); - assertEquals(rp.get$ref(), "#/definitions/"+ "FooBar"); + assertEquals(rp.get$ref(), "#/definitions/" + "FooBar"); assertEquals(rp.getSimpleRef(), "FooBar"); Model inline = swagger.getDefinitions().get("FooBar"); @@ -525,7 +502,7 @@ public void resolveInlineArrayResponseWithTitle() throws Exception { assertNotNull(impl.getProperties().get("name")); assertTrue(impl.getProperties().get("name") instanceof StringProperty); } - + @Test public void testInlineMapResponse() throws Exception { Swagger swagger = new Swagger(); @@ -534,11 +511,10 @@ public void testInlineMapResponse() throws Exception { schema.setAdditionalProperties(new StringProperty()); schema.setVendorExtension("x-ext", "ext-prop"); - swagger.path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .vendorExtension("x-foo", "bar") - .description("it works!") + swagger.path( + "/foo/baz", + new Path().get(new Operation().response(200, + new Response().vendorExtension("x-foo", "bar").description("it works!") .schema(schema)))); new InlineModelResolver().flatten(swagger); Json.prettyPrint(swagger); @@ -557,15 +533,13 @@ public void testInlineMapResponseWithObjectProperty() throws Exception { Swagger swagger = new Swagger(); MapProperty schema = new MapProperty(); - schema.setAdditionalProperties(new ObjectProperty() - .property("name", new StringProperty())); + schema.setAdditionalProperties(new ObjectProperty().property("name", new StringProperty())); schema.setVendorExtension("x-ext", "ext-prop"); - swagger.path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .vendorExtension("x-foo", "bar") - .description("it works!") + swagger.path( + "/foo/baz", + new Path().get(new Operation().response(200, + new Response().vendorExtension("x-foo", "bar").description("it works!") .schema(schema)))); new InlineModelResolver().flatten(swagger); @@ -588,14 +562,12 @@ public void testArrayResponse() { Swagger swagger = new Swagger(); ArrayProperty schema = new ArrayProperty(); - schema.setItems(new ObjectProperty() - .property("name", new StringProperty())); + schema.setItems(new ObjectProperty().property("name", new StringProperty())); - swagger.path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .vendorExtension("x-foo", "bar") - .description("it works!") + swagger.path( + "/foo/baz", + new Path().get(new Operation().response(200, + new Response().vendorExtension("x-foo", "bar").description("it works!") .schema(schema)))); new InlineModelResolver().flatten(swagger); @@ -621,14 +593,10 @@ public void testArrayResponse() { public void testBasicInput() { Swagger swagger = new Swagger(); - ModelImpl user = new ModelImpl() - .property("name", new StringProperty()); + ModelImpl user = new ModelImpl().property("name", new StringProperty()); - swagger.path("/foo/baz", new Path() - .post(new Operation() - .parameter(new BodyParameter() - .name("myBody") - .schema(new RefModel("User"))))); + swagger.path("/foo/baz", new Path().post(new Operation().parameter(new BodyParameter() + .name("myBody").schema(new RefModel("User"))))); swagger.addDefinition("User", user); @@ -641,16 +609,15 @@ public void testBasicInput() { public void testArbitraryObjectBodyParam() { Swagger swagger = new Swagger(); - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(new ModelImpl())))); + swagger.path( + "/hello", + new Path().get(new Operation().parameter(new BodyParameter().name("body").schema( + new ModelImpl())))); new InlineModelResolver().flatten(swagger); Operation operation = swagger.getPaths().get("/hello").getGet(); - BodyParameter bp = (BodyParameter)operation.getParameters().get(0); + BodyParameter bp = (BodyParameter) operation.getParameters().get(0); assertTrue(bp.getSchema() instanceof ModelImpl); ModelImpl m = (ModelImpl) bp.getSchema(); assertNull(m.getType()); @@ -660,17 +627,15 @@ public void testArbitraryObjectBodyParam() { public void testArbitraryObjectBodyParamInline() { Swagger swagger = new Swagger(); - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(new ModelImpl() - .property("arbitrary", new ObjectProperty()))))); + swagger.path( + "/hello", + new Path().get(new Operation().parameter(new BodyParameter().name("body").schema( + new ModelImpl().property("arbitrary", new ObjectProperty()))))); new InlineModelResolver().flatten(swagger); Operation operation = swagger.getPaths().get("/hello").getGet(); - BodyParameter bp = (BodyParameter)operation.getParameters().get(0); + BodyParameter bp = (BodyParameter) operation.getParameters().get(0); assertTrue(bp.getSchema() instanceof RefModel); Model body = swagger.getDefinitions().get("body"); @@ -686,12 +651,10 @@ public void testArbitraryObjectBodyParamInline() { public void testArbitraryObjectBodyParamWithArray() { Swagger swagger = new Swagger(); - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(new ArrayModel() - .items(new ObjectProperty()))))); + swagger.path( + "/hello", + new Path().get(new Operation().parameter(new BodyParameter().name("body").schema( + new ArrayModel().items(new ObjectProperty()))))); new InlineModelResolver().flatten(swagger); @@ -716,13 +679,10 @@ public void testArbitraryObjectBodyParamWithArray() { public void testArbitraryObjectBodyParamArrayInline() { Swagger swagger = new Swagger(); - swagger.path("/hello", new Path() - .get(new Operation() - .parameter(new BodyParameter() - .name("body") - .schema(new ArrayModel() - .items(new ObjectProperty() - .property("arbitrary", new ObjectProperty())))))); + swagger.path("/hello", new Path().get(new Operation().parameter(new BodyParameter().name( + "body").schema( + new ArrayModel().items(new ObjectProperty().property("arbitrary", + new ObjectProperty())))))); new InlineModelResolver().flatten(swagger); @@ -757,14 +717,12 @@ public void testArbitraryObjectBodyParamArrayInline() { public void testArbitraryObjectResponse() { Swagger swagger = new Swagger(); - swagger.path("/foo/bar", new Path() - .get(new Operation() - .response(200, new Response() - .description("it works!") - .schema(new ObjectProperty())))); + swagger.path("/foo/bar", new Path().get(new Operation().response(200, new Response() + .description("it works!").schema(new ObjectProperty())))); new InlineModelResolver().flatten(swagger); - Map responses = swagger.getPaths().get("/foo/bar").getGet().getResponses(); + Map responses = + swagger.getPaths().get("/foo/bar").getGet().getResponses(); Response response = responses.get("200"); assertNotNull(response); @@ -777,12 +735,8 @@ public void testArbitraryObjectResponse() { public void testArbitraryObjectResponseArray() { Swagger swagger = new Swagger(); - swagger.path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .description("it works!") - .schema(new ArrayProperty() - .items(new ObjectProperty()))))); + swagger.path("/foo/baz", new Path().get(new Operation().response(200, new Response() + .description("it works!").schema(new ArrayProperty().items(new ObjectProperty()))))); new InlineModelResolver().flatten(swagger); Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200"); @@ -799,14 +753,13 @@ public void testArbitraryObjectResponseArray() { public void testArbitraryObjectResponseArrayInline() { Swagger swagger = new Swagger(); - swagger.path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .vendorExtension("x-foo", "bar") - .description("it works!") - .schema(new ArrayProperty() - .items(new ObjectProperty() - .property("arbitrary", new ObjectProperty())))))); + swagger.path("/foo/baz", new Path().get(new Operation().response( + 200, + new Response() + .vendorExtension("x-foo", "bar") + .description("it works!") + .schema(new ArrayProperty().items(new ObjectProperty().property( + "arbitrary", new ObjectProperty())))))); new InlineModelResolver().flatten(swagger); @@ -844,11 +797,8 @@ public void testArbitraryObjectResponseMapInline() { MapProperty schema = new MapProperty(); schema.setAdditionalProperties(new ObjectProperty()); - swagger.path("/foo/baz", new Path() - .get(new Operation() - .response(200, new Response() - .description("it works!") - .schema(schema)))); + swagger.path("/foo/baz", new Path().get(new Operation().response(200, new Response() + .description("it works!").schema(schema)))); new InlineModelResolver().flatten(swagger); Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200"); @@ -866,22 +816,21 @@ public void testArbitraryObjectResponseMapInline() { public void testArbitraryObjectModelInline() { Swagger swagger = new Swagger(); - swagger.addDefinition("User", new ModelImpl() - .name("user") - .description("a common user") - .property("name", new StringProperty()) - .property("arbitrary", new ObjectProperty() - .title("title") - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name"))); + swagger.addDefinition( + "User", + new ModelImpl() + .name("user") + .description("a common user") + .property("name", new StringProperty()) + .property( + "arbitrary", + new ObjectProperty().title("title")._default("default") + .access("access").readOnly(false).required(true) + .description("description").name("name"))); new InlineModelResolver().flatten(swagger); - ModelImpl user = (ModelImpl)swagger.getDefinitions().get("User"); + ModelImpl user = (ModelImpl) swagger.getDefinitions().get("User"); assertNotNull(user); Property inlineProp = user.getProperties().get("arbitrary"); assertTrue(inlineProp instanceof ObjectProperty); @@ -893,14 +842,10 @@ public void testArbitraryObjectModelInline() { public void testArbitraryObjectModelWithArrayInlineWithoutTitle() { Swagger swagger = new Swagger(); - swagger.addDefinition("User", new ArrayModel() - .items(new ObjectProperty() - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") + swagger.addDefinition( + "User", + new ArrayModel().items(new ObjectProperty()._default("default").access("access") + .readOnly(false).required(true).description("description").name("name") .property("arbitrary", new ObjectProperty()))); new InlineModelResolver().flatten(swagger); @@ -911,27 +856,23 @@ public void testArbitraryObjectModelWithArrayInlineWithoutTitle() { Property inner = am.getItems(); assertTrue(inner instanceof RefProperty); - ModelImpl userInner = (ModelImpl)swagger.getDefinitions().get("User_inner"); + ModelImpl userInner = (ModelImpl) swagger.getDefinitions().get("User_inner"); assertNotNull(userInner); Property inlineProp = userInner.getProperties().get("arbitrary"); assertTrue(inlineProp instanceof ObjectProperty); ObjectProperty op = (ObjectProperty) inlineProp; assertNull(op.getProperties()); } - + @Test public void testArbitraryObjectModelWithArrayInlineWithTitle() { Swagger swagger = new Swagger(); - swagger.addDefinition("User", new ArrayModel() - .items(new ObjectProperty() - .title("InnerUserTitle") - ._default("default") - .access("access") - .readOnly(false) - .required(true) - .description("description") - .name("name") + swagger.addDefinition( + "User", + new ArrayModel().items(new ObjectProperty().title("InnerUserTitle") + ._default("default").access("access").readOnly(false).required(true) + .description("description").name("name") .property("arbitrary", new ObjectProperty()))); new InlineModelResolver().flatten(swagger); @@ -942,11 +883,11 @@ public void testArbitraryObjectModelWithArrayInlineWithTitle() { Property inner = am.getItems(); assertTrue(inner instanceof RefProperty); - ModelImpl userInner = (ModelImpl)swagger.getDefinitions().get("InnerUserTitle"); + ModelImpl userInner = (ModelImpl) swagger.getDefinitions().get("InnerUserTitle"); assertNotNull(userInner); Property inlineProp = userInner.getProperties().get("arbitrary"); assertTrue(inlineProp instanceof ObjectProperty); ObjectProperty op = (ObjectProperty) inlineProp; assertNull(op.getProperties()); - } + } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java index 4acf7d5aaa9..928233346a3 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java @@ -25,15 +25,18 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(AkkaScalaClientOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(AkkaScalaClientOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(AkkaScalaClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setSourceFolder(AkkaScalaClientOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setModelPackage(AkkaScalaClientOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(AkkaScalaClientOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(AkkaScalaClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setSourceFolder(AkkaScalaClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java index d3e97de43b8..c778fd47f1a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java @@ -25,31 +25,38 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(AndroidClientOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(AndroidClientOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(AndroidClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(AndroidClientOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(AndroidClientOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(AndroidClientOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(AndroidClientOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setSourceFolder(AndroidClientOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setUseAndroidMavenGradlePlugin(Boolean.valueOf(AndroidClientOptionsProvider.ANDROID_MAVEN_GRADLE_PLUGIN_VALUE)); - times = 1; - clientCodegen.setLibrary(AndroidClientOptionsProvider.LIBRARY_VALUE); - times = 1; - clientCodegen.setSerializableModel(Boolean.valueOf(AndroidClientOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - clientCodegen.setAllowUnicodeIdentifiers(Boolean.valueOf(AndroidClientOptionsProvider.ALLOW_UNICODE_IDENTIFIERS_VALUE)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setModelPackage(AndroidClientOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(AndroidClientOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(AndroidClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setInvokerPackage(AndroidClientOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(AndroidClientOptionsProvider.GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(AndroidClientOptionsProvider.ARTIFACT_ID_VALUE); + times = 1; + clientCodegen + .setArtifactVersion(AndroidClientOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen.setSourceFolder(AndroidClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setUseAndroidMavenGradlePlugin(Boolean + .valueOf(AndroidClientOptionsProvider.ANDROID_MAVEN_GRADLE_PLUGIN_VALUE)); + times = 1; + clientCodegen.setLibrary(AndroidClientOptionsProvider.LIBRARY_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean + .valueOf(AndroidClientOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + times = 1; + clientCodegen.setAllowUnicodeIdentifiers(Boolean + .valueOf(AndroidClientOptionsProvider.ALLOW_UNICODE_IDENTIFIERS_VALUE)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/aspnetcore/AspNetCoreServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/aspnetcore/AspNetCoreServerOptionsTest.java index befeb4f1865..fc0e4fb5c4b 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/aspnetcore/AspNetCoreServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/aspnetcore/AspNetCoreServerOptionsTest.java @@ -24,19 +24,22 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(serverCodegen) {{ - serverCodegen.setPackageName(AspNetCoreServerOptionsProvider.PACKAGE_NAME_VALUE); - times = 1; - serverCodegen.setPackageVersion(AspNetCoreServerOptionsProvider.PACKAGE_VERSION_VALUE); - times = 1; - serverCodegen.setSourceFolder(AspNetCoreServerOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - serverCodegen.useDateTimeOffset(true); - times = 1; - serverCodegen.setUseCollection(false); - times = 1; - serverCodegen.setReturnICollection(false); - times = 1; - }}; + new Expectations(serverCodegen) { + { + serverCodegen.setPackageName(AspNetCoreServerOptionsProvider.PACKAGE_NAME_VALUE); + times = 1; + serverCodegen + .setPackageVersion(AspNetCoreServerOptionsProvider.PACKAGE_VERSION_VALUE); + times = 1; + serverCodegen.setSourceFolder(AspNetCoreServerOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + serverCodegen.useDateTimeOffset(true); + times = 1; + serverCodegen.setUseCollection(false); + times = 1; + serverCodegen.setReturnICollection(false); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java index 12f4f19e379..99e28129957 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java @@ -25,15 +25,18 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(AsyncScalaClientOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(AsyncScalaClientOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(AsyncScalaClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setSourceFolder(AsyncScalaClientOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setModelPackage(AsyncScalaClientOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(AsyncScalaClientOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(AsyncScalaClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setSourceFolder(AsyncScalaClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashClientOptionsTest.java index 1cfb8b847a3..a2ea2f91b10 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashClientOptionsTest.java @@ -25,35 +25,32 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setCurlOptions( - BashClientOptionsProvider.CURL_OPTIONS); - times = 1; - clientCodegen.setProcessMarkdown( - Boolean.parseBoolean( - BashClientOptionsProvider.PROCESS_MARKDOWN)); - times = 1; - clientCodegen.setScriptName( - BashClientOptionsProvider.SCRIPT_NAME); - times = 1; - clientCodegen.setGenerateBashCompletion( - Boolean.parseBoolean( - BashClientOptionsProvider.GENERATE_BASH_COMPLETION)); - times = 1; - clientCodegen.setGenerateZshCompletion( - Boolean.parseBoolean( - BashClientOptionsProvider.GENERATE_ZSH_COMPLETION)); - times = 1; - clientCodegen.setHostEnvironmentVariable( - BashClientOptionsProvider.HOST_ENVIRONMENT_VARIABLE_NAME); - times = 1; - clientCodegen.setApiKeyAuthEnvironmentVariable( - BashClientOptionsProvider.APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME); - times = 1; - clientCodegen.setAllowUnicodeIdentifiers(Boolean.valueOf(BashClientOptionsProvider.ALLOW_UNICODE_IDENTIFIERS_VALUE)); - times = 1; - - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setCurlOptions(BashClientOptionsProvider.CURL_OPTIONS); + times = 1; + clientCodegen.setProcessMarkdown(Boolean + .parseBoolean(BashClientOptionsProvider.PROCESS_MARKDOWN)); + times = 1; + clientCodegen.setScriptName(BashClientOptionsProvider.SCRIPT_NAME); + times = 1; + clientCodegen.setGenerateBashCompletion(Boolean + .parseBoolean(BashClientOptionsProvider.GENERATE_BASH_COMPLETION)); + times = 1; + clientCodegen.setGenerateZshCompletion(Boolean + .parseBoolean(BashClientOptionsProvider.GENERATE_ZSH_COMPLETION)); + times = 1; + clientCodegen + .setHostEnvironmentVariable(BashClientOptionsProvider.HOST_ENVIRONMENT_VARIABLE_NAME); + times = 1; + clientCodegen + .setApiKeyAuthEnvironmentVariable(BashClientOptionsProvider.APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME); + times = 1; + clientCodegen.setAllowUnicodeIdentifiers(Boolean + .valueOf(BashClientOptionsProvider.ALLOW_UNICODE_IDENTIFIERS_VALUE)); + times = 1; + + } + }; } } - diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashTest.java index 4f355723a7f..eb7928f0c17 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashTest.java @@ -32,54 +32,39 @@ public class BashTest { @Test(description = "test basic petstore operation with Bash extensions") public void petstoreOperationTest() { - final Swagger swagger - = new SwaggerParser() - .read("src/test/resources/2_0/petstore-bash.json"); + final Swagger swagger = + new SwaggerParser().read("src/test/resources/2_0/petstore-bash.json"); final DefaultCodegen codegen = new BashClientCodegen(); - final Operation findPetsByStatusOperation - = swagger.getPath("/pet/findByStatus").getGet(); + final Operation findPetsByStatusOperation = swagger.getPath("/pet/findByStatus").getGet(); - final CodegenOperation op - = codegen.fromOperation( - "/pet/findByStatus", - "GET", - findPetsByStatusOperation, - swagger.getDefinitions(), - swagger); + final CodegenOperation op = + codegen.fromOperation("/pet/findByStatus", "GET", findPetsByStatusOperation, + swagger.getDefinitions(), swagger); - Assert.assertTrue( - op.vendorExtensions.containsKey("x-bash-codegen-sample")); + Assert.assertTrue(op.vendorExtensions.containsKey("x-bash-codegen-sample")); - Assert.assertEquals( - op.vendorExtensions.get("x-bash-codegen-description"), - "Multiple status 'values' can be provided with comma separated strings"); + Assert.assertEquals(op.vendorExtensions.get("x-bash-codegen-description"), + "Multiple status 'values' can be provided with comma separated strings"); } @Test(description = "test basic petstore operation with example body") public void petstoreParameterExampleTest() { - final Swagger swagger - = new SwaggerParser() - .read("src/test/resources/2_0/petstore-bash.json"); + final Swagger swagger = + new SwaggerParser().read("src/test/resources/2_0/petstore-bash.json"); final DefaultCodegen codegen = new BashClientCodegen(); - final Operation addPetOperation - = swagger.getPath("/pet").getPost(); + final Operation addPetOperation = swagger.getPath("/pet").getPost(); - final CodegenOperation op - = codegen.fromOperation( - "/pet", - "POST", - addPetOperation, - swagger.getDefinitions(), - swagger); + final CodegenOperation op = + codegen.fromOperation("/pet", "POST", addPetOperation, swagger.getDefinitions(), + swagger); Assert.assertEquals(op.bodyParams.size(), 1); CodegenParameter pet = op.bodyParams.get(0); - Assert.assertTrue(pet.vendorExtensions - .containsKey("x-codegen-body-example")); + Assert.assertTrue(pet.vendorExtensions.containsKey("x-codegen-body-example")); } @@ -94,59 +79,53 @@ public void escapeTextTest() { Assert.assertEquals(codegen.escapeText("\\"), "\\\\"); - ((BashClientCodegen)codegen).setProcessMarkdown(false); + ((BashClientCodegen) codegen).setProcessMarkdown(false); - Assert.assertEquals(codegen.escapeText("__Bold text__"), - "__Bold text__"); + Assert.assertEquals(codegen.escapeText("__Bold text__"), "__Bold text__"); - Assert.assertEquals(codegen.escapeText("**Bold text**"), - "**Bold text**"); + Assert.assertEquals(codegen.escapeText("**Bold text**"), "**Bold text**"); - Assert.assertEquals(codegen.escapeText("*Italic text*"), - "*Italic text*"); + Assert.assertEquals(codegen.escapeText("*Italic text*"), "*Italic text*"); - Assert.assertEquals(codegen.escapeText("_Italic text_"), - "_Italic text_"); + Assert.assertEquals(codegen.escapeText("_Italic text_"), "_Italic text_"); - ((BashClientCodegen)codegen).setProcessMarkdown(true); + ((BashClientCodegen) codegen).setProcessMarkdown(true); - Assert.assertEquals(codegen.escapeText("__Bold text__"), - "$(tput bold) Bold text $(tput sgr0)"); + Assert.assertEquals(codegen.escapeText("__Bold text__"), + "$(tput bold) Bold text $(tput sgr0)"); - Assert.assertEquals(codegen.escapeText("**Bold text**"), - "$(tput bold) Bold text $(tput sgr0)"); + Assert.assertEquals(codegen.escapeText("**Bold text**"), + "$(tput bold) Bold text $(tput sgr0)"); - Assert.assertEquals(codegen.escapeText("*Italic text*"), - "$(tput dim) Italic text $(tput sgr0)"); + Assert.assertEquals(codegen.escapeText("*Italic text*"), + "$(tput dim) Italic text $(tput sgr0)"); - Assert.assertEquals(codegen.escapeText("_Italic text_"), - "$(tput dim) Italic text $(tput sgr0)"); + Assert.assertEquals(codegen.escapeText("_Italic text_"), + "$(tput dim) Italic text $(tput sgr0)"); - Assert.assertEquals(codegen.escapeText("# SECTION NAME"), - "\n$(tput bold)$(tput setaf 7)SECTION NAME$(tput sgr0)"); + Assert.assertEquals(codegen.escapeText("# SECTION NAME"), + "\n$(tput bold)$(tput setaf 7)SECTION NAME$(tput sgr0)"); - Assert.assertEquals(codegen.escapeText("## SECTION NAME"), - "\n$(tput bold)$(tput setaf 7)SECTION NAME$(tput sgr0)"); + Assert.assertEquals(codegen.escapeText("## SECTION NAME"), + "\n$(tput bold)$(tput setaf 7)SECTION NAME$(tput sgr0)"); - Assert.assertEquals(codegen.escapeText("### SECTION NAME"), - "\n$(tput bold)$(tput setaf 7)SECTION NAME$(tput sgr0)"); + Assert.assertEquals(codegen.escapeText("### SECTION NAME"), + "\n$(tput bold)$(tput setaf 7)SECTION NAME$(tput sgr0)"); - Assert.assertEquals(codegen.escapeText( - "```\nnice -n 100 mvn test\n```"), - "\n---\nnice -n 100 mvn test\n---"); + Assert.assertEquals(codegen.escapeText("```\nnice -n 100 mvn test\n```"), + "\n---\nnice -n 100 mvn test\n---"); } @Test(description = "test Bash client codegen escapeUnsafeCharacters method") public void escapeUnsafeCharactersTest() { final DefaultCodegen codegen = new BashClientCodegen(); - Assert.assertEquals(codegen.escapeUnsafeCharacters("`no backticks`"), - "'no backticks'"); + Assert.assertEquals(codegen.escapeUnsafeCharacters("`no backticks`"), "'no backticks'"); } - + @Test(description = "test Bash client codegen escapeReservedWord method") public void escapeReservedWordTest() { final DefaultCodegen codegen = new BashClientCodegen(); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java index edffc835de8..ce905c6ddc4 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java @@ -52,16 +52,18 @@ public void testVerbose() throws Exception { configurator.setVerbose(true); - new StrictExpectations(System.class) {{ - System.setProperty("debugSwagger", ""); - times = 1; - System.setProperty("debugModels", ""); - times = 1; - System.setProperty("debugOperations", ""); - times = 1; - System.setProperty("debugSupportingFiles", ""); - times = 1; - }}; + new StrictExpectations(System.class) { + { + System.setProperty("debugSwagger", ""); + times = 1; + System.setProperty("debugModels", ""); + times = 1; + System.setProperty("debugOperations", ""); + times = 1; + System.setProperty("debugSupportingFiles", ""); + times = 1; + } + }; setupAndRunGenericTest(configurator); } @@ -74,22 +76,24 @@ public void testTemplateDir() throws Exception { final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.TEMPLATE_DIR, toAbsolutePathDir(templateDir)); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), + CodegenConstants.TEMPLATE_DIR, toAbsolutePathDir(templateDir)); } @SuppressWarnings("unused") @Test public void testSystemProperties() throws Exception { - configurator.addSystemProperty("hello", "world") - .addSystemProperty("foo", "bar"); + configurator.addSystemProperty("hello", "world").addSystemProperty("foo", "bar"); - new Expectations(System.class) {{ - System.setProperty("hello", "world"); - times = 1; - System.setProperty("foo", "bar"); - times = 1; - }}; + new Expectations(System.class) { + { + System.setProperty("hello", "world"); + times = 1; + System.setProperty("foo", "bar"); + times = 1; + } + }; setupAndRunGenericTest(configurator); } @@ -115,7 +119,8 @@ public void testApiPackage() throws Exception { configurator.setApiPackage(apiPackage); final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.API_PACKAGE, apiPackage); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), + CodegenConstants.API_PACKAGE, apiPackage); } @@ -125,14 +130,14 @@ public void testModelPackage() throws Exception { configurator.setModelPackage(modelPackage); final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.MODEL_PACKAGE, modelPackage); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), + CodegenConstants.MODEL_PACKAGE, modelPackage); } @Test public void testInstantiationTypes() throws Exception { - configurator.addInstantiationType("foo", "bar") - .addInstantiationType("hello", "world"); + configurator.addInstantiationType("foo", "bar").addInstantiationType("hello", "world"); final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); @@ -143,8 +148,7 @@ public void testInstantiationTypes() throws Exception { @Test public void testTypeMappings() throws Exception { - configurator.addTypeMapping("foo", "bar") - .addTypeMapping("hello", "world"); + configurator.addTypeMapping("foo", "bar").addTypeMapping("hello", "world"); final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); @@ -155,8 +159,7 @@ public void testTypeMappings() throws Exception { @Test public void testAdditionalProperties() throws Exception { - configurator.addAdditionalProperty("foo", "bar") - .addAdditionalProperty("hello", "world") + configurator.addAdditionalProperty("foo", "bar").addAdditionalProperty("hello", "world") .addAdditionalProperty("supportJava6", false) .addAdditionalProperty("useRxJava", true); @@ -171,10 +174,8 @@ public void testAdditionalProperties() throws Exception { @Test public void testLanguageSpecificPrimitives() throws Exception { - configurator.addLanguageSpecificPrimitive("foo") - .addLanguageSpecificPrimitive("bar") - .addLanguageSpecificPrimitive("hello") - .addLanguageSpecificPrimitive("world"); + configurator.addLanguageSpecificPrimitive("foo").addLanguageSpecificPrimitive("bar") + .addLanguageSpecificPrimitive("hello").addLanguageSpecificPrimitive("world"); final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); @@ -187,8 +188,7 @@ public void testLanguageSpecificPrimitives() throws Exception { @Test public void testImportMappings() throws Exception { - configurator.addImportMapping("foo", "bar") - .addImportMapping("hello", "world"); + configurator.addImportMapping("foo", "bar").addImportMapping("hello", "world"); final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); @@ -202,7 +202,8 @@ public void testInvokerPackage() throws Exception { configurator.setInvokerPackage(invokerPackage); final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.INVOKER_PACKAGE, invokerPackage); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), + CodegenConstants.INVOKER_PACKAGE, invokerPackage); } @Test @@ -211,7 +212,8 @@ public void testGroupId() throws Exception { configurator.setGroupId(expectedValue); final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.GROUP_ID, expectedValue); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), + CodegenConstants.GROUP_ID, expectedValue); } @Test @@ -220,7 +222,8 @@ public void testArtifactId() throws Exception { configurator.setArtifactId(expectedValue); final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.ARTIFACT_ID, expectedValue); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), + CodegenConstants.ARTIFACT_ID, expectedValue); } @Test @@ -229,7 +232,8 @@ public void testArtifactVersion() throws Exception { configurator.setArtifactVersion(expectedValue); final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.ARTIFACT_VERSION, expectedValue); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), + CodegenConstants.ARTIFACT_VERSION, expectedValue); } @Test @@ -250,14 +254,16 @@ public void testDynamicProperties() throws Exception { final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); - assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.LOCAL_VARIABLE_PREFIX, "_"); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), + CodegenConstants.LOCAL_VARIABLE_PREFIX, "_"); assertValueInMap(clientOptInput.getConfig().additionalProperties(), "supportJava6", false); assertValueInMap(clientOptInput.getConfig().additionalProperties(), "useRxJava", true); } @Test public void testFromFile() throws Exception { - final CodegenConfigurator configurator = CodegenConfigurator.fromFile("src/test/resources/sampleConfig.json"); + final CodegenConfigurator configurator = + CodegenConfigurator.fromFile("src/test/resources/sampleConfig.json"); assertEquals(configurator.getLang(), "java"); assertEquals(configurator.getInputSpec(), "swagger.yaml"); @@ -294,9 +300,11 @@ public void testFromFile() throws Exception { assertTrue(configurator.getLanguageSpecificPrimitives().contains("rolex")); assertEquals(configurator.getDynamicProperties().size(), 1); - assertValueInMap(configurator.getDynamicProperties(), CodegenConstants.LOCAL_VARIABLE_PREFIX, "_"); + assertValueInMap(configurator.getDynamicProperties(), + CodegenConstants.LOCAL_VARIABLE_PREFIX, "_"); - assertEquals(configurator.getIgnoreFileOverride(), "/path/to/override/.swagger-codegen-ignore"); + assertEquals(configurator.getIgnoreFileOverride(), + "/path/to/override/.swagger-codegen-ignore"); } @SuppressWarnings("unused") @@ -308,10 +316,7 @@ private ClientOptInput setupAndRunGenericTest(CodegenConfigurator configurator) final String expectedAuth = "hello:world"; - configurator.setLang(lang) - .setOutputDir(outputDir) - .setInputSpec(spec) - .setAuth(expectedAuth); + configurator.setLang(lang).setOutputDir(outputDir).setInputSpec(spec).setAuth(expectedAuth); final CodegenConfig config = new JavaClientCodegen(); @@ -319,8 +324,10 @@ private ClientOptInput setupAndRunGenericTest(CodegenConfigurator configurator) ClientOptInput result = configurator.toClientOptInput(); - new FullVerifications() {{ - }}; + new FullVerifications() { + { + } + }; final String expectedOutputDir = toAbsolutePathDir(outputDir); @@ -334,27 +341,33 @@ private static String toAbsolutePathDir(String outputDir) { } @SuppressWarnings("unused") - private void setupStandardExpectations(final String spec, final String languageName, final String auth, final CodegenConfig config) { + private void setupStandardExpectations(final String spec, final String languageName, + final String auth, final CodegenConfig config) { - new StrictExpectations() {{ - CodegenConfigLoader.forName(languageName); - times = 1; - result = config; + new StrictExpectations() { + { + CodegenConfigLoader.forName(languageName); + times = 1; + result = config; - AuthParser.parse(auth); times=1; result = authorizationValues; + AuthParser.parse(auth); + times = 1; + result = authorizationValues; - new SwaggerParser(); - times = 1; - result = parser; + new SwaggerParser(); + times = 1; + result = parser; - parser.read(spec, authorizationValues, true); - times = 1; - result = swagger; + parser.read(spec, authorizationValues, true); + times = 1; + result = swagger; - }}; + } + }; } - private static void assertValueInMap(Map map, String propertyKey, Object expectedPropertyValue) { + private static void assertValueInMap(Map map, String propertyKey, + Object expectedPropertyValue) { assertTrue(map.containsKey(propertyKey)); assertEquals(map.get(propertyKey), expectedPropertyValue); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java index 37b37ba0b8f..f18b2d40823 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java @@ -25,38 +25,41 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setPackageName(CSharpClientOptionsProvider.PACKAGE_NAME_VALUE); - times = 1; - clientCodegen.setOptionalMethodArgumentFlag(true); - times = 1; - clientCodegen.setPackageVersion(CSharpClientOptionsProvider.PACKAGE_VERSION_VALUE); - times = 1; - clientCodegen.setOptionalAssemblyInfoFlag(true); - times = 1; - clientCodegen.setSourceFolder(CSharpClientOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.useDateTimeOffset(true); - times = 1; - clientCodegen.setOptionalProjectFileFlag(true); - times = 1; - clientCodegen.setPackageGuid(CSharpClientOptionsProvider.PACKAGE_GUID_VALUE); - times = 1; - clientCodegen.setUseCollection(false); - times = 1; - clientCodegen.setReturnICollection(false); - times = 1; - clientCodegen.setOptionalEmitDefaultValue(true); - times = 1; - clientCodegen.setGeneratePropertyChanged(true); - times = 1; - clientCodegen.setNonPublicApi(true); - times = 1; - clientCodegen.setInterfacePrefix("X"); - times = 1; - clientCodegen.setAllowUnicodeIdentifiers(Boolean.valueOf(CSharpClientOptionsProvider.ALLOW_UNICODE_IDENTIFIERS_VALUE)); - times = 1; - - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setPackageName(CSharpClientOptionsProvider.PACKAGE_NAME_VALUE); + times = 1; + clientCodegen.setOptionalMethodArgumentFlag(true); + times = 1; + clientCodegen.setPackageVersion(CSharpClientOptionsProvider.PACKAGE_VERSION_VALUE); + times = 1; + clientCodegen.setOptionalAssemblyInfoFlag(true); + times = 1; + clientCodegen.setSourceFolder(CSharpClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.useDateTimeOffset(true); + times = 1; + clientCodegen.setOptionalProjectFileFlag(true); + times = 1; + clientCodegen.setPackageGuid(CSharpClientOptionsProvider.PACKAGE_GUID_VALUE); + times = 1; + clientCodegen.setUseCollection(false); + times = 1; + clientCodegen.setReturnICollection(false); + times = 1; + clientCodegen.setOptionalEmitDefaultValue(true); + times = 1; + clientCodegen.setGeneratePropertyChanged(true); + times = 1; + clientCodegen.setNonPublicApi(true); + times = 1; + clientCodegen.setInterfacePrefix("X"); + times = 1; + clientCodegen.setAllowUnicodeIdentifiers(Boolean + .valueOf(CSharpClientOptionsProvider.ALLOW_UNICODE_IDENTIFIERS_VALUE)); + times = 1; + + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpModelTest.java index 6e5c2076f5d..68b5071836a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpModelTest.java @@ -101,22 +101,18 @@ public void arrayPropertyICollectionOptionTest() { } private Model getArrayTestModel() { - return new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) + return new ModelImpl().description("a sample model").property("id", new LongProperty()) .property("examples", new ArrayProperty().items(new StringProperty())) .required("id"); } @Test(description = "convert a simple 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()) - .required("id") - .required("name"); + final Model model = + new ModelImpl().description("a sample model").property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()).required("id") + .required("name"); final DefaultCodegen codegen = new CSharpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -160,12 +156,10 @@ public void simpleModelTest() { @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 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 CSharpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -200,11 +194,12 @@ public void listPropertyTest() { @Test(description = "convert a model with a map property") public void mapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); + final Model model = + new ModelImpl() + .description("a sample model") + .property("translations", + new MapProperty().additionalProperties(new StringProperty())) + .required("id"); final DefaultCodegen codegen = new CSharpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -226,9 +221,9 @@ public void mapPropertyTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new CSharpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -248,10 +243,9 @@ public void complexPropertyTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new ArrayProperty().items(new RefProperty("#/definitions/Children"))); final DefaultCodegen codegen = new CSharpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -273,10 +267,11 @@ public void complexListPropertyTest() { @Test(description = "convert a model with complex map property") public void complexMapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new MapProperty() - .additionalProperties(new RefProperty("#/definitions/Children"))); + final Model model = + new ModelImpl().description("a sample model").property( + "children", + new MapProperty().additionalProperties(new RefProperty( + "#/definitions/Children"))); final DefaultCodegen codegen = new CSharpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -300,9 +295,9 @@ public void complexMapPropertyTest() { @Test(description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Model model = + new ArrayModel().description("an array model").items( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new CSharpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -317,9 +312,9 @@ public void arrayModelTest() { @Test(description = "convert an map model") public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + final Model model = + new ModelImpl().description("a map model").additionalProperties( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new CSharpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java index cb3854e2bd8..14a4535594f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java @@ -25,13 +25,17 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setPackageName(CsharpDotNet2ClientOptionsProvider.PACKAGE_NAME_VALUE); - times = 1; - clientCodegen.setPackageVersion(CsharpDotNet2ClientOptionsProvider.PACKAGE_VERSION_VALUE); - times = 1; - clientCodegen.setClientPackage(CsharpDotNet2ClientOptionsProvider.CLIENT_PACKAGE_VALUE); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setPackageName(CsharpDotNet2ClientOptionsProvider.PACKAGE_NAME_VALUE); + times = 1; + clientCodegen + .setPackageVersion(CsharpDotNet2ClientOptionsProvider.PACKAGE_VERSION_VALUE); + times = 1; + clientCodegen + .setClientPackage(CsharpDotNet2ClientOptionsProvider.CLIENT_PACKAGE_VALUE); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java index 519ac4943cc..b47dcde414a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java @@ -25,20 +25,23 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(DartClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setBrowserClient(Boolean.valueOf(DartClientOptionsProvider.BROWSER_CLIENT_VALUE)); - times = 1; - clientCodegen.setPubName(DartClientOptionsProvider.PUB_NAME_VALUE); - times = 1; - clientCodegen.setPubVersion(DartClientOptionsProvider.PUB_VERSION_VALUE); - times = 1; - clientCodegen.setPubDescription(DartClientOptionsProvider.PUB_DESCRIPTION_VALUE); - times = 1; - clientCodegen.setSourceFolder(DartClientOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(DartClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setBrowserClient(Boolean + .valueOf(DartClientOptionsProvider.BROWSER_CLIENT_VALUE)); + times = 1; + clientCodegen.setPubName(DartClientOptionsProvider.PUB_NAME_VALUE); + times = 1; + clientCodegen.setPubVersion(DartClientOptionsProvider.PUB_VERSION_VALUE); + times = 1; + clientCodegen.setPubDescription(DartClientOptionsProvider.PUB_DESCRIPTION_VALUE); + times = 1; + clientCodegen.setSourceFolder(DartClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + } + }; } } - diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/elixir/ElixirClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/elixir/ElixirClientOptionsTest.java index edeab0eb284..7686470f94b 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/elixir/ElixirClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/elixir/ElixirClientOptionsTest.java @@ -24,8 +24,10 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - // TODO - }}; + new Expectations(clientCodegen) { + { + // TODO + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java index d3debf29579..240b1f410da 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java @@ -25,15 +25,17 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setPackageName(FlashClienOptionsProvider.PACKAGE_NAME_VALUE); - times = 1; - clientCodegen.setPackageVersion(FlashClienOptionsProvider.PACKAGE_VERSION_VALUE); - times = 1; - clientCodegen.setInvokerPackage(FlashClienOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setSourceFolder(FlashClienOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setPackageName(FlashClienOptionsProvider.PACKAGE_NAME_VALUE); + times = 1; + clientCodegen.setPackageVersion(FlashClienOptionsProvider.PACKAGE_VERSION_VALUE); + times = 1; + clientCodegen.setInvokerPackage(FlashClienOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setSourceFolder(FlashClienOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoClientOptionsTest.java index 5baf4f9eb1c..090055a7669 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoClientOptionsTest.java @@ -25,11 +25,13 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setPackageVersion(GoClientOptionsProvider.PACKAGE_VERSION_VALUE); - times = 1; - clientCodegen.setPackageName(GoClientOptionsProvider.PACKAGE_NAME_VALUE); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setPackageVersion(GoClientOptionsProvider.PACKAGE_VERSION_VALUE); + times = 1; + clientCodegen.setPackageName(GoClientOptionsProvider.PACKAGE_NAME_VALUE); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoModelTest.java index e631b259445..3215ab6de74 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoModelTest.java @@ -24,13 +24,11 @@ public class GoModelTest { @Test(description = "convert a simple Go 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()) - .required("id") - .required("name"); + final Model model = + new ModelImpl().description("a sample model").property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()).required("id") + .required("name"); final DefaultCodegen codegen = new GoClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -76,12 +74,10 @@ public void simpleModelTest() { @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 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 GoClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -115,11 +111,12 @@ public void listPropertyTest() { @Test(description = "convert a model with a map property") public void mapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); + final Model model = + new ModelImpl() + .description("a sample model") + .property("translations", + new MapProperty().additionalProperties(new StringProperty())) + .required("id"); final DefaultCodegen codegen = new GoClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -141,9 +138,9 @@ public void mapPropertyTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new GoClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -163,10 +160,9 @@ public void complexPropertyTest() { @Test(description = "convert a model with complex list property") public void complexListProperty() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))); + final Model model = + new ModelImpl().description("a sample model").property("children", + new ArrayProperty().items(new RefProperty("#/definitions/Children"))); final DefaultCodegen codegen = new GoClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -187,10 +183,11 @@ public void complexListProperty() { @Test(description = "convert a model with complex map property") public void complexMapProperty() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new MapProperty() - .additionalProperties(new RefProperty("#/definitions/Children"))); + final Model model = + new ModelImpl().description("a sample model").property( + "children", + new MapProperty().additionalProperties(new RefProperty( + "#/definitions/Children"))); final DefaultCodegen codegen = new GoClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -214,9 +211,9 @@ public void complexMapProperty() { @Test(description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Model model = + new ArrayModel().description("an array model").items( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new GoClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -229,9 +226,9 @@ public void arrayModelTest() { @Test(description = "convert an map model") public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + final Model model = + new ModelImpl().description("a map model").additionalProperties( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new GoClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -245,15 +242,9 @@ public void mapModelTest() { @DataProvider(name = "modelNames") public static Object[][] primeNumbers() { - return new Object[][] { - {"sample", "Sample"}, - {"sample_name", "SampleName"}, - {"sample__name", "SampleName"}, - {"/sample", "Sample"}, - {"\\sample", "Sample"}, - {"sample.name", "SampleName"}, - {"_sample", "Sample"}, - }; + return new Object[][] { {"sample", "Sample"}, {"sample_name", "SampleName"}, + {"sample__name", "SampleName"}, {"/sample", "Sample"}, {"\\sample", "Sample"}, + {"sample.name", "SampleName"}, {"_sample", "Sample"},}; } @Test(dataProvider = "modelNames", description = "avoid inner class") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/haskellservant/HaskellServantOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/haskellservant/HaskellServantOptionsTest.java index d5848e47cae..e0297684749 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/haskellservant/HaskellServantOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/haskellservant/HaskellServantOptionsTest.java @@ -24,13 +24,16 @@ protected CodegenConfig getCodegenConfig() { @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(HaskellServantOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(HaskellServantOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(HaskellServantOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setModelPackage(HaskellServantOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(HaskellServantOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(HaskellServantOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java index da4a46f4af8..cad0cf0226f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java @@ -26,7 +26,8 @@ public class CodegenIgnoreProcessorTest { private File target; private Path temp; - private CodegenIgnoreProcessorTest(String filename, String ignoreDefinition, String description) throws IOException { + private CodegenIgnoreProcessorTest(String filename, String ignoreDefinition, String description) + throws IOException { this.filename = filename; this.ignoreDefinition = ignoreDefinition; this.description = description; @@ -48,23 +49,25 @@ CodegenIgnoreProcessorTest ignored() { } private void prepareTestFiles() throws IOException { - // NOTE: Each test needs its own directory because .swagger-codegen-ignore needs to exist at the root. + // NOTE: Each test needs its own directory because .swagger-codegen-ignore needs to exist at + // the root. temp = Files.createTempDirectory(getClass().getSimpleName()); this.outputDir = temp.toFile().getAbsolutePath(); target = new File(this.outputDir, this.filename); boolean mkdirs = target.getParentFile().mkdirs(); - if(!mkdirs) { + if (!mkdirs) { LOGGER.warn("Failed to create directories for CodegenIgnoreProcessorTest test file. Directory may already exist."); } Path created = Files.createFile(target.toPath()); - if(!created.toFile().exists()) { + if (!created.toFile().exists()) { throw new IOException("Failed to write CodegenIgnoreProcessorTest test file."); } - // System.out.print(String.format("Created codegen ignore processor test file: %s\n", created.toAbsolutePath())); + // System.out.print(String.format("Created codegen ignore processor test file: %s\n", + // created.toAbsolutePath())); File ignoreFile = new File(this.outputDir, ".swagger-codegen-ignore"); try (FileOutputStream stream = new FileOutputStream(ignoreFile)) { stream.write(this.ignoreDefinition.getBytes()); @@ -73,14 +76,14 @@ private void prepareTestFiles() throws IOException { @AfterTest public void afterTest() throws IOException { - if(temp != null && temp.toFile().exists() && temp.toFile().isDirectory()) { + if (temp != null && temp.toFile().exists() && temp.toFile().isDirectory()) { FileUtils.deleteDirectory(temp.toFile()); } } @Test public void evaluate() { - if(this.skip) { + if (this.skip) { return; } @@ -106,49 +109,105 @@ public void evaluate() { public static Object[] factoryMethod() throws IOException { return new Object[] { // Matching filenames - new CodegenIgnoreProcessorTest("build.sh", "build.sh", "A file when matching should ignore.").ignored(), - new CodegenIgnoreProcessorTest("build.sh", "*.sh", "A file when matching glob should ignore.").ignored(), - new CodegenIgnoreProcessorTest("src/build.sh", "*.sh", "A nested file when matching non-nested simple glob should allow.").allowed(), - new CodegenIgnoreProcessorTest("src/build.sh", "**/build.sh", "A file when matching nested files should ignore.").ignored(), - new CodegenIgnoreProcessorTest("Build.sh", "build.sh", "A file when non-matching should allow.").allowed().skipOnCondition(SystemUtils.IS_OS_WINDOWS), - new CodegenIgnoreProcessorTest("build.sh", "/build.sh", "A rooted file when matching should ignore.").ignored(), - new CodegenIgnoreProcessorTest("nested/build.sh", "/build.sh", "A rooted file definition when non-matching should allow.").allowed(), - new CodegenIgnoreProcessorTest("src/IO.Swagger.Test/Model/AnimalFarmTests.cs", "src/IO.Swagger.Test/Model/AnimalFarmTests.cs", "A file when matching exactly should ignore.").ignored(), + new CodegenIgnoreProcessorTest("build.sh", "build.sh", + "A file when matching should ignore.").ignored(), + new CodegenIgnoreProcessorTest("build.sh", "*.sh", + "A file when matching glob should ignore.").ignored(), + new CodegenIgnoreProcessorTest("src/build.sh", "*.sh", + "A nested file when matching non-nested simple glob should allow.") + .allowed(), + new CodegenIgnoreProcessorTest("src/build.sh", "**/build.sh", + "A file when matching nested files should ignore.").ignored(), + new CodegenIgnoreProcessorTest("Build.sh", "build.sh", + "A file when non-matching should allow.").allowed().skipOnCondition( + SystemUtils.IS_OS_WINDOWS), + new CodegenIgnoreProcessorTest("build.sh", "/build.sh", + "A rooted file when matching should ignore.").ignored(), + new CodegenIgnoreProcessorTest("nested/build.sh", "/build.sh", + "A rooted file definition when non-matching should allow.").allowed(), + new CodegenIgnoreProcessorTest("src/IO.Swagger.Test/Model/AnimalFarmTests.cs", + "src/IO.Swagger.Test/Model/AnimalFarmTests.cs", + "A file when matching exactly should ignore.").ignored(), // Matching spaces in filenames - new CodegenIgnoreProcessorTest("src/properly escaped.txt", "**/properly escaped.txt", "A file when matching nested files with spaces in the name should ignore.").ignored(), - new CodegenIgnoreProcessorTest("src/improperly escaped.txt", "**/improperly\\ escaped.txt", "A file when matching nested files with spaces in the name (improperly escaped rule) should allow.").allowed(), + new CodegenIgnoreProcessorTest("src/properly escaped.txt", + "**/properly escaped.txt", + "A file when matching nested files with spaces in the name should ignore.") + .ignored(), + new CodegenIgnoreProcessorTest("src/improperly escaped.txt", + "**/improperly\\ escaped.txt", + "A file when matching nested files with spaces in the name (improperly escaped rule) should allow.") + .allowed(), // Match All - new CodegenIgnoreProcessorTest("docs/somefile.md", "docs/**", "A recursive file (0 level) when matching should ignore.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/somefile.md", "docs/**", "A recursive file (1 level) when matching should ignore.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/2/3/somefile.md", "docs/**", "A recursive file (n level) when matching should ignore.").ignored(), + new CodegenIgnoreProcessorTest("docs/somefile.md", "docs/**", + "A recursive file (0 level) when matching should ignore.").ignored(), + new CodegenIgnoreProcessorTest("docs/1/somefile.md", "docs/**", + "A recursive file (1 level) when matching should ignore.").ignored(), + new CodegenIgnoreProcessorTest("docs/1/2/3/somefile.md", "docs/**", + "A recursive file (n level) when matching should ignore.").ignored(), // Match Any - new CodegenIgnoreProcessorTest("docs/1/2/3/somefile.md", "docs/**/somefile.*", "A recursive file with match-any extension when matching should ignore.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/2/3/somefile.java", "docs/**/*.java", "A recursive file with match-any file name when matching should ignore.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/2/3/4/somefile.md", "docs/**/*", "A recursive file with match-any file name when matching should ignore.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/2/3/4/5/somefile.md", "docs/**/anyfile.*", "A recursive file with match-any extension when non-matching should allow.").allowed(), + new CodegenIgnoreProcessorTest("docs/1/2/3/somefile.md", "docs/**/somefile.*", + "A recursive file with match-any extension when matching should ignore.") + .ignored(), + new CodegenIgnoreProcessorTest("docs/1/2/3/somefile.java", "docs/**/*.java", + "A recursive file with match-any file name when matching should ignore.") + .ignored(), + new CodegenIgnoreProcessorTest("docs/1/2/3/4/somefile.md", "docs/**/*", + "A recursive file with match-any file name when matching should ignore.") + .ignored(), + new CodegenIgnoreProcessorTest("docs/1/2/3/4/5/somefile.md", "docs/**/anyfile.*", + "A recursive file with match-any extension when non-matching should allow.") + .allowed(), // Directory matches - new CodegenIgnoreProcessorTest("docs/1/Users/a", "docs/**/Users/", "A directory rule when matching should be ignored.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/Users1/a", "docs/**/Users/", "A directory rule when non-matching should be allowed.").allowed(), + new CodegenIgnoreProcessorTest("docs/1/Users/a", "docs/**/Users/", + "A directory rule when matching should be ignored.").ignored(), + new CodegenIgnoreProcessorTest("docs/1/Users1/a", "docs/**/Users/", + "A directory rule when non-matching should be allowed.").allowed(), // Negation of excluded recursive files - new CodegenIgnoreProcessorTest("docs/UserApi.md", "docs/**\n!docs/UserApi.md", "A pattern negating a previous ignore FILE rule should be allowed.").allowed(), + new CodegenIgnoreProcessorTest("docs/UserApi.md", "docs/**\n!docs/UserApi.md", + "A pattern negating a previous ignore FILE rule should be allowed.") + .allowed(), // Negation of excluded directories - new CodegenIgnoreProcessorTest("docs/1/Users/UserApi.md", "docs/**/Users/\n!docs/1/Users/UserApi.md", "A pattern negating a previous ignore DIRECTORY rule should be ignored.").ignored(), - - // Other matches which may not be parsed for correctness, but are free because of PathMatcher - new CodegenIgnoreProcessorTest("docs/1/2/3/Some99File.md", "**/*[0-9]*", "A file when matching against simple regex patterns when matching should be ignored.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/2/3/SomeFile.md", "**/*.{java,md}", "A file when matching against grouped subpatterns for extension when matching (md) should be ignored.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/2/3/SomeFile.java", "**/*.{java,md}", "A file when matching against grouped subpatterns for extension when matching (java) should be ignored.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/2/3/SomeFile.txt", "**/*.{java,md}", "A file when matching against grouped subpatterns for extension when non-matching should be allowed.").allowed(), - - new CodegenIgnoreProcessorTest("docs/1/2/3/foo.c", "**/*.?", "A file when matching against required single-character extension when matching should be ignored.").ignored(), - new CodegenIgnoreProcessorTest("docs/1/2/3/foo.cc", "**/*.?", "A file when matching against required single-character extension when non-matching should be allowed.").allowed() + new CodegenIgnoreProcessorTest("docs/1/Users/UserApi.md", + "docs/**/Users/\n!docs/1/Users/UserApi.md", + "A pattern negating a previous ignore DIRECTORY rule should be ignored.") + .ignored(), + + // Other matches which may not be parsed for correctness, but are free because of + // PathMatcher + new CodegenIgnoreProcessorTest("docs/1/2/3/Some99File.md", "**/*[0-9]*", + "A file when matching against simple regex patterns when matching should be ignored.") + .ignored(), + new CodegenIgnoreProcessorTest( + "docs/1/2/3/SomeFile.md", + "**/*.{java,md}", + "A file when matching against grouped subpatterns for extension when matching (md) should be ignored.") + .ignored(), + new CodegenIgnoreProcessorTest( + "docs/1/2/3/SomeFile.java", + "**/*.{java,md}", + "A file when matching against grouped subpatterns for extension when matching (java) should be ignored.") + .ignored(), + new CodegenIgnoreProcessorTest( + "docs/1/2/3/SomeFile.txt", + "**/*.{java,md}", + "A file when matching against grouped subpatterns for extension when non-matching should be allowed.") + .allowed(), + + new CodegenIgnoreProcessorTest("docs/1/2/3/foo.c", "**/*.?", + "A file when matching against required single-character extension when matching should be ignored.") + .ignored(), + new CodegenIgnoreProcessorTest( + "docs/1/2/3/foo.cc", + "**/*.?", + "A file when matching against required single-character extension when non-matching should be allowed.") + .allowed() }; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/FileRuleTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/FileRuleTest.java index 401bb7031a7..4a8edff8553 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/FileRuleTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/FileRuleTest.java @@ -14,19 +14,16 @@ public void testMatchComplex() throws Exception { final String definition = "path/to/**/complex/*.txt"; final String relativePath = "path/to/some/nested/complex/xyzzy.txt"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "path"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.TEXT, "to"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.MATCH_ALL), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.TEXT, "complex"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".txt") - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.ROOTED_MARKER), new Part( + IgnoreLineParser.Token.TEXT, "path"), new Part( + IgnoreLineParser.Token.PATH_DELIM), new Part(IgnoreLineParser.Token.TEXT, + "to"), new Part(IgnoreLineParser.Token.PATH_DELIM), new Part( + IgnoreLineParser.Token.MATCH_ALL), new Part( + IgnoreLineParser.Token.PATH_DELIM), new Part(IgnoreLineParser.Token.TEXT, + "complex"), new Part(IgnoreLineParser.Token.PATH_DELIM), new Part( + IgnoreLineParser.Token.MATCH_ANY), new Part(IgnoreLineParser.Token.TEXT, + ".txt")); Rule rule = new FileRule(syntax, definition); Boolean actual = null; @@ -44,18 +41,15 @@ public void testNonMatchComplex() throws Exception { final String definition = "path/to/**/complex/*.txt"; final String relativePath = "path/to/some/nested/invalid/xyzzy.txt"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "path"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.TEXT, "to"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.MATCH_ALL), - new Part(IgnoreLineParser.Token.TEXT, "complex"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".txt") - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.ROOTED_MARKER), new Part( + IgnoreLineParser.Token.TEXT, "path"), new Part( + IgnoreLineParser.Token.PATH_DELIM), new Part(IgnoreLineParser.Token.TEXT, + "to"), new Part(IgnoreLineParser.Token.PATH_DELIM), new Part( + IgnoreLineParser.Token.MATCH_ALL), new Part(IgnoreLineParser.Token.TEXT, + "complex"), new Part(IgnoreLineParser.Token.PATH_DELIM), new Part( + IgnoreLineParser.Token.MATCH_ANY), new Part(IgnoreLineParser.Token.TEXT, + ".txt")); Rule rule = new FileRule(syntax, definition); Boolean actual = null; @@ -74,12 +68,11 @@ public void testGlobbingRecursive() throws Exception { final String relativePath = "path/to/some/nested/location/xyzzy.txt"; // Act - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.MATCH_ALL), - new Part(IgnoreLineParser.Token.DIRECTORY_MARKER), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".txt") - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.MATCH_ALL), new Part( + IgnoreLineParser.Token.DIRECTORY_MARKER), new Part( + IgnoreLineParser.Token.MATCH_ANY), new Part(IgnoreLineParser.Token.TEXT, + ".txt")); Rule rule = new FileRule(syntax, definition); Boolean actual = rule.matches(relativePath); @@ -95,10 +88,9 @@ public void testGlobbingNotRecursive() throws Exception { final String relativePath = "path/to/some/nested/location/xyzzy.txt"; // Act - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".txt") - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.MATCH_ANY), new Part( + IgnoreLineParser.Token.TEXT, ".txt")); Rule rule = new FileRule(syntax, definition); Boolean actual = rule.matches(relativePath); @@ -106,4 +98,4 @@ public void testGlobbingNotRecursive() throws Exception { // Assert assertFalse(actual); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/IgnoreLineParserTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/IgnoreLineParserTest.java index 17a96932d72..016c88ac2fd 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/IgnoreLineParserTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/IgnoreLineParserTest.java @@ -9,7 +9,8 @@ import static org.testng.Assert.*; public class IgnoreLineParserTest { - private IgnoreLineParser.Token verifyInputToSingleToken(final String input, IgnoreLineParser.Token token) throws ParserException { + private IgnoreLineParser.Token verifyInputToSingleToken(final String input, + IgnoreLineParser.Token token) throws ParserException { // Act List result = IgnoreLineParser.parse(input); @@ -33,7 +34,7 @@ public void parseMatchAny() throws Exception { } @Test(expectedExceptions = ParserException.class, - expectedExceptionsMessageRegExp = "Negation with no negated pattern\\.") + expectedExceptionsMessageRegExp = "Negation with no negated pattern\\.") public void parseNegate() throws Exception { verifyInputToSingleToken("!", IgnoreLineParser.Token.NEGATE); @@ -54,7 +55,7 @@ public void parseComment() throws Exception { assertEquals(result.size(), 1); actual = result.get(0); assertEquals(actual.getToken(), IgnoreLineParser.Token.COMMENT); - assertEquals(actual.getValue(), input); + assertEquals(actual.getValue(), input); } @Test @@ -155,4 +156,4 @@ public void parseTripleStarPattern() throws Exception { // Assert fail("Expected pattern containing '***' to throw a ParserException."); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/RootedFileRuleTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/RootedFileRuleTest.java index 471422fcc03..5aa06f36c3a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/RootedFileRuleTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/RootedFileRuleTest.java @@ -13,10 +13,9 @@ public void testMatchFilenameOnly() throws Exception { // Arrange final String definition = "/foo"; final String relativePath = "foo"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo") - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.ROOTED_MARKER), new Part( + IgnoreLineParser.Token.TEXT, "foo")); Rule rule = new RootedFileRule(syntax, definition); Boolean actual = null; @@ -32,10 +31,9 @@ public void testNonMatchFilenameOnly() throws Exception { // Arrange final String definition = "/foo"; final String relativePath = "bar"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo") - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.ROOTED_MARKER), new Part( + IgnoreLineParser.Token.TEXT, "foo")); Rule rule = new RootedFileRule(syntax, definition); Boolean actual = null; @@ -51,10 +49,9 @@ public void testMatchFilenameAndExtension() throws Exception { // Arrange final String definition = "/foo.txt"; final String relativePath = "foo.txt"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo.txt") - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.ROOTED_MARKER), new Part( + IgnoreLineParser.Token.TEXT, "foo.txt")); Rule rule = new RootedFileRule(syntax, definition); Boolean actual = null; @@ -70,10 +67,9 @@ public void testNonMatchFilenameAndExtension() throws Exception { // Arrange final String definition = "/foo.txt"; final String relativePath = "bar.baz"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo.txt") - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.ROOTED_MARKER), new Part( + IgnoreLineParser.Token.TEXT, "foo.txt")); Rule rule = new RootedFileRule(syntax, definition); Boolean actual = null; @@ -90,11 +86,10 @@ public void testMatchFilenameWithGlob() throws Exception { final String definition = "/foo*"; final String relativePath = "foobarbaz"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo"), - new Part(IgnoreLineParser.Token.MATCH_ANY) - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.ROOTED_MARKER), new Part( + IgnoreLineParser.Token.TEXT, "foo"), new Part( + IgnoreLineParser.Token.MATCH_ANY)); Rule rule = new RootedFileRule(syntax, definition); Boolean actual = null; @@ -111,11 +106,10 @@ public void testNonMatchFilenameWithGlob() throws Exception { // Arrange final String definition = "/foo*"; final String relativePath = "boobarbaz"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo"), - new Part(IgnoreLineParser.Token.MATCH_ANY) - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.ROOTED_MARKER), new Part( + IgnoreLineParser.Token.TEXT, "foo"), new Part( + IgnoreLineParser.Token.MATCH_ANY)); Rule rule = new RootedFileRule(syntax, definition); Boolean actual = null; @@ -133,12 +127,11 @@ public void testMatchFilenameAndExtensionWithFilenameGlob() throws Exception { final String definition = "/foo*.txt"; final String relativePath = "foobarbaz.txt"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo"), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".txt") - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.ROOTED_MARKER), new Part( + IgnoreLineParser.Token.TEXT, "foo"), new Part( + IgnoreLineParser.Token.MATCH_ANY), new Part(IgnoreLineParser.Token.TEXT, + ".txt")); Rule rule = new RootedFileRule(syntax, definition); Boolean actual = null; @@ -156,12 +149,11 @@ public void testNonMatchFilenameAndExtensionWithFilenameGlob() throws Exception final String definition = "/foo*qux.txt"; final String relativePath = "foobarbaz.txt"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo"), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, "qux.txt") - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.ROOTED_MARKER), new Part( + IgnoreLineParser.Token.TEXT, "foo"), new Part( + IgnoreLineParser.Token.MATCH_ANY), new Part(IgnoreLineParser.Token.TEXT, + "qux.txt")); Rule rule = new RootedFileRule(syntax, definition); Boolean actual = null; @@ -178,11 +170,10 @@ public void testMatchFilenameAndExtensionWithExtensionGlob() throws Exception { // Arrange final String definition = "/foo.*"; final String relativePath = "foo.bak"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo."), - new Part(IgnoreLineParser.Token.MATCH_ANY) - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.ROOTED_MARKER), new Part( + IgnoreLineParser.Token.TEXT, "foo."), new Part( + IgnoreLineParser.Token.MATCH_ANY)); Rule rule = new RootedFileRule(syntax, definition); Boolean actual = null; @@ -198,12 +189,11 @@ public void testMatchFilenameAndExtensionWithMultiplePeriods() throws Exception // Arrange final String definition = "/foo*.xyzzy.txt"; final String relativePath = "foo.bar.baz.xyzzy.txt"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo"), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".xyzzy.txt") - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.ROOTED_MARKER), new Part( + IgnoreLineParser.Token.TEXT, "foo"), new Part( + IgnoreLineParser.Token.MATCH_ANY), new Part(IgnoreLineParser.Token.TEXT, + ".xyzzy.txt")); Rule rule = new RootedFileRule(syntax, definition); Boolean actual = null; @@ -219,12 +209,11 @@ public void testNonMatchFilenameAndExtensionWithMultiplePeriods() throws Excepti // Arrange final String definition = "/foo*.xyzzy.txt"; final String relativePath = "foo.bar.baz.qux.txt"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo"), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".xyzzy.txt") - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.ROOTED_MARKER), new Part( + IgnoreLineParser.Token.TEXT, "foo"), new Part( + IgnoreLineParser.Token.MATCH_ANY), new Part(IgnoreLineParser.Token.TEXT, + ".xyzzy.txt")); Rule rule = new RootedFileRule(syntax, definition); Boolean actual = null; @@ -240,12 +229,11 @@ public void testMatchWithoutLeadingForwardSlash() throws Exception { // Arrange final String definition = "foo*.xyzzy.txt"; final String relativePath = "foo.bar.baz.xyzzy.txt"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "foo"), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".xyzzy.txt") - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.ROOTED_MARKER), new Part( + IgnoreLineParser.Token.TEXT, "foo"), new Part( + IgnoreLineParser.Token.MATCH_ANY), new Part(IgnoreLineParser.Token.TEXT, + ".xyzzy.txt")); Rule rule = new RootedFileRule(syntax, definition); Boolean actual = null; @@ -261,18 +249,15 @@ public void testMatchesOnlyRooted() throws Exception { // Arrange final String definition = "/path/to/some/foo*.xyzzy.txt"; final String relativePath = "foo.bar.baz.xyzzy.txt"; - final List syntax = Arrays.asList( - new Part(IgnoreLineParser.Token.ROOTED_MARKER), - new Part(IgnoreLineParser.Token.TEXT, "path"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.TEXT, "to"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.TEXT, "some"), - new Part(IgnoreLineParser.Token.PATH_DELIM), - new Part(IgnoreLineParser.Token.TEXT, "oo"), - new Part(IgnoreLineParser.Token.MATCH_ANY), - new Part(IgnoreLineParser.Token.TEXT, ".xyzzy.txt") - ); + final List syntax = + Arrays.asList(new Part(IgnoreLineParser.Token.ROOTED_MARKER), new Part( + IgnoreLineParser.Token.TEXT, "path"), new Part( + IgnoreLineParser.Token.PATH_DELIM), new Part(IgnoreLineParser.Token.TEXT, + "to"), new Part(IgnoreLineParser.Token.PATH_DELIM), new Part( + IgnoreLineParser.Token.TEXT, "some"), new Part( + IgnoreLineParser.Token.PATH_DELIM), new Part(IgnoreLineParser.Token.TEXT, + "oo"), new Part(IgnoreLineParser.Token.MATCH_ANY), new Part( + IgnoreLineParser.Token.TEXT, ".xyzzy.txt")); Rule rule = new RootedFileRule(syntax, definition); Boolean actual = null; @@ -282,4 +267,4 @@ public void testMatchesOnlyRooted() throws Exception { // Assert assertFalse(actual); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java index 4d020f0591b..02251671309 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java @@ -25,31 +25,41 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(JavaInflectorServerOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(JavaInflectorServerOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JavaInflectorServerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(JavaInflectorServerOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(JavaInflectorServerOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(JavaInflectorServerOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(JavaInflectorServerOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setSourceFolder(JavaInflectorServerOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(JavaInflectorServerOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen.setSerializableModel(Boolean.valueOf(JavaInflectorServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaInflectorServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); - times = 1; - clientCodegen.setSerializeBigDecimalAsString(true); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen + .setModelPackage(JavaInflectorServerOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(JavaInflectorServerOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(JavaInflectorServerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen + .setInvokerPackage(JavaInflectorServerOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(JavaInflectorServerOptionsProvider.GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(JavaInflectorServerOptionsProvider.ARTIFACT_ID_VALUE); + times = 1; + clientCodegen + .setArtifactVersion(JavaInflectorServerOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen + .setSourceFolder(JavaInflectorServerOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen + .setLocalVariablePrefix(JavaInflectorServerOptionsProvider.LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean + .valueOf(JavaInflectorServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + times = 1; + clientCodegen.setFullJavaUtil(Boolean + .valueOf(JavaInflectorServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); + times = 1; + clientCodegen.setSerializeBigDecimalAsString(true); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java index a4a13ecbcbc..8f797f05126 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java @@ -31,57 +31,68 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(JavaClientOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(JavaClientOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JavaClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(JavaClientOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(JavaClientOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(JavaClientOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(JavaClientOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setArtifactUrl(JavaClientOptionsProvider.ARTIFACT_URL_VALUE); - times = 1; - clientCodegen.setArtifactDescription(JavaClientOptionsProvider.ARTIFACT_DESCRIPTION_VALUE); - times = 1; - clientCodegen.setScmConnection(JavaClientOptionsProvider.SCM_CONNECTION_VALUE); - times = 1; - clientCodegen.setScmDeveloperConnection(JavaClientOptionsProvider.SCM_DEVELOPER_CONNECTION_VALUE); - times = 1; - clientCodegen.setScmUrl(JavaClientOptionsProvider.SCM_URL_VALUE); - times = 1; - clientCodegen.setDeveloperName(JavaClientOptionsProvider.DEVELOPER_NAME_VALUE); - times = 1; - clientCodegen.setDeveloperEmail(JavaClientOptionsProvider.DEVELOPER_EMAIL_VALUE); - times = 1; - clientCodegen.setDeveloperOrganization(JavaClientOptionsProvider.DEVELOPER_ORGANIZATION_VALUE); - times = 1; - clientCodegen.setDeveloperOrganizationUrl(JavaClientOptionsProvider.DEVELOPER_ORGANIZATION_URL_VALUE); - times = 1; - clientCodegen.setLicenseName(JavaClientOptionsProvider.LICENSE_NAME_VALUE); - times = 1; - clientCodegen.setLicenseUrl(JavaClientOptionsProvider.LICENSE_URL_VALUE); - times = 1; - clientCodegen.setSourceFolder(JavaClientOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(JavaClientOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen.setSerializableModel(Boolean.valueOf(JavaClientOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - clientCodegen.setLibrary(JavaClientOptionsProvider.DEFAULT_LIBRARY_VALUE); - times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaClientOptionsProvider.FULL_JAVA_UTIL_VALUE)); - times = 1; - clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaClientOptionsProvider.USE_BEANVALIDATION)); - times = 1; - clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaClientOptionsProvider.PERFORM_BEANVALIDATION)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setModelPackage(JavaClientOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(JavaClientOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(JavaClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setInvokerPackage(JavaClientOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(JavaClientOptionsProvider.GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(JavaClientOptionsProvider.ARTIFACT_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(JavaClientOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen.setArtifactUrl(JavaClientOptionsProvider.ARTIFACT_URL_VALUE); + times = 1; + clientCodegen + .setArtifactDescription(JavaClientOptionsProvider.ARTIFACT_DESCRIPTION_VALUE); + times = 1; + clientCodegen.setScmConnection(JavaClientOptionsProvider.SCM_CONNECTION_VALUE); + times = 1; + clientCodegen + .setScmDeveloperConnection(JavaClientOptionsProvider.SCM_DEVELOPER_CONNECTION_VALUE); + times = 1; + clientCodegen.setScmUrl(JavaClientOptionsProvider.SCM_URL_VALUE); + times = 1; + clientCodegen.setDeveloperName(JavaClientOptionsProvider.DEVELOPER_NAME_VALUE); + times = 1; + clientCodegen.setDeveloperEmail(JavaClientOptionsProvider.DEVELOPER_EMAIL_VALUE); + times = 1; + clientCodegen + .setDeveloperOrganization(JavaClientOptionsProvider.DEVELOPER_ORGANIZATION_VALUE); + times = 1; + clientCodegen + .setDeveloperOrganizationUrl(JavaClientOptionsProvider.DEVELOPER_ORGANIZATION_URL_VALUE); + times = 1; + clientCodegen.setLicenseName(JavaClientOptionsProvider.LICENSE_NAME_VALUE); + times = 1; + clientCodegen.setLicenseUrl(JavaClientOptionsProvider.LICENSE_URL_VALUE); + times = 1; + clientCodegen.setSourceFolder(JavaClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setLocalVariablePrefix(JavaClientOptionsProvider.LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean + .valueOf(JavaClientOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + times = 1; + clientCodegen.setLibrary(JavaClientOptionsProvider.DEFAULT_LIBRARY_VALUE); + times = 1; + clientCodegen.setFullJavaUtil(Boolean + .valueOf(JavaClientOptionsProvider.FULL_JAVA_UTIL_VALUE)); + times = 1; + clientCodegen.setUseBeanValidation(Boolean + .valueOf(JavaClientOptionsProvider.USE_BEANVALIDATION)); + times = 1; + clientCodegen.setUseBeanValidation(Boolean + .valueOf(JavaClientOptionsProvider.PERFORM_BEANVALIDATION)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java index a4cb27db756..64ed490ba39 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java @@ -22,8 +22,9 @@ public class JavaInheritanceTest { @SuppressWarnings("static-method") @Test(description = "convert a composed model with parent") public void javaInheritanceTest() { - final Model model = new ComposedModel().parent(new RefModel("Base")) - .child(new ModelImpl().additionalProperties(new StringProperty())); + final Model model = + new ComposedModel().parent(new RefModel("Base")).child( + new ModelImpl().additionalProperties(new StringProperty())); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -40,9 +41,9 @@ public void javaInheritanceWithDiscriminatorTest() { ModelImpl base = new ModelImpl(); base.setDiscriminator("disc"); - final Model model = new ComposedModel() - .interfaces(Arrays.asList(new RefModel("Base"))) - .child(new ModelImpl().additionalProperties(new StringProperty())); + final Model model = + new ComposedModel().interfaces(Arrays.asList(new RefModel("Base"))).child( + new ModelImpl().additionalProperties(new StringProperty())); final Map allDefinitions = new HashMap(); allDefinitions.put("Base", base); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelEnumTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelEnumTest.java index 5ac5f788590..4c13cb445fa 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelEnumTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelEnumTest.java @@ -67,10 +67,9 @@ public void overrideEnumTest() { subModel.setProperties(subProperties); subModel.name("subModel"); - final ComposedModel model = new ComposedModel() - .parent(new RefModel(parentModel.getName())) - .child(subModel) - .interfaces(new ArrayList()); + final ComposedModel model = + new ComposedModel().parent(new RefModel(parentModel.getName())).child(subModel) + .interfaces(new ArrayList()); final DefaultCodegen codegen = new JavaClientCodegen(); final Map allModels = new HashMap(); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java index 7dfd05faca7..df6a59c5ebd 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java @@ -30,14 +30,11 @@ public class JavaModelTest { @Test(description = "convert a simple java model") public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty() - .example("Tony")) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name"); + final Model model = + new ModelImpl().description("a sample model").property("id", new LongProperty()) + .property("name", new StringProperty().example("Tony")) + .property("createdAt", new DateTimeProperty()).required("id") + .required("name"); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -88,12 +85,10 @@ public void simpleModelTest() { @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 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 JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -117,11 +112,12 @@ public void listPropertyTest() { @Test(description = "convert a model with a map property") public void mapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); + final Model model = + new ModelImpl() + .description("a sample model") + .property("translations", + new MapProperty().additionalProperties(new StringProperty())) + .required("id"); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -145,11 +141,13 @@ public void mapPropertyTest() { @Test(description = "convert a model with a map with complex list property") public void mapWithListPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("translations", - new MapProperty().additionalProperties(new ArrayProperty().items(new RefProperty("Pet")))) - .required("id"); + final Model model = + new ModelImpl() + .description("a sample model") + .property( + "translations", + new MapProperty().additionalProperties(new ArrayProperty() + .items(new RefProperty("Pet")))).required("id"); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -173,8 +171,12 @@ public void mapWithListPropertyTest() { @Test(description = "convert a model with a 2D list property") public void list2DPropertyTest() { - final Model model = new ModelImpl().name("sample").property("list2D", new ArrayProperty().items( - new ArrayProperty().items(new RefProperty("Pet")))); + final Model model = + new ModelImpl().name("sample") + .property( + "list2D", + new ArrayProperty().items(new ArrayProperty() + .items(new RefProperty("Pet")))); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -195,8 +197,9 @@ public void list2DPropertyTest() { @Test(description = "convert a model with complex properties") public void complexPropertiesTest() { - final Model model = new ModelImpl().description("a sample model") - .property("children", new RefProperty("#/definitions/Children")); + final Model model = + new ModelImpl().description("a sample model").property("children", + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -219,9 +222,9 @@ public void complexPropertiesTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new ArrayProperty().items(new RefProperty("#/definitions/Children"))); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -246,9 +249,11 @@ public void complexListPropertyTest() { @Test(description = "convert a model with complex map property") public void complexMapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new MapProperty().additionalProperties(new RefProperty("#/definitions/Children"))); + final Model model = + new ModelImpl().description("a sample model").property( + "children", + new MapProperty().additionalProperties(new RefProperty( + "#/definitions/Children"))); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -256,7 +261,8 @@ public void complexMapPropertyTest() { Assert.assertEquals(cm.classname, "Sample"); Assert.assertEquals(cm.description, "a sample model"); Assert.assertEquals(cm.vars.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Map", "List", "Children")).size(), 3); + Assert.assertEquals( + Sets.intersection(cm.imports, Sets.newHashSet("Map", "List", "Children")).size(), 3); final CodegenProperty property = cm.vars.get(0); Assert.assertEquals(property.baseName, "children"); @@ -276,9 +282,9 @@ public void complexMapPropertyTest() { @Test(description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Model model = + new ArrayModel().description("an array model").items( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -288,14 +294,16 @@ public void arrayModelTest() { Assert.assertEquals(cm.vars.size(), 0); Assert.assertEquals(cm.parent, "ArrayList"); Assert.assertEquals(cm.imports.size(), 4); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("ApiModel", "List", "ArrayList", "Children")).size(), 4); + Assert.assertEquals( + Sets.intersection(cm.imports, + Sets.newHashSet("ApiModel", "List", "ArrayList", "Children")).size(), 4); } @Test(description = "convert an map model") public void mapModelTest() { - final Model model = new ModelImpl() - .description("an map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + final Model model = + new ModelImpl().description("an map model").additionalProperties( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -305,15 +313,16 @@ public void mapModelTest() { Assert.assertEquals(cm.vars.size(), 0); Assert.assertEquals(cm.parent, "HashMap"); Assert.assertEquals(cm.imports.size(), 4); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("ApiModel", "Map", "HashMap", "Children")).size(), 4); + Assert.assertEquals( + Sets.intersection(cm.imports, + Sets.newHashSet("ApiModel", "Map", "HashMap", "Children")).size(), 4); } @Test(description = "convert a model with upper-case property names") public void upperCaseNamesTest() { - final Model model = new ModelImpl() - .description("a model with upper-case property names") - .property("NAME", new StringProperty()) - .required("NAME"); + final Model model = + new ModelImpl().description("a model with upper-case property names") + .property("NAME", new StringProperty()).required("NAME"); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -336,10 +345,9 @@ public void upperCaseNamesTest() { @Test(description = "convert a model with a 2nd char upper-case property names") public void secondCharUpperCaseNamesTest() { - final Model model = new ModelImpl() - .description("a model with a 2nd char upper-case property names") - .property("pId", new StringProperty()) - .required("pId"); + final Model model = + new ModelImpl().description("a model with a 2nd char upper-case property names") + .property("pId", new StringProperty()).required("pId"); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -362,10 +370,11 @@ public void secondCharUpperCaseNamesTest() { @Test(description = "convert a model starting with two upper-case letter property names") public void firstTwoUpperCaseLetterNamesTest() { - final Model model = new ModelImpl() - .description("a model with a property name starting with two upper-case letters") - .property("ATTName", new StringProperty()) - .required("ATTName"); + final Model model = + new ModelImpl() + .description( + "a model with a property name starting with two upper-case letters") + .property("ATTName", new StringProperty()).required("ATTName"); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -388,9 +397,9 @@ public void firstTwoUpperCaseLetterNamesTest() { @Test(description = "convert hyphens per issue 503") public void hyphensTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("created-at", new DateTimeProperty()); + final Model model = + new ModelImpl().description("a sample model").property("created-at", + new DateTimeProperty()); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -403,9 +412,9 @@ public void hyphensTest() { @Test(description = "convert query[password] to queryPassword") public void squareBracketsTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("query[password]", new StringProperty()); + final Model model = + new ModelImpl().description("a sample model").property("query[password]", + new StringProperty()); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -418,9 +427,9 @@ public void squareBracketsTest() { @Test(description = "properly escape names per 567") public void escapeNamesTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("created-at", new DateTimeProperty()); + final Model model = + new ModelImpl().description("a sample model").property("created-at", + new DateTimeProperty()); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("with.dots", model); @@ -429,9 +438,9 @@ public void escapeNamesTest() { @Test(description = "convert a model with binary data") public void binaryDataTest() { - final Model model = new ModelImpl() - .description("model with binary") - .property("inputBinaryData", new ByteArrayProperty()); + final Model model = + new ModelImpl().description("model with binary").property("inputBinaryData", + new ByteArrayProperty()); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -450,9 +459,9 @@ public void binaryDataTest() { @Test(description = "translate an invalid param name") public void invalidParamNameTest() { - final Model model = new ModelImpl() - .description("a model with a 2nd char upper-case property names") - .property("_", new StringProperty()); + final Model model = + new ModelImpl().description("a model with a 2nd char upper-case property names") + .property("_", new StringProperty()); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -474,10 +483,8 @@ public void invalidParamNameTest() { @Test(description = "convert a parameter") public void convertParameterTest() { - final QueryParameter parameter = new QueryParameter() - .property(new IntegerProperty()) - .name("limit") - .required(true); + final QueryParameter parameter = + new QueryParameter().property(new IntegerProperty()).name("limit").required(true); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenParameter cm = codegen.fromParameter(parameter, null); @@ -486,31 +493,35 @@ public void convertParameterTest() { @Test(description = "types used by inner properties should be imported") public void mapWithAnListOfBigDecimalTest() { - final CodegenModel cm1 = new JavaClientCodegen().fromModel("sample", new ModelImpl() - .description("model with Map>") - .property("map", new MapProperty().additionalProperties(new ArrayProperty(new DecimalProperty())))); + final CodegenModel cm1 = + new JavaClientCodegen().fromModel( + "sample", + new ModelImpl().description("model with Map>") + .property( + "map", + new MapProperty().additionalProperties(new ArrayProperty( + new DecimalProperty())))); Assert.assertEquals(cm1.vars.get(0).datatype, "Map>"); Assert.assertTrue(cm1.imports.contains("BigDecimal")); - final CodegenModel cm2 = new JavaClientCodegen().fromModel("sample", new ModelImpl() - .description("model with Map>>") - .property("map", new MapProperty().additionalProperties(new MapProperty().additionalProperties(new ArrayProperty(new DecimalProperty()))))); + final CodegenModel cm2 = + new JavaClientCodegen().fromModel( + "sample", + new ModelImpl().description( + "model with Map>>").property( + "map", + new MapProperty().additionalProperties(new MapProperty() + .additionalProperties(new ArrayProperty( + new DecimalProperty()))))); Assert.assertEquals(cm2.vars.get(0).datatype, "Map>>"); Assert.assertTrue(cm2.imports.contains("BigDecimal")); } @DataProvider(name = "modelNames") public static Object[][] primeNumbers() { - return new Object[][] { - {"sample", "Sample"}, - {"sample_name", "SampleName"}, - {"sample__name", "SampleName"}, - {"/sample", "Sample"}, - {"\\sample", "Sample"}, - {"sample.name", "SampleName"}, - {"_sample", "Sample"}, - {"Sample", "Sample"}, - }; + return new Object[][] { {"sample", "Sample"}, {"sample_name", "SampleName"}, + {"sample__name", "SampleName"}, {"/sample", "Sample"}, {"\\sample", "Sample"}, + {"sample.name", "SampleName"}, {"_sample", "Sample"}, {"Sample", "Sample"},}; } @Test(dataProvider = "modelNames", description = "avoid inner class") @@ -525,18 +536,16 @@ public void modelNameTest(String name, String expectedName) { @DataProvider(name = "classProperties") public static Object[][] classProperties() { - return new Object[][] { - {"class", "getPropertyClass", "setPropertyClass", "propertyClass"}, + return new Object[][] { {"class", "getPropertyClass", "setPropertyClass", "propertyClass"}, {"_class", "getPropertyClass", "setPropertyClass", "propertyClass"}, - {"__class", "getPropertyClass", "setPropertyClass", "propertyClass"} - }; + {"__class", "getPropertyClass", "setPropertyClass", "propertyClass"}}; } @Test(dataProvider = "classProperties", description = "handle 'class' properties") public void classPropertyTest(String baseName, String getter, String setter, String name) { - final Model model = new ModelImpl() - .description("a sample model") - .property(baseName, new StringProperty()); + final Model model = + new ModelImpl().description("a sample model").property(baseName, + new StringProperty()); final DefaultCodegen codegen = new JavaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java index aa81a3cf81e..8b4383775d8 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java @@ -33,31 +33,39 @@ private static String loadClassResource(Class cls, String name) throws IOExce @DataProvider(name = PROVIDER_NAME) private static Object[][] resource() { final CodegenParameter param1 = new CodegenParameter(); - final CodegenParameter param2 = new CodegenParameter() {{ - allowableValues = ImmutableMap.of("values", ImmutableList.of("item1", "item2", "item3")); - }}; - final CodegenParameter param3 = new CodegenParameter() {{ - allowableValues = ImmutableMap.of("min", 1, "max", 10); - }}; - final CodegenParameter param4 = new CodegenParameter() {{ - allowableValues = ImmutableMap.of("min", 1); - }}; - final CodegenParameter param5 = new CodegenParameter() {{ - allowableValues = ImmutableMap.of("max", 10); - }}; + final CodegenParameter param2 = new CodegenParameter() { + { + allowableValues = + ImmutableMap.of("values", + ImmutableList.of("item1", "item2", "item3")); + } + }; + final CodegenParameter param3 = new CodegenParameter() { + { + allowableValues = ImmutableMap.of("min", 1, "max", 10); + } + }; + final CodegenParameter param4 = new CodegenParameter() { + { + allowableValues = ImmutableMap.of("min", 1); + } + }; + final CodegenParameter param5 = new CodegenParameter() { + { + allowableValues = ImmutableMap.of("max", 10); + } + }; - return new Object[][]{ - {param1, ""}, - {param2, "allowableValues=\"item1, item2, item3\""}, + return new Object[][] { {param1, ""}, {param2, "allowableValues=\"item1, item2, item3\""}, {param3, "allowableValues=\"range=[1, 10]\""}, {param4, "allowableValues=\"range=[1, infinity]\""}, - {param5, "allowableValues=\"range=[-infinity, 10]\""}, - }; + {param5, "allowableValues=\"range=[-infinity, 10]\""},}; } @Test(dataProvider = PROVIDER_NAME) public void annotationsTest(CodegenParameter parameter, String expected) throws IOException { - final Template template = Mustache.compiler().compile(loadClassResource(this.getClass(), TEMPLATE_FILE)); + final Template template = + Mustache.compiler().compile(loadClassResource(this.getClass(), TEMPLATE_FILE)); Assert.assertEquals(template.execute(parameter), expected); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptClientOptionsTest.java index eda6602607d..49dfcebb5cf 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptClientOptionsTest.java @@ -29,45 +29,54 @@ protected CodegenConfig getCodegenConfig() { @Override protected void setExpectations() { // Commented generic options not yet supported by JavaScript codegen. - new Expectations(clientCodegen) {{ - clientCodegen.setInvokerPackage(JavaScriptOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setModelPackage(JavaScriptOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(JavaScriptOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JavaScriptOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; -// clientCodegen.setInvokerPackage(JavaScriptOptionsProvider.INVOKER_PACKAGE_VALUE); -// times = 1; -// clientCodegen.setGroupId(JavaScriptOptionsProvider.GROUP_ID_VALUE); -// times = 1; -// clientCodegen.setArtifactId(JavaScriptOptionsProvider.ARTIFACT_ID_VALUE); -// times = 1; -// clientCodegen.setArtifactVersion(JavaScriptOptionsProvider.ARTIFACT_VERSION_VALUE); -// times = 1; - clientCodegen.setSourceFolder(JavaScriptOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(JavaScriptOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen.setProjectName(JavaScriptOptionsProvider.PROJECT_NAME_VALUE); - times = 1; - clientCodegen.setModuleName(JavaScriptOptionsProvider.MODULE_NAME_VALUE); - times = 1; - clientCodegen.setProjectDescription(JavaScriptOptionsProvider.PROJECT_DESCRIPTION_VALUE); - times = 1; - clientCodegen.setProjectVersion(JavaScriptOptionsProvider.PROJECT_VERSION_VALUE); - times = 1; - clientCodegen.setProjectLicenseName(JavaScriptOptionsProvider.PROJECT_LICENSE_NAME_VALUE); - times = 1; - clientCodegen.setUsePromises(Boolean.valueOf(JavaScriptOptionsProvider.USE_PROMISES_VALUE)); - times = 1; - clientCodegen.setUseInheritance(Boolean.valueOf(JavaScriptOptionsProvider.USE_INHERITANCE_VALUE)); - times = 1; - clientCodegen.setEmitModelMethods(Boolean.valueOf(JavaScriptOptionsProvider.EMIT_MODEL_METHODS_VALUE)); - times = 1; - clientCodegen.setEmitJSDoc(Boolean.valueOf(JavaScriptOptionsProvider.EMIT_JS_DOC_VALUE)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setInvokerPackage(JavaScriptOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setModelPackage(JavaScriptOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(JavaScriptOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(JavaScriptOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + // clientCodegen.setInvokerPackage(JavaScriptOptionsProvider.INVOKER_PACKAGE_VALUE); + // times = 1; + // clientCodegen.setGroupId(JavaScriptOptionsProvider.GROUP_ID_VALUE); + // times = 1; + // clientCodegen.setArtifactId(JavaScriptOptionsProvider.ARTIFACT_ID_VALUE); + // times = 1; + // clientCodegen.setArtifactVersion(JavaScriptOptionsProvider.ARTIFACT_VERSION_VALUE); + // times = 1; + clientCodegen.setSourceFolder(JavaScriptOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setLocalVariablePrefix(JavaScriptOptionsProvider.LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setProjectName(JavaScriptOptionsProvider.PROJECT_NAME_VALUE); + times = 1; + clientCodegen.setModuleName(JavaScriptOptionsProvider.MODULE_NAME_VALUE); + times = 1; + clientCodegen + .setProjectDescription(JavaScriptOptionsProvider.PROJECT_DESCRIPTION_VALUE); + times = 1; + clientCodegen.setProjectVersion(JavaScriptOptionsProvider.PROJECT_VERSION_VALUE); + times = 1; + clientCodegen + .setProjectLicenseName(JavaScriptOptionsProvider.PROJECT_LICENSE_NAME_VALUE); + times = 1; + clientCodegen.setUsePromises(Boolean + .valueOf(JavaScriptOptionsProvider.USE_PROMISES_VALUE)); + times = 1; + clientCodegen.setUseInheritance(Boolean + .valueOf(JavaScriptOptionsProvider.USE_INHERITANCE_VALUE)); + times = 1; + clientCodegen.setEmitModelMethods(Boolean + .valueOf(JavaScriptOptionsProvider.EMIT_MODEL_METHODS_VALUE)); + times = 1; + clientCodegen.setEmitJSDoc(Boolean + .valueOf(JavaScriptOptionsProvider.EMIT_JS_DOC_VALUE)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptInheritanceTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptInheritanceTest.java index 592a9e2ae58..b0660e0cb33 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptInheritanceTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptInheritanceTest.java @@ -35,9 +35,12 @@ public void javascriptInheritanceTest() { allDefinitions.put("Interface1", intf1); allDefinitions.put("Interface2", intf2); - final Model model = new ComposedModel().parent(new RefModel("Base")) - .interfaces(Arrays.asList(new RefModel("Interface1"), new RefModel("Interface2"))) - .child(child); + final Model model = + new ComposedModel() + .parent(new RefModel("Base")) + .interfaces( + Arrays.asList(new RefModel("Interface1"), + new RefModel("Interface2"))).child(child); final JavascriptClientCodegen codegen = new JavascriptClientCodegen(); codegen.setUseInheritance(true); @@ -76,9 +79,12 @@ public void javascriptNoInheritanceTest() { allDefinitions.put("Interface1", intf1); allDefinitions.put("Interface2", intf2); - final Model model = new ComposedModel().parent(new RefModel("Base")) - .interfaces(Arrays.asList(new RefModel("Interface1"), new RefModel("Interface2"))) - .child(child); + final Model model = + new ComposedModel() + .parent(new RefModel("Base")) + .interfaces( + Arrays.asList(new RefModel("Interface1"), + new RefModel("Interface2"))).child(child); final JavascriptClientCodegen codegen = new JavascriptClientCodegen(); codegen.setUseInheritance(false); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java index f8d38149ce1..65812ab47aa 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java @@ -68,10 +68,9 @@ public void overrideEnumTest() { subModel.setProperties(subProperties); subModel.name("subModel"); - final ComposedModel model = new ComposedModel() - .parent(new RefModel(parentModel.getName())) - .child(subModel) - .interfaces(new ArrayList()); + final ComposedModel model = + new ComposedModel().parent(new RefModel(parentModel.getName())).child(subModel) + .interfaces(new ArrayList()); final DefaultCodegen codegen = new JavascriptClientCodegen(); final Map allModels = new HashMap(); @@ -96,11 +95,13 @@ public void overrideEnumTest() { @Test(description = "test enum array model") public void enumArrayModelTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final Swagger model = + new SwaggerParser() + .read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); final DefaultCodegen codegen = new JavascriptClientCodegen(); final Model definition = model.getDefinitions().get("EnumArrays"); - Property property = definition.getProperties().get("array_enum"); + Property property = definition.getProperties().get("array_enum"); CodegenProperty prope = codegen.fromProperty("array_enum", property); codegen.updateCodegenPropertyEnum(prope); Assert.assertEquals(prope.datatypeWithEnum, "[ArrayEnumEnum]"); @@ -108,10 +109,10 @@ public void enumArrayModelTest() { Assert.assertTrue(prope.isEnum); Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList("fish", "crab")); - HashMap fish= new HashMap(); + HashMap fish = new HashMap(); fish.put("name", "fish"); fish.put("value", "\"fish\""); - HashMap crab= new HashMap(); + HashMap crab = new HashMap(); crab.put("name", "crab"); crab.put("value", "\"crab\""); Assert.assertEquals(prope.allowableValues.get("enumVars"), Arrays.asList(fish, crab)); @@ -120,18 +121,21 @@ public void enumArrayModelTest() { Assert.assertEquals(prope.datatypeWithEnum, "[ArrayEnumEnum]"); Assert.assertEquals(prope.enumName, "ArrayEnumEnum"); Assert.assertTrue(prope.items.isEnum); - Assert.assertEquals(prope.items.allowableValues.get("values"), Arrays.asList("fish", "crab")); + Assert.assertEquals(prope.items.allowableValues.get("values"), + Arrays.asList("fish", "crab")); Assert.assertEquals(prope.items.allowableValues.get("enumVars"), Arrays.asList(fish, crab)); } @Test(description = "test enum model for values (numeric, string, etc)") public void enumModelValueTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final Swagger model = + new SwaggerParser() + .read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); final DefaultCodegen codegen = new JavascriptClientCodegen(); final Model definition = model.getDefinitions().get("Enum_Test"); - Property property = definition.getProperties().get("enum_integer"); + Property property = definition.getProperties().get("enum_integer"); CodegenProperty prope = codegen.fromProperty("enum_integer", property); codegen.updateCodegenPropertyEnum(prope); Assert.assertEquals(prope.datatypeWithEnum, "EnumIntegerEnum"); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java index b159918c73c..be8a7d74950 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java @@ -30,14 +30,11 @@ public class JavaScriptModelTest { @Test(description = "convert a simple java model") public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty() - .example("Tony")) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name"); + final Model model = + new ModelImpl().description("a sample model").property("id", new LongProperty()) + .property("name", new StringProperty().example("Tony")) + .property("createdAt", new DateTimeProperty()).required("id") + .required("name"); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -88,12 +85,10 @@ public void simpleModelTest() { @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 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 JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -108,7 +103,8 @@ public void listPropertyTest() { Assert.assertEquals(property.setter, "setUrls"); Assert.assertEquals(property.datatype, "[String]"); Assert.assertEquals(property.name, "urls"); - // FIXME: should an array property have an empty array as its default value? What if the property is required? + // FIXME: should an array property have an empty array as its default value? What if the + // property is required? Assert.assertEquals(property.defaultValue, /*"[]"*/null); Assert.assertEquals(property.baseType, "Array"); Assert.assertEquals(property.containerType, "array"); @@ -118,11 +114,12 @@ public void listPropertyTest() { @Test(description = "convert a model with a map property") public void mapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); + final Model model = + new ModelImpl() + .description("a sample model") + .property("translations", + new MapProperty().additionalProperties(new StringProperty())) + .required("id"); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -137,7 +134,8 @@ public void mapPropertyTest() { Assert.assertEquals(property.setter, "setTranslations"); Assert.assertEquals(property.datatype, "{String: String}"); Assert.assertEquals(property.name, "translations"); - // FIXME: should a map property have an empty object as its default value? What if the property is required? + // FIXME: should a map property have an empty object as its default value? What if the + // property is required? Assert.assertEquals(property.defaultValue, /*"{}"*/null); Assert.assertEquals(property.baseType, "Object"); Assert.assertEquals(property.containerType, "map"); @@ -147,11 +145,13 @@ public void mapPropertyTest() { @Test(description = "convert a model with a map with complex list property") public void mapWithListPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("translations", - new MapProperty().additionalProperties(new ArrayProperty().items(new RefProperty("Pet")))) - .required("id"); + final Model model = + new ModelImpl() + .description("a sample model") + .property( + "translations", + new MapProperty().additionalProperties(new ArrayProperty() + .items(new RefProperty("Pet")))).required("id"); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -166,7 +166,8 @@ public void mapWithListPropertyTest() { Assert.assertEquals(property.setter, "setTranslations"); Assert.assertEquals(property.datatype, "{String: [Pet]}"); Assert.assertEquals(property.name, "translations"); - // FIXME: should a map property have an empty object as its default value? What if the property is required? + // FIXME: should a map property have an empty object as its default value? What if the + // property is required? Assert.assertEquals(property.defaultValue, /*"{}"*/null); Assert.assertEquals(property.baseType, "Object"); Assert.assertEquals(property.containerType, "map"); @@ -176,8 +177,12 @@ public void mapWithListPropertyTest() { @Test(description = "convert a model with a 2D list property") public void list2DPropertyTest() { - final Model model = new ModelImpl().name("sample").property("list2D", new ArrayProperty().items( - new ArrayProperty().items(new RefProperty("Pet")))); + final Model model = + new ModelImpl().name("sample") + .property( + "list2D", + new ArrayProperty().items(new ArrayProperty() + .items(new RefProperty("Pet")))); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -189,7 +194,8 @@ public void list2DPropertyTest() { Assert.assertEquals(property.setter, "setList2D"); Assert.assertEquals(property.datatype, "[[Pet]]"); Assert.assertEquals(property.name, "list2D"); - // FIXME: should an array property have an empty array as its default value? What if the property is required? + // FIXME: should an array property have an empty array as its default value? What if the + // property is required? Assert.assertEquals(property.defaultValue, /*"[]"*/null); Assert.assertEquals(property.baseType, "Array"); Assert.assertEquals(property.containerType, "array"); @@ -199,8 +205,9 @@ public void list2DPropertyTest() { @Test(description = "convert a model with complex properties") public void complexPropertiesTest() { - final Model model = new ModelImpl().description("a sample model") - .property("children", new RefProperty("#/definitions/Children")); + final Model model = + new ModelImpl().description("a sample model").property("children", + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -223,9 +230,9 @@ public void complexPropertiesTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new ArrayProperty().items(new RefProperty("#/definitions/Children"))); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -239,10 +246,11 @@ public void complexListPropertyTest() { Assert.assertEquals(property.complexType, "Children"); Assert.assertEquals(property.getter, "getChildren"); Assert.assertEquals(property.setter, "setChildren"); - // FIXME: what should datatype be for a JavaScript array? -// Assert.assertEquals(property.datatype, "Array"); + // FIXME: what should datatype be for a JavaScript array? + // Assert.assertEquals(property.datatype, "Array"); Assert.assertEquals(property.name, "children"); - // FIXME: should an array property have an empty array as its default value? What if the property is required? + // FIXME: should an array property have an empty array as its default value? What if the + // property is required? Assert.assertEquals(property.defaultValue, /*"[]"*/null); Assert.assertEquals(property.baseType, "Array"); Assert.assertEquals(property.containerType, "array"); @@ -252,9 +260,11 @@ public void complexListPropertyTest() { @Test(description = "convert a model with complex map property") public void complexMapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new MapProperty().additionalProperties(new RefProperty("#/definitions/Children"))); + final Model model = + new ModelImpl().description("a sample model").property( + "children", + new MapProperty().additionalProperties(new RefProperty( + "#/definitions/Children"))); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -272,8 +282,9 @@ public void complexMapPropertyTest() { // TODO: create a functional test to see whether map properties actually work. Assert.assertEquals(property.datatype, /*"Object"*/"{String: Children}"); Assert.assertEquals(property.name, "children"); - // FIXME: should a map property have an empty object as its default value? What if the property is required? - Assert.assertEquals(property.defaultValue, /*"{}"*/ null); + // FIXME: should a map property have an empty object as its default value? What if the + // property is required? + Assert.assertEquals(property.defaultValue, /*"{}"*/null); Assert.assertEquals(property.baseType, "Object"); Assert.assertEquals(property.containerType, "map"); Assert.assertFalse(property.required); @@ -283,9 +294,9 @@ public void complexMapPropertyTest() { @Test(description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Model model = + new ArrayModel().description("an array model").items( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -300,9 +311,9 @@ public void arrayModelTest() { @Test(description = "convert a map model") public void mapModelTest() { - final Model model = new ModelImpl() - .description("an map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + final Model model = + new ModelImpl().description("an map model").additionalProperties( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -317,10 +328,9 @@ public void mapModelTest() { @Test(description = "convert a model with uppercase property names") public void upperCaseNamesTest() { - final Model model = new ModelImpl() - .description("a model with uppercase property names") - .property("NAME", new StringProperty()) - .required("NAME"); + final Model model = + new ModelImpl().description("a model with uppercase property names") + .property("NAME", new StringProperty()).required("NAME"); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -343,10 +353,9 @@ public void upperCaseNamesTest() { @Test(description = "convert a model with a 2nd char uppercase property names") public void secondCharUpperCaseNamesTest() { - final Model model = new ModelImpl() - .description("a model with a 2nd char uppercase property names") - .property("pId", new StringProperty()) - .required("pId"); + final Model model = + new ModelImpl().description("a model with a 2nd char uppercase property names") + .property("pId", new StringProperty()).required("pId"); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -369,9 +378,9 @@ public void secondCharUpperCaseNamesTest() { @Test(description = "convert hyphens per issue 503") public void hyphensTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("created-at", new DateTimeProperty()); + final Model model = + new ModelImpl().description("a sample model").property("created-at", + new DateTimeProperty()); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -384,9 +393,9 @@ public void hyphensTest() { @Test(description = "convert query[password] to queryPassword") public void squareBracketsTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("query[password]", new StringProperty()); + final Model model = + new ModelImpl().description("a sample model").property("query[password]", + new StringProperty()); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -399,9 +408,9 @@ public void squareBracketsTest() { @Test(description = "properly escape names per 567") public void escapeNamesTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("created-at", new DateTimeProperty()); + final Model model = + new ModelImpl().description("a sample model").property("created-at", + new DateTimeProperty()); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("with.dots", model); @@ -410,9 +419,9 @@ public void escapeNamesTest() { @Test(description = "convert a model with binary data") public void binaryDataTest() { - final Model model = new ModelImpl() - .description("model with binary") - .property("inputBinaryData", new ByteArrayProperty()); + final Model model = + new ModelImpl().description("model with binary").property("inputBinaryData", + new ByteArrayProperty()); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -431,9 +440,9 @@ public void binaryDataTest() { @Test(description = "translate an invalid param name") public void invalidParamNameTest() { - final Model model = new ModelImpl() - .description("a model with a 2nd char uppercase property name") - .property("_", new StringProperty()); + final Model model = + new ModelImpl().description("a model with a 2nd char uppercase property name") + .property("_", new StringProperty()); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -455,10 +464,8 @@ public void invalidParamNameTest() { @Test(description = "convert a parameter") public void convertParameterTest() { - final QueryParameter parameter = new QueryParameter() - .property(new IntegerProperty()) - .name("limit") - .required(true); + final QueryParameter parameter = + new QueryParameter().property(new IntegerProperty()).name("limit").required(true); final DefaultCodegen codegen = new JavascriptClientCodegen(); final CodegenParameter cm = codegen.fromParameter(parameter, null); @@ -467,16 +474,9 @@ public void convertParameterTest() { @DataProvider(name = "modelNames") public static Object[][] primeNumbers() { - return new Object[][] { - {"sample", "Sample"}, - {"sample_name", "SampleName"}, - {"sample__name", "SampleName"}, - {"/sample", "Sample"}, - {"\\sample", "Sample"}, - {"sample.name", "SampleName"}, - {"_sample", "Sample"}, - {"Sample", "Sample"}, - }; + return new Object[][] { {"sample", "Sample"}, {"sample_name", "SampleName"}, + {"sample__name", "SampleName"}, {"/sample", "Sample"}, {"\\sample", "Sample"}, + {"sample.name", "SampleName"}, {"_sample", "Sample"}, {"Sample", "Sample"},}; } @Test(dataProvider = "modelNames", description = "avoid inner class") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyServerOptionsTest.java index d76ee89416f..2aa35087239 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyServerOptionsTest.java @@ -30,37 +30,45 @@ protected CodegenConfig getCodegenConfig() { protected void setExpectations() { new Expectations(clientCodegen) { { - clientCodegen.setModelPackage(JavaResteasyServerOptionsProvider.MODEL_PACKAGE_VALUE); + clientCodegen + .setModelPackage(JavaResteasyServerOptionsProvider.MODEL_PACKAGE_VALUE); times = 1; clientCodegen.setApiPackage(JavaResteasyServerOptionsProvider.API_PACKAGE_VALUE); times = 1; - clientCodegen.setSortParamsByRequiredFlag( - Boolean.valueOf(JavaResteasyServerOptionsProvider.SORT_PARAMS_VALUE)); + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(JavaResteasyServerOptionsProvider.SORT_PARAMS_VALUE)); times = 1; - clientCodegen.setInvokerPackage(JavaResteasyServerOptionsProvider.INVOKER_PACKAGE_VALUE); + clientCodegen + .setInvokerPackage(JavaResteasyServerOptionsProvider.INVOKER_PACKAGE_VALUE); times = 1; clientCodegen.setGroupId(JavaResteasyServerOptionsProvider.GROUP_ID_VALUE); times = 1; clientCodegen.setArtifactId(JavaResteasyServerOptionsProvider.ARTIFACT_ID_VALUE); times = 1; - clientCodegen.setArtifactVersion(JavaResteasyServerOptionsProvider.ARTIFACT_VERSION_VALUE); + clientCodegen + .setArtifactVersion(JavaResteasyServerOptionsProvider.ARTIFACT_VERSION_VALUE); times = 1; - clientCodegen.setSourceFolder(JavaResteasyServerOptionsProvider.SOURCE_FOLDER_VALUE); + clientCodegen + .setSourceFolder(JavaResteasyServerOptionsProvider.SOURCE_FOLDER_VALUE); times = 1; - clientCodegen.setLocalVariablePrefix(JavaResteasyServerOptionsProvider.LOCAL_PREFIX_VALUE); + clientCodegen + .setLocalVariablePrefix(JavaResteasyServerOptionsProvider.LOCAL_PREFIX_VALUE); times = 1; - clientCodegen.setSerializableModel( - Boolean.valueOf(JavaResteasyServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + clientCodegen.setSerializableModel(Boolean + .valueOf(JavaResteasyServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaResteasyServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); + clientCodegen.setFullJavaUtil(Boolean + .valueOf(JavaResteasyServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); times = 1; clientCodegen.setSerializeBigDecimalAsString(true); times = 1; - clientCodegen.setGenerateJbossDeploymentDescriptor( - Boolean.valueOf(JavaResteasyServerOptionsProvider.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)); - - clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaResteasyServerOptionsProvider.USE_BEANVALIDATION)); + clientCodegen + .setGenerateJbossDeploymentDescriptor(Boolean + .valueOf(JavaResteasyServerOptionsProvider.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)); + + clientCodegen.setUseBeanValidation(Boolean + .valueOf(JavaResteasyServerOptionsProvider.USE_BEANVALIDATION)); times = 1; } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java index 4ce6410eafd..dc1d8f5c44d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java @@ -26,56 +26,66 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(JaxRSServerOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(JaxRSServerOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JaxRSServerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(JaxRSServerOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(JaxRSServerOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(JaxRSServerOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(JaxRSServerOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setArtifactUrl(JaxRSServerOptionsProvider.ARTIFACT_URL_VALUE); - times = 1; - clientCodegen.setArtifactDescription(JaxRSServerOptionsProvider.ARTIFACT_DESCRIPTION_VALUE); - times = 1; - clientCodegen.setScmConnection(JaxRSServerOptionsProvider.SCM_CONNECTION_VALUE); - times = 1; - clientCodegen.setScmDeveloperConnection(JaxRSServerOptionsProvider.SCM_DEVELOPER_CONNECTION_VALUE); - times = 1; - clientCodegen.setScmUrl(JaxRSServerOptionsProvider.SCM_URL_VALUE); - times = 1; - clientCodegen.setDeveloperName(JaxRSServerOptionsProvider.DEVELOPER_NAME_VALUE); - times = 1; - clientCodegen.setDeveloperEmail(JaxRSServerOptionsProvider.DEVELOPER_EMAIL_VALUE); - times = 1; - clientCodegen.setDeveloperOrganization(JaxRSServerOptionsProvider.DEVELOPER_ORGANIZATION_VALUE); - times = 1; - clientCodegen.setDeveloperOrganizationUrl(JaxRSServerOptionsProvider.DEVELOPER_ORGANIZATION_URL_VALUE); - times = 1; - clientCodegen.setSourceFolder(JaxRSServerOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(JaxRSServerOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen.setSerializableModel(Boolean.valueOf(JaxRSServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - //clientCodegen.setLibrary(JaxRSServerOptionsProvider.JAXRS_LIBRARY_VALUE); - clientCodegen.setLibrary("jersey1"); - times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(JaxRSServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); - times = 1; - clientCodegen.setDateLibrary("joda"); - times = 1; - clientCodegen.setSupportJava6(false); - times = 1; - clientCodegen.setUseBeanValidation(Boolean.valueOf(JaxRSServerOptionsProvider.USE_BEANVALIDATION)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setModelPackage(JaxRSServerOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(JaxRSServerOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(JaxRSServerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setInvokerPackage(JaxRSServerOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(JaxRSServerOptionsProvider.GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(JaxRSServerOptionsProvider.ARTIFACT_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(JaxRSServerOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen.setArtifactUrl(JaxRSServerOptionsProvider.ARTIFACT_URL_VALUE); + times = 1; + clientCodegen + .setArtifactDescription(JaxRSServerOptionsProvider.ARTIFACT_DESCRIPTION_VALUE); + times = 1; + clientCodegen.setScmConnection(JaxRSServerOptionsProvider.SCM_CONNECTION_VALUE); + times = 1; + clientCodegen + .setScmDeveloperConnection(JaxRSServerOptionsProvider.SCM_DEVELOPER_CONNECTION_VALUE); + times = 1; + clientCodegen.setScmUrl(JaxRSServerOptionsProvider.SCM_URL_VALUE); + times = 1; + clientCodegen.setDeveloperName(JaxRSServerOptionsProvider.DEVELOPER_NAME_VALUE); + times = 1; + clientCodegen.setDeveloperEmail(JaxRSServerOptionsProvider.DEVELOPER_EMAIL_VALUE); + times = 1; + clientCodegen + .setDeveloperOrganization(JaxRSServerOptionsProvider.DEVELOPER_ORGANIZATION_VALUE); + times = 1; + clientCodegen + .setDeveloperOrganizationUrl(JaxRSServerOptionsProvider.DEVELOPER_ORGANIZATION_URL_VALUE); + times = 1; + clientCodegen.setSourceFolder(JaxRSServerOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setLocalVariablePrefix(JaxRSServerOptionsProvider.LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean + .valueOf(JaxRSServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + times = 1; + // clientCodegen.setLibrary(JaxRSServerOptionsProvider.JAXRS_LIBRARY_VALUE); + clientCodegen.setLibrary("jersey1"); + times = 1; + clientCodegen.setFullJavaUtil(Boolean + .valueOf(JaxRSServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); + times = 1; + clientCodegen.setDateLibrary("joda"); + times = 1; + clientCodegen.setSupportJava6(false); + times = 1; + clientCodegen.setUseBeanValidation(Boolean + .valueOf(JaxRSServerOptionsProvider.USE_BEANVALIDATION)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsCXFClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsCXFClientOptionsTest.java index 6f6ed93084f..d7cb0de63a8 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsCXFClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsCXFClientOptionsTest.java @@ -34,8 +34,8 @@ protected void setExpectations() { times = 1; clientCodegen.setApiPackage(JavaCXFClientOptionsProvider.API_PACKAGE_VALUE); times = 1; - clientCodegen - .setSortParamsByRequiredFlag(Boolean.valueOf(JavaCXFClientOptionsProvider.SORT_PARAMS_VALUE)); + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(JavaCXFClientOptionsProvider.SORT_PARAMS_VALUE)); times = 1; clientCodegen.setInvokerPackage(JavaCXFClientOptionsProvider.INVOKER_PACKAGE_VALUE); times = 1; @@ -43,28 +43,33 @@ protected void setExpectations() { times = 1; clientCodegen.setArtifactId(JavaCXFClientOptionsProvider.ARTIFACT_ID_VALUE); times = 1; - clientCodegen.setArtifactVersion(JavaCXFClientOptionsProvider.ARTIFACT_VERSION_VALUE); + clientCodegen + .setArtifactVersion(JavaCXFClientOptionsProvider.ARTIFACT_VERSION_VALUE); times = 1; clientCodegen.setSourceFolder(JavaCXFClientOptionsProvider.SOURCE_FOLDER_VALUE); times = 1; - clientCodegen.setLocalVariablePrefix(JavaCXFClientOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; clientCodegen - .setSerializableModel(Boolean.valueOf(JavaCXFClientOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + .setLocalVariablePrefix(JavaCXFClientOptionsProvider.LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean + .valueOf(JavaCXFClientOptionsProvider.SERIALIZABLE_MODEL_VALUE)); times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaCXFClientOptionsProvider.FULL_JAVA_UTIL_VALUE)); + clientCodegen.setFullJavaUtil(Boolean + .valueOf(JavaCXFClientOptionsProvider.FULL_JAVA_UTIL_VALUE)); times = 1; clientCodegen.setSerializeBigDecimalAsString(true); times = 1; - clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaCXFClientOptionsProvider.USE_BEANVALIDATION)); + clientCodegen.setUseBeanValidation(Boolean + .valueOf(JavaCXFClientOptionsProvider.USE_BEANVALIDATION)); times = 1; - clientCodegen.setUseLoggingFeatureForTests( - Boolean.valueOf(JavaCXFClientOptionsProvider.USE_LOGGING_FEATURE_FOR_TESTS)); + clientCodegen.setUseLoggingFeatureForTests(Boolean + .valueOf(JavaCXFClientOptionsProvider.USE_LOGGING_FEATURE_FOR_TESTS)); times = 1; - clientCodegen.setUseJaxbAnnotations(Boolean.valueOf(JavaCXFClientOptionsProvider.USE_JAXB_ANNOTATIONS)); + clientCodegen.setUseJaxbAnnotations(Boolean + .valueOf(JavaCXFClientOptionsProvider.USE_JAXB_ANNOTATIONS)); times = 1; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsCXFServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsCXFServerOptionsTest.java index ef3de3a8900..bff0e5b548a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsCXFServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsCXFServerOptionsTest.java @@ -1,108 +1,119 @@ -package io.swagger.codegen.jaxrs; - -import io.swagger.codegen.AbstractOptionsTest; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.languages.JavaCXFServerCodegen; -import io.swagger.codegen.options.JavaCXFServerOptionsProvider; -import io.swagger.codegen.options.OptionsProvider; -import mockit.Expectations; -import mockit.Tested; - -public class JaxrsCXFServerOptionsTest extends AbstractOptionsTest { - - @Tested - private JavaCXFServerCodegen clientCodegen; - - public JaxrsCXFServerOptionsTest() { - super(new JavaCXFServerOptionsProvider()); - } - - protected JaxrsCXFServerOptionsTest(OptionsProvider optionsProvider) { - super(optionsProvider); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @Override - protected void setExpectations() { - new Expectations(clientCodegen) { - { - clientCodegen.setModelPackage(JavaCXFServerOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(JavaCXFServerOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen - .setSortParamsByRequiredFlag(Boolean.valueOf(JavaCXFServerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(JavaCXFServerOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(JavaCXFServerOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(JavaCXFServerOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(JavaCXFServerOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setSourceFolder(JavaCXFServerOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(JavaCXFServerOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen - .setSerializableModel(Boolean.valueOf(JavaCXFServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaCXFServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); - times = 1; - clientCodegen.setSerializeBigDecimalAsString(true); - times = 1; - - clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaCXFServerOptionsProvider.USE_BEANVALIDATION)); - times = 1; - - clientCodegen.setGenerateSpringApplication( - Boolean.valueOf(JavaCXFServerOptionsProvider.USE_SWAGGER_FEATURE)); - times = 1; - clientCodegen.setUseWadlFeature(Boolean.valueOf(JavaCXFServerOptionsProvider.USE_WADL_FEATURE)); - times = 1; - clientCodegen - .setUseMultipartFeature(Boolean.valueOf(JavaCXFServerOptionsProvider.USE_MULTIPART_FEATURE)); - times = 1; - clientCodegen.setUseGzipFeature(Boolean.valueOf(JavaCXFServerOptionsProvider.USE_GZIP_FEATURE)); - times = 1; - clientCodegen.setUseGzipFeatureForTests(Boolean.valueOf(JavaCXFServerOptionsProvider.USE_GZIP_FEATURE)); - times = 1; - clientCodegen.setUseLoggingFeature(Boolean.valueOf(JavaCXFServerOptionsProvider.USE_LOGGING_FEATURE)); - times = 1; - clientCodegen.setUseLoggingFeatureForTests( - Boolean.valueOf(JavaCXFServerOptionsProvider.USE_LOGGING_FEATURE_FOR_TESTS)); - times = 1; - clientCodegen.setUseBeanValidationFeature( - Boolean.valueOf(JavaCXFServerOptionsProvider.USE_BEANVALIDATION_FEATURE)); - times = 1; - - clientCodegen.setGenerateSpringBootApplication( - Boolean.valueOf(JavaCXFServerOptionsProvider.GENERATE_SPRING_BOOT_APPLICATION)); - times = 1; - - clientCodegen.setUseJaxbAnnotations(Boolean.valueOf(JavaCXFServerOptionsProvider.USE_JAXB_ANNOTATIONS)); - times = 1; - - clientCodegen.setUseSpringAnnotationConfig( - Boolean.valueOf(JavaCXFServerOptionsProvider.USE_SPRING_ANNOTATION_CONFIG)); - times = 1; - - clientCodegen.setGenerateJbossDeploymentDescriptor( - Boolean.valueOf(JavaCXFServerOptionsProvider.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)); - times = 1; - - clientCodegen.setUseSwaggerUI(Boolean.valueOf(JavaCXFServerOptionsProvider.USE_SWAGGER_UI)); - times = 1; - - clientCodegen.setAddConsumesProducesJson( - Boolean.valueOf(JavaCXFServerOptionsProvider.ADD_CONSUMES_PRODUCES_JSON)); - times = 1; - } - }; - } -} +package io.swagger.codegen.jaxrs; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.JavaCXFServerCodegen; +import io.swagger.codegen.options.JavaCXFServerOptionsProvider; +import io.swagger.codegen.options.OptionsProvider; +import mockit.Expectations; +import mockit.Tested; + +public class JaxrsCXFServerOptionsTest extends AbstractOptionsTest { + + @Tested + private JavaCXFServerCodegen clientCodegen; + + public JaxrsCXFServerOptionsTest() { + super(new JavaCXFServerOptionsProvider()); + } + + protected JaxrsCXFServerOptionsTest(OptionsProvider optionsProvider) { + super(optionsProvider); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) { + { + clientCodegen.setModelPackage(JavaCXFServerOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(JavaCXFServerOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(JavaCXFServerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setInvokerPackage(JavaCXFServerOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(JavaCXFServerOptionsProvider.GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(JavaCXFServerOptionsProvider.ARTIFACT_ID_VALUE); + times = 1; + clientCodegen + .setArtifactVersion(JavaCXFServerOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen.setSourceFolder(JavaCXFServerOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen + .setLocalVariablePrefix(JavaCXFServerOptionsProvider.LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean + .valueOf(JavaCXFServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + times = 1; + clientCodegen.setFullJavaUtil(Boolean + .valueOf(JavaCXFServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); + times = 1; + clientCodegen.setSerializeBigDecimalAsString(true); + times = 1; + + clientCodegen.setUseBeanValidation(Boolean + .valueOf(JavaCXFServerOptionsProvider.USE_BEANVALIDATION)); + times = 1; + + clientCodegen.setGenerateSpringApplication(Boolean + .valueOf(JavaCXFServerOptionsProvider.USE_SWAGGER_FEATURE)); + times = 1; + clientCodegen.setUseWadlFeature(Boolean + .valueOf(JavaCXFServerOptionsProvider.USE_WADL_FEATURE)); + times = 1; + clientCodegen.setUseMultipartFeature(Boolean + .valueOf(JavaCXFServerOptionsProvider.USE_MULTIPART_FEATURE)); + times = 1; + clientCodegen.setUseGzipFeature(Boolean + .valueOf(JavaCXFServerOptionsProvider.USE_GZIP_FEATURE)); + times = 1; + clientCodegen.setUseGzipFeatureForTests(Boolean + .valueOf(JavaCXFServerOptionsProvider.USE_GZIP_FEATURE)); + times = 1; + clientCodegen.setUseLoggingFeature(Boolean + .valueOf(JavaCXFServerOptionsProvider.USE_LOGGING_FEATURE)); + times = 1; + clientCodegen.setUseLoggingFeatureForTests(Boolean + .valueOf(JavaCXFServerOptionsProvider.USE_LOGGING_FEATURE_FOR_TESTS)); + times = 1; + clientCodegen.setUseBeanValidationFeature(Boolean + .valueOf(JavaCXFServerOptionsProvider.USE_BEANVALIDATION_FEATURE)); + times = 1; + + clientCodegen.setGenerateSpringBootApplication(Boolean + .valueOf(JavaCXFServerOptionsProvider.GENERATE_SPRING_BOOT_APPLICATION)); + times = 1; + + clientCodegen.setUseJaxbAnnotations(Boolean + .valueOf(JavaCXFServerOptionsProvider.USE_JAXB_ANNOTATIONS)); + times = 1; + + clientCodegen.setUseSpringAnnotationConfig(Boolean + .valueOf(JavaCXFServerOptionsProvider.USE_SPRING_ANNOTATION_CONFIG)); + times = 1; + + clientCodegen + .setGenerateJbossDeploymentDescriptor(Boolean + .valueOf(JavaCXFServerOptionsProvider.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)); + times = 1; + + clientCodegen.setUseSwaggerUI(Boolean + .valueOf(JavaCXFServerOptionsProvider.USE_SWAGGER_UI)); + times = 1; + + clientCodegen.setAddConsumesProducesJson(Boolean + .valueOf(JavaCXFServerOptionsProvider.ADD_CONSUMES_PRODUCES_JSON)); + times = 1; + } + }; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsJava8ModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsJava8ModelTest.java index ad26ecc9ae5..826c8dff3c4 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsJava8ModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsJava8ModelTest.java @@ -15,16 +15,14 @@ @SuppressWarnings("static-method") public class JaxrsJava8ModelTest { - + @Test(description = "convert a simple java model with java8 types") public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("theDate", new DateProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name"); + final Model model = + new ModelImpl().description("a sample model").property("id", new LongProperty()) + .property("theDate", new DateProperty()) + .property("createdAt", new DateTimeProperty()).required("id") + .required("name"); final JavaJerseyServerCodegen codegen = new JavaJerseyServerCodegen(); codegen.setDateLibrary("java8"); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsJodaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsJodaModelTest.java index 8c71c51418c..d9881a127a5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsJodaModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsJodaModelTest.java @@ -14,16 +14,14 @@ @SuppressWarnings("static-method") public class JaxrsJodaModelTest { - + @Test(description = "convert a simple java model with Joda types") public void simpleModelTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("theDate", new DateProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name"); + final Model model = + new ModelImpl().description("a sample model").property("id", new LongProperty()) + .property("theDate", new DateProperty()) + .property("createdAt", new DateTimeProperty()).required("id") + .required("name"); final JavaJerseyServerCodegen codegen = new JavaJerseyServerCodegen(); codegen.setDateLibrary("joda"); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/BooleanOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/BooleanOptionsTest.java index 3566f2e98e2..b728d755a48 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/BooleanOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/BooleanOptionsTest.java @@ -23,13 +23,15 @@ private Iterator listOptions() throws IllegalAccessException, Instanti final Reflections reflections = new Reflections(packageName); final List codegenList = new ArrayList(); - for (Class codegen : reflections.getSubTypesOf(DefaultCodegen.class)) { + for (Class codegen : reflections + .getSubTypesOf(DefaultCodegen.class)) { if (!Modifier.isAbstract(codegen.getModifiers())) { codegenList.add((new Object[] {codegen.newInstance()})); } } if (codegenList.size() == 0) { - Assert.fail(String.format("No classes for testing have been found in the package %s", packageName)); + Assert.fail(String.format("No classes for testing have been found in the package %s", + packageName)); } return codegenList.iterator(); @@ -40,8 +42,8 @@ public void booleanOptionsTest(DefaultCodegen codegen) { for (CliOption option : codegen.cliOptions()) { if (option.getType().equals(BooleanProperty.TYPE)) { Assert.assertNotNull(option.getDefault()); - Assert.assertTrue(option.getDefault().equals(Boolean.TRUE.toString()) || - option.getDefault().equals(Boolean.FALSE.toString())); + Assert.assertTrue(option.getDefault().equals(Boolean.TRUE.toString()) + || option.getDefault().equals(Boolean.FALSE.toString())); } } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/JavaClientCodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/JavaClientCodegenTest.java index 2dceedacf93..0bc89aee263 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/JavaClientCodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/JavaClientCodegenTest.java @@ -10,70 +10,83 @@ import org.testng.annotations.Test; public class JavaClientCodegenTest { - - private static final String VENDOR_MIME_TYPE = "application/vnd.company.v1+json"; - private static final String XML_MIME_TYPE = "application/xml"; - private static final String JSON_MIME_TYPE = "application/json"; - private static final String TEXT_MIME_TYPE = "text/plain"; - - @Test - public void testJsonMime() { - Assert.assertTrue(JavaClientCodegen.isJsonMimeType(JSON_MIME_TYPE)); - Assert.assertFalse(JavaClientCodegen.isJsonMimeType(XML_MIME_TYPE)); - Assert.assertFalse(JavaClientCodegen.isJsonMimeType(TEXT_MIME_TYPE)); - - Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany+json")); - Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany.v1+json")); - Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany.resourceTypeA.version1+json")); - Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany.resourceTypeB.version2+json")); - Assert.assertFalse(JavaClientCodegen.isJsonVendorMimeType("application/v.json")); - - } - - @Test - public void testContentTypePrioritization() { - Map jsonMimeType = new HashMap<>(); - jsonMimeType.put(JavaClientCodegen.MEDIA_TYPE, JSON_MIME_TYPE); - - Map xmlMimeType = new HashMap<>(); - xmlMimeType.put(JavaClientCodegen.MEDIA_TYPE, XML_MIME_TYPE); - - Map vendorMimeType = new HashMap<>(); - vendorMimeType.put(JavaClientCodegen.MEDIA_TYPE, VENDOR_MIME_TYPE); - - Map textMimeType = new HashMap<>(); - textMimeType.put(JavaClientCodegen.MEDIA_TYPE, TEXT_MIME_TYPE); - - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes( - Collections.>emptyList()), Collections.emptyList()); - - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType)), Arrays.asList(xmlMimeType)); - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(jsonMimeType)), Arrays.asList(jsonMimeType)); - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(vendorMimeType)), Arrays.asList(vendorMimeType)); - - - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType, jsonMimeType)), - Arrays.asList(jsonMimeType, xmlMimeType)); - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(jsonMimeType, xmlMimeType)), - Arrays.asList(jsonMimeType, xmlMimeType)); - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(jsonMimeType, vendorMimeType)), - Arrays.asList(vendorMimeType, jsonMimeType)); - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(textMimeType, xmlMimeType)), - Arrays.asList(textMimeType, xmlMimeType)); - Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType, textMimeType)), - Arrays.asList(xmlMimeType, textMimeType)); - - System.out.println(JavaClientCodegen.prioritizeContentTypes(Arrays.asList( - xmlMimeType,textMimeType, jsonMimeType, vendorMimeType))); - - List> priContentTypes = JavaClientCodegen.prioritizeContentTypes(Arrays.asList( - xmlMimeType, textMimeType, jsonMimeType, vendorMimeType)); - Assert.assertEquals(priContentTypes, Arrays.asList(vendorMimeType, jsonMimeType, xmlMimeType, textMimeType)); - - for ( int i = 0; i < 3; i++ ) - Assert.assertNotNull(priContentTypes.get(i).get("hasMore")); - Assert.assertNull(priContentTypes.get(3).get("hasMore")); - - } - + + private static final String VENDOR_MIME_TYPE = "application/vnd.company.v1+json"; + private static final String XML_MIME_TYPE = "application/xml"; + private static final String JSON_MIME_TYPE = "application/json"; + private static final String TEXT_MIME_TYPE = "text/plain"; + + @Test + public void testJsonMime() { + Assert.assertTrue(JavaClientCodegen.isJsonMimeType(JSON_MIME_TYPE)); + Assert.assertFalse(JavaClientCodegen.isJsonMimeType(XML_MIME_TYPE)); + Assert.assertFalse(JavaClientCodegen.isJsonMimeType(TEXT_MIME_TYPE)); + + Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany+json")); + Assert.assertTrue(JavaClientCodegen + .isJsonVendorMimeType("application/vnd.mycompany.v1+json")); + Assert.assertTrue(JavaClientCodegen + .isJsonVendorMimeType("application/vnd.mycompany.resourceTypeA.version1+json")); + Assert.assertTrue(JavaClientCodegen + .isJsonVendorMimeType("application/vnd.mycompany.resourceTypeB.version2+json")); + Assert.assertFalse(JavaClientCodegen.isJsonVendorMimeType("application/v.json")); + + } + + @Test + public void testContentTypePrioritization() { + Map jsonMimeType = new HashMap<>(); + jsonMimeType.put(JavaClientCodegen.MEDIA_TYPE, JSON_MIME_TYPE); + + Map xmlMimeType = new HashMap<>(); + xmlMimeType.put(JavaClientCodegen.MEDIA_TYPE, XML_MIME_TYPE); + + Map vendorMimeType = new HashMap<>(); + vendorMimeType.put(JavaClientCodegen.MEDIA_TYPE, VENDOR_MIME_TYPE); + + Map textMimeType = new HashMap<>(); + textMimeType.put(JavaClientCodegen.MEDIA_TYPE, TEXT_MIME_TYPE); + + Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Collections + .>emptyList()), Collections.emptyList()); + + Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType)), + Arrays.asList(xmlMimeType)); + Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(jsonMimeType)), + Arrays.asList(jsonMimeType)); + Assert.assertEquals( + JavaClientCodegen.prioritizeContentTypes(Arrays.asList(vendorMimeType)), + Arrays.asList(vendorMimeType)); + + + Assert.assertEquals( + JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType, jsonMimeType)), + Arrays.asList(jsonMimeType, xmlMimeType)); + Assert.assertEquals( + JavaClientCodegen.prioritizeContentTypes(Arrays.asList(jsonMimeType, xmlMimeType)), + Arrays.asList(jsonMimeType, xmlMimeType)); + Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(jsonMimeType, + vendorMimeType)), Arrays.asList(vendorMimeType, jsonMimeType)); + Assert.assertEquals( + JavaClientCodegen.prioritizeContentTypes(Arrays.asList(textMimeType, xmlMimeType)), + Arrays.asList(textMimeType, xmlMimeType)); + Assert.assertEquals( + JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType, textMimeType)), + Arrays.asList(xmlMimeType, textMimeType)); + + System.out.println(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType, + textMimeType, jsonMimeType, vendorMimeType))); + + List> priContentTypes = + JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType, textMimeType, + jsonMimeType, vendorMimeType)); + Assert.assertEquals(priContentTypes, + Arrays.asList(vendorMimeType, jsonMimeType, xmlMimeType, textMimeType)); + + for (int i = 0; i < 3; i++) + Assert.assertNotNull(priContentTypes.get(i).get("hasMore")); + Assert.assertNull(priContentTypes.get(3).get("hasMore")); + + } + } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/lumen/LumenServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/lumen/LumenServerOptionsTest.java index 434e318f593..d14a7e903ef 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/lumen/LumenServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/lumen/LumenServerOptionsTest.java @@ -25,27 +25,31 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(LumenServerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setParameterNamingConvention(LumenServerOptionsProvider.VARIABLE_NAMING_CONVENTION_VALUE); - clientCodegen.setModelPackage(LumenServerOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(LumenServerOptionsProvider.API_PACKAGE_VALUE); - times = 1; - times = 1; - clientCodegen.setInvokerPackage(LumenServerOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setPackagePath(LumenServerOptionsProvider.PACKAGE_PATH_VALUE); - times = 1; - clientCodegen.setSrcBasePath(LumenServerOptionsProvider.SRC_BASE_PATH_VALUE); - times = 1; - clientCodegen.setGitUserId(LumenServerOptionsProvider.GIT_USER_ID_VALUE); - times = 1; - clientCodegen.setGitRepoId(LumenServerOptionsProvider.GIT_REPO_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(LumenServerOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(LumenServerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen + .setParameterNamingConvention(LumenServerOptionsProvider.VARIABLE_NAMING_CONVENTION_VALUE); + clientCodegen.setModelPackage(LumenServerOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(LumenServerOptionsProvider.API_PACKAGE_VALUE); + times = 1; + times = 1; + clientCodegen.setInvokerPackage(LumenServerOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setPackagePath(LumenServerOptionsProvider.PACKAGE_PATH_VALUE); + times = 1; + clientCodegen.setSrcBasePath(LumenServerOptionsProvider.SRC_BASE_PATH_VALUE); + times = 1; + clientCodegen.setGitUserId(LumenServerOptionsProvider.GIT_USER_ID_VALUE); + times = 1; + clientCodegen.setGitRepoId(LumenServerOptionsProvider.GIT_REPO_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(LumenServerOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java index 658b2f7ecca..99b5eb5b2e4 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java @@ -28,22 +28,25 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(NodeJSServerOptionsProvider.SORT_PARAMS_VALUE)); - clientCodegen.setGoogleCloudFunctions(Boolean.valueOf(NodeJSServerOptionsProvider.GOOGLE_CLOUD_FUNCTIONS)); - clientCodegen.setExportedName(NodeJSServerOptionsProvider.EXPORTED_NAME); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(NodeJSServerOptionsProvider.SORT_PARAMS_VALUE)); + clientCodegen.setGoogleCloudFunctions(Boolean + .valueOf(NodeJSServerOptionsProvider.GOOGLE_CLOUD_FUNCTIONS)); + clientCodegen.setExportedName(NodeJSServerOptionsProvider.EXPORTED_NAME); + times = 1; + } + }; } @Test public void testCleanTitle() { String dirtyTitle = "safe-title"; - String clean = dirtyTitle.replaceAll("[^a-zA-Z0-9]", "-") - .replaceAll("^[-]*", "") - .replaceAll("[-]*$", "") - .replaceAll("[-]{2,}", "-"); + String clean = + dirtyTitle.replaceAll("[^a-zA-Z0-9]", "-").replaceAll("^[-]*", "") + .replaceAll("[-]*$", "").replaceAll("[-]{2,}", "-"); assertEquals(clean, "safe-title"); } @@ -51,10 +54,9 @@ public void testCleanTitle() { @Test public void testDirtyTitleCleansing() { String dirtyTitle = "_it's-$ooo//////////---_//dirty!!!!"; - String clean = dirtyTitle.replaceAll("[^a-zA-Z0-9]", "-") - .replaceAll("^[-]*", "") - .replaceAll("[-]*$", "") - .replaceAll("[-]{2,}", "-"); + String clean = + dirtyTitle.replaceAll("[^a-zA-Z0-9]", "-").replaceAll("^[-]*", "") + .replaceAll("[-]*$", "").replaceAll("[-]{2,}", "-"); assertEquals(clean, "it-s-ooo-dirty"); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java index f1d55e007da..b764de565c0 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java @@ -25,19 +25,21 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setClassPrefix(ObjcClientOptionsProvider.CLASS_PREFIX_VALUE); - times = 1; - clientCodegen.setPodName(ObjcClientOptionsProvider.POD_NAME_VALUE); - times = 1; - clientCodegen.setPodVersion(ObjcClientOptionsProvider.POD_VERSION_VALUE); - times = 1; - clientCodegen.setAuthorName(ObjcClientOptionsProvider.AUTHOR_NAME_VALUE); - times = 1; - clientCodegen.setAuthorEmail(ObjcClientOptionsProvider.AUTHOR_EMAIL_VALUE); - times = 1; - clientCodegen.setGitRepoURL(ObjcClientOptionsProvider.GIT_REPO_URL_VALUE); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setClassPrefix(ObjcClientOptionsProvider.CLASS_PREFIX_VALUE); + times = 1; + clientCodegen.setPodName(ObjcClientOptionsProvider.POD_NAME_VALUE); + times = 1; + clientCodegen.setPodVersion(ObjcClientOptionsProvider.POD_VERSION_VALUE); + times = 1; + clientCodegen.setAuthorName(ObjcClientOptionsProvider.AUTHOR_NAME_VALUE); + times = 1; + clientCodegen.setAuthorEmail(ObjcClientOptionsProvider.AUTHOR_EMAIL_VALUE); + times = 1; + clientCodegen.setGitRepoURL(ObjcClientOptionsProvider.GIT_REPO_URL_VALUE); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java index 7f74cdf1145..9166e13ae93 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java @@ -17,39 +17,40 @@ public class ObjcModelTest { @Test(description = "convert a model with a advanced map property") public void advancedMapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new MapProperty().additionalProperties(new StringProperty()))) - .required("id"); + final Model model = + new ModelImpl() + .description("a sample model") + .property( + "translations", + new MapProperty().additionalProperties(new MapProperty() + .additionalProperties(new StringProperty()))) + .required("id"); final DefaultCodegen codegen = new ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); - + Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "SWGSample"); Assert.assertEquals(cm.description, "a sample model"); Assert.assertEquals(cm.vars.size(), 1); - + final CodegenProperty property1 = cm.vars.get(0); Assert.assertEquals(property1.baseName, "translations"); - Assert.assertEquals(property1.datatype, "NSDictionary*>*"); + Assert.assertEquals(property1.datatype, + "NSDictionary*>*"); Assert.assertEquals(property1.name, "translations"); Assert.assertEquals(property1.baseType, "NSDictionary"); Assert.assertEquals(property1.containerType, "map"); Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); } - + @Test(description = "convert a simple java 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()) - .required("id") - .required("name") - .discriminator("test"); + final Model model = + new ModelImpl().description("a sample model").property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()).required("id") + .required("name").discriminator("test"); final DefaultCodegen codegen = new ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -57,7 +58,7 @@ public void simpleModelTest() { Assert.assertEquals(cm.classname, "SWGSample"); Assert.assertEquals(cm.description, "a sample model"); Assert.assertEquals(cm.vars.size(), 3); - Assert.assertEquals(cm.discriminator,"test"); + Assert.assertEquals(cm.discriminator, "test"); final CodegenProperty property1 = cm.vars.get(0); Assert.assertEquals(property1.baseName, "id"); @@ -94,12 +95,10 @@ public void simpleModelTest() { @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 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 ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -134,11 +133,12 @@ public void listPropertyTest() { @Test(description = "convert a model with a map property") public void mapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); + final Model model = + new ModelImpl() + .description("a sample model") + .property("translations", + new MapProperty().additionalProperties(new StringProperty())) + .required("id"); final DefaultCodegen codegen = new ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -158,12 +158,12 @@ public void mapPropertyTest() { Assert.assertTrue(property1.isPrimitiveType); } - + @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 Model model = + new ModelImpl().description("a sample model").property("children", + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -183,10 +183,9 @@ public void complexPropertyTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new ArrayProperty().items(new RefProperty("#/definitions/Children"))); final DefaultCodegen codegen = new ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -208,10 +207,11 @@ public void complexListPropertyTest() { @Test(description = "convert a model with complex map property") public void complexMapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new MapProperty() - .additionalProperties(new RefProperty("#/definitions/Children"))); + final Model model = + new ModelImpl().description("a sample model").property( + "children", + new MapProperty().additionalProperties(new RefProperty( + "#/definitions/Children"))); final DefaultCodegen codegen = new ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -235,9 +235,9 @@ public void complexMapPropertyTest() { @Test(description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Model model = + new ArrayModel().description("an array model").items( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -252,9 +252,9 @@ public void arrayModelTest() { @Test(description = "convert an map model") public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + final Model model = + new ModelImpl().description("a map model").additionalProperties( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new ObjcClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -269,11 +269,13 @@ public void mapModelTest() { @Test(description = "test udid") public void udidAndPasswordDataModelTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final Swagger model = + new SwaggerParser() + .read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); final DefaultCodegen codegen = new ObjcClientCodegen(); final Model definition = model.getDefinitions().get("format_test"); - Property property = definition.getProperties().get("uuid"); + Property property = definition.getProperties().get("uuid"); CodegenProperty prope = codegen.fromProperty("uuid", property); Assert.assertEquals(prope.baseType, "NSString"); @@ -283,30 +285,36 @@ public void udidAndPasswordDataModelTest() { @Test(description = "test mixedProperties") public void mixedPropertiesDataModelTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final Swagger model = + new SwaggerParser() + .read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); final DefaultCodegen codegen = new ObjcClientCodegen(); - final Model definition = model.getDefinitions().get("MixedPropertiesAndAdditionalPropertiesClass"); + final Model definition = + model.getDefinitions().get("MixedPropertiesAndAdditionalPropertiesClass"); - Property property = definition.getProperties().get("map"); + Property property = definition.getProperties().get("map"); CodegenProperty prope = codegen.fromProperty("map", property); Assert.assertEquals(prope.baseType, "NSDictionary"); } @Test(description = "test isArrayModel") public void isArrayModelModelTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final Swagger model = + new SwaggerParser() + .read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); final DefaultCodegen codegen = new ObjcClientCodegen(); final Model definition = model.getDefinitions().get("AnimalFarm"); - final CodegenModel codegenModel = codegen.fromModel("AnimalFarm",definition); + final CodegenModel codegenModel = codegen.fromModel("AnimalFarm", definition); Assert.assertEquals(codegenModel.isArrayModel, true); - Assert.assertEquals(codegenModel.arrayModelType,"SWGAnimal"); + Assert.assertEquals(codegenModel.arrayModelType, "SWGAnimal"); } @Test(description = "test binary data") public void binaryDataModelTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); + final Swagger model = + new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); final DefaultCodegen codegen = new ObjcClientCodegen(); final String path = "/tests/binaryResponse"; final Operation p = model.getPaths().get(path).getPost(); @@ -328,7 +336,9 @@ public void issue316Test() { final Path animalOps = animalPaths.get("/animals"); Assert.assertNotNull(animalOps.getPost()); - final CodegenOperation animalCo = codegen.fromOperation("/animals", "POST", animalOps.getPost(), model.getDefinitions()); + final CodegenOperation animalCo = + codegen.fromOperation("/animals", "POST", animalOps.getPost(), + model.getDefinitions()); Assert.assertEquals(animalCo.imports.size(), 1); Assert.assertTrue(animalCo.imports.contains("SWGAnimal")); @@ -336,7 +346,9 @@ public void issue316Test() { final Path insectOps = insectPaths.get("/insects"); Assert.assertNotNull(insectOps.getPost()); - final CodegenOperation insectCo = codegen.fromOperation("/insects", "POST", insectOps.getPost(), model.getDefinitions()); + final CodegenOperation insectCo = + codegen.fromOperation("/insects", "POST", insectOps.getPost(), + model.getDefinitions()); Assert.assertEquals(insectCo.imports.size(), 1); Assert.assertTrue(insectCo.imports.contains("SWGInsect")); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java index c17a567798e..544219c5525 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java @@ -30,7 +30,8 @@ public String getLanguage() { @Override public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + return builder + .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) @@ -39,7 +40,8 @@ public Map createOptions() { .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .put(AndroidClientCodegen.USE_ANDROID_MAVEN_GRADLE_PLUGIN, ANDROID_MAVEN_GRADLE_PLUGIN_VALUE) + .put(AndroidClientCodegen.USE_ANDROID_MAVEN_GRADLE_PLUGIN, + ANDROID_MAVEN_GRADLE_PLUGIN_VALUE) .put(CodegenConstants.LIBRARY, LIBRARY_VALUE) .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AspNetCoreServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AspNetCoreServerOptionsProvider.java index f4c58fd7124..524a3ca561a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AspNetCoreServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AspNetCoreServerOptionsProvider.java @@ -9,7 +9,7 @@ public class AspNetCoreServerOptionsProvider implements OptionsProvider { public static final String PACKAGE_NAME_VALUE = "swagger_server_aspnetcore"; public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String SOURCE_FOLDER_VALUE = "src_aspnetcore"; - + @Override public String getLanguage() { return "aspnetcore"; @@ -24,8 +24,7 @@ public Map createOptions() { .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") .put(CodegenConstants.USE_DATETIME_OFFSET, "true") .put(CodegenConstants.USE_COLLECTION, "false") - .put(CodegenConstants.RETURN_ICOLLECTION, "false") - .build(); + .put(CodegenConstants.RETURN_ICOLLECTION, "false").build(); } @Override diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/BashClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/BashClientOptionsProvider.java index cd27b2f43dd..3233f338322 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/BashClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/BashClientOptionsProvider.java @@ -14,14 +14,10 @@ public class BashClientOptionsProvider implements OptionsProvider { public static final String SCRIPT_NAME = "petstore-cli"; public static final String GENERATE_BASH_COMPLETION = "true"; public static final String GENERATE_ZSH_COMPLETION = "false"; - public static final String HOST_ENVIRONMENT_VARIABLE_NAME - = "PETSTORE_HOSTNAME"; - public static final String BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME - = "PETSTORE_BASIC_AUTH"; - public static final String APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME - = "PETSTORE_APIKEY"; - public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE - = "false"; + public static final String HOST_ENVIRONMENT_VARIABLE_NAME = "PETSTORE_HOSTNAME"; + public static final String BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME = "PETSTORE_BASIC_AUTH"; + public static final String APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME = "PETSTORE_APIKEY"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; @Override @@ -31,35 +27,32 @@ public String getLanguage() { @Override public Map createOptions() { - - ImmutableMap.Builder builder - = new ImmutableMap.Builder(); + + ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder .put(BashClientCodegen.CURL_OPTIONS, CURL_OPTIONS) .put(BashClientCodegen.SCRIPT_NAME, SCRIPT_NAME) .put(BashClientCodegen.PROCESS_MARKDOWN, PROCESS_MARKDOWN) - .put(BashClientCodegen.GENERATE_BASH_COMPLETION, - GENERATE_BASH_COMPLETION) - .put(BashClientCodegen.GENERATE_ZSH_COMPLETION, - GENERATE_ZSH_COMPLETION) - .put(BashClientCodegen.HOST_ENVIRONMENT_VARIABLE_NAME, + .put(BashClientCodegen.GENERATE_BASH_COMPLETION, GENERATE_BASH_COMPLETION) + .put(BashClientCodegen.GENERATE_ZSH_COMPLETION, GENERATE_ZSH_COMPLETION) + .put(BashClientCodegen.HOST_ENVIRONMENT_VARIABLE_NAME, HOST_ENVIRONMENT_VARIABLE_NAME) - .put(BashClientCodegen.BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME, + .put(BashClientCodegen.BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME, BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME) - .put(BashClientCodegen.APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME, + .put(BashClientCodegen.APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME, APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "false") .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, "false") .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/options/CsharpDotNet2ClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CsharpDotNet2ClientOptionsProvider.java index cbbd7b2f093..85dcf905421 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CsharpDotNet2ClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CsharpDotNet2ClientOptionsProvider.java @@ -22,8 +22,7 @@ public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) - .put(CsharpDotNet2ClientCodegen.CLIENT_PACKAGE, CLIENT_PACKAGE_VALUE) - .build(); + .put(CsharpDotNet2ClientCodegen.CLIENT_PACKAGE, CLIENT_PACKAGE_VALUE).build(); } @Override diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ElixirClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ElixirClientOptionsProvider.java index 092fccc2e0a..a991535a3bd 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ElixirClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ElixirClientOptionsProvider.java @@ -15,11 +15,9 @@ public String getLanguage() { @Override public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "false") + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "false") .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, "false") - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, "false") - .build(); + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, "false").build(); } @Override diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/FlashClienOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/FlashClienOptionsProvider.java index 1fcdc86271b..4c147b02ca2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/FlashClienOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/FlashClienOptionsProvider.java @@ -23,8 +23,7 @@ public Map createOptions() { return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .build(); + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE).build(); } @Override diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/GoClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/GoClientOptionsProvider.java index af1613e8051..8aa8d673a00 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/GoClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/GoClientOptionsProvider.java @@ -20,11 +20,9 @@ public String getLanguage() { @Override public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder - .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) + return builder.put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) .put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) - .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") - .build(); + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true").build(); } @Override diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaCXFClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaCXFClientOptionsProvider.java index afafd6ecf2f..ba2a307671d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaCXFClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaCXFClientOptionsProvider.java @@ -11,12 +11,12 @@ public class JavaCXFClientOptionsProvider extends JavaOptionsProvider { public static final String USE_BEANVALIDATION = "true"; public static final String USE_JAXB_ANNOTATIONS = "true"; - + public static final String USE_GZIP_FEATURE_FOR_TESTS = "true"; public static final String USE_LOGGING_FEATURE_FOR_TESTS = "true"; - + @Override public boolean isServer() { return false; @@ -29,19 +29,21 @@ public String getLanguage() { @Override public Map createOptions() { - - Map parentOptions = super.createOptions(); - - ImmutableMap.Builder builder = new ImmutableMap.Builder() - .putAll(parentOptions); - - builder.put(JavaCXFClientCodegen.USE_BEANVALIDATION, JavaCXFClientOptionsProvider.USE_BEANVALIDATION); + + Map parentOptions = super.createOptions(); + + ImmutableMap.Builder builder = + new ImmutableMap.Builder().putAll(parentOptions); + + builder.put(JavaCXFClientCodegen.USE_BEANVALIDATION, + JavaCXFClientOptionsProvider.USE_BEANVALIDATION); builder.put(JavaCXFClientCodegen.USE_JAXB_ANNOTATIONS, USE_JAXB_ANNOTATIONS); builder.put(JavaCXFClientCodegen.USE_GZIP_FEATURE_FOR_TESTS, USE_GZIP_FEATURE_FOR_TESTS); - builder.put(JavaCXFClientCodegen.USE_LOGGING_FEATURE_FOR_TESTS, USE_LOGGING_FEATURE_FOR_TESTS); + builder.put(JavaCXFClientCodegen.USE_LOGGING_FEATURE_FOR_TESTS, + USE_LOGGING_FEATURE_FOR_TESTS); return builder.build(); - + } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaCXFServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaCXFServerOptionsProvider.java index 22deb3daace..b38ac9dae0d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaCXFServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaCXFServerOptionsProvider.java @@ -1,99 +1,103 @@ -package io.swagger.codegen.options; - -import java.util.Map; - -import com.google.common.collect.ImmutableMap; - -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.languages.JavaCXFServerCodegen; - -public class JavaCXFServerOptionsProvider extends JavaOptionsProvider { - - public static final String USE_JAXB_ANNOTATIONS = "true"; - - public static final String GENERATE_SPRING_APPLICATION = "true"; - - public static final String USE_SWAGGER_FEATURE = "true"; - - public static final String USE_SWAGGER_UI = "true"; - - public static final String USE_WADL_FEATURE = "true"; - - public static final String USE_MULTIPART_FEATURE = "true"; - - public static final String USE_GZIP_FEATURE = "true"; - - public static final String USE_GZIP_FEATURE_FOR_TESTS = "true"; - - public static final String USE_LOGGING_FEATURE = "true"; - - public static final String USE_LOGGING_FEATURE_FOR_TESTS = "true"; - - public static final String USE_BEANVALIDATION_FEATURE = "true"; - - public static final String USE_SPRING_ANNOTATION_CONFIG = "true"; - - public static final String GENERATE_SPRING_BOOT_APPLICATION = "true"; - - public static final String GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR = "true"; - - public static final String ADD_CONSUMES_PRODUCES_JSON = "true"; - - public static final String IMPL_FOLDER_VALUE = "src/main/java"; - - public static final String USE_ANNOTATED_BASE_PATH = "true"; - - public static final String GENERATE_NON_SPRING_APPLICATION = "true"; - - @Override - public boolean isServer() { - return true; - } - - @Override - public String getLanguage() { - return "jaxrs-cxf"; - } - - @Override - public Map createOptions() { - - Map parentOptions = super.createOptions(); - - ImmutableMap.Builder builder = new ImmutableMap.Builder() - .putAll(parentOptions); - - builder.put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE); - builder.put("title", "Test title"); - - builder.put(JavaCXFServerCodegen.USE_BEANVALIDATION, JavaOptionsProvider.USE_BEANVALIDATION); - builder.put(JavaCXFServerCodegen.USE_JAXB_ANNOTATIONS, USE_JAXB_ANNOTATIONS); - - builder.put(JavaCXFServerCodegen.GENERATE_SPRING_APPLICATION, GENERATE_SPRING_APPLICATION); - builder.put(JavaCXFServerCodegen.USE_SPRING_ANNOTATION_CONFIG, USE_SPRING_ANNOTATION_CONFIG); - - builder.put(JavaCXFServerCodegen.USE_SWAGGER_FEATURE, USE_SWAGGER_FEATURE); - builder.put(JavaCXFServerCodegen.USE_SWAGGER_UI, USE_SWAGGER_UI); - - builder.put(JavaCXFServerCodegen.USE_WADL_FEATURE, USE_WADL_FEATURE); - builder.put(JavaCXFServerCodegen.USE_MULTIPART_FEATURE, USE_MULTIPART_FEATURE); - builder.put(JavaCXFServerCodegen.USE_GZIP_FEATURE, USE_GZIP_FEATURE); - builder.put(JavaCXFServerCodegen.USE_GZIP_FEATURE_FOR_TESTS, USE_GZIP_FEATURE_FOR_TESTS); - builder.put(JavaCXFServerCodegen.USE_LOGGING_FEATURE, USE_LOGGING_FEATURE); - builder.put(JavaCXFServerCodegen.USE_LOGGING_FEATURE_FOR_TESTS, USE_LOGGING_FEATURE_FOR_TESTS); - builder.put(JavaCXFServerCodegen.USE_BEANVALIDATION_FEATURE, USE_BEANVALIDATION_FEATURE); - - builder.put(JavaCXFServerCodegen.GENERATE_SPRING_BOOT_APPLICATION, GENERATE_SPRING_BOOT_APPLICATION); - - builder.put(JavaCXFServerCodegen.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); - - builder.put(JavaCXFServerCodegen.ADD_CONSUMES_PRODUCES_JSON, ADD_CONSUMES_PRODUCES_JSON); - - builder.put(JavaCXFServerCodegen.USE_ANNOTATED_BASE_PATH, USE_ANNOTATED_BASE_PATH); - - builder.put(JavaCXFServerCodegen.GENERATE_NON_SPRING_APPLICATION, GENERATE_NON_SPRING_APPLICATION); - - return builder.build(); - - } -} +package io.swagger.codegen.options; + +import java.util.Map; + +import com.google.common.collect.ImmutableMap; + +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.JavaCXFServerCodegen; + +public class JavaCXFServerOptionsProvider extends JavaOptionsProvider { + + public static final String USE_JAXB_ANNOTATIONS = "true"; + + public static final String GENERATE_SPRING_APPLICATION = "true"; + + public static final String USE_SWAGGER_FEATURE = "true"; + + public static final String USE_SWAGGER_UI = "true"; + + public static final String USE_WADL_FEATURE = "true"; + + public static final String USE_MULTIPART_FEATURE = "true"; + + public static final String USE_GZIP_FEATURE = "true"; + + public static final String USE_GZIP_FEATURE_FOR_TESTS = "true"; + + public static final String USE_LOGGING_FEATURE = "true"; + + public static final String USE_LOGGING_FEATURE_FOR_TESTS = "true"; + + public static final String USE_BEANVALIDATION_FEATURE = "true"; + + public static final String USE_SPRING_ANNOTATION_CONFIG = "true"; + + public static final String GENERATE_SPRING_BOOT_APPLICATION = "true"; + + public static final String GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR = "true"; + + public static final String ADD_CONSUMES_PRODUCES_JSON = "true"; + + public static final String IMPL_FOLDER_VALUE = "src/main/java"; + + public static final String USE_ANNOTATED_BASE_PATH = "true"; + + public static final String GENERATE_NON_SPRING_APPLICATION = "true"; + + @Override + public boolean isServer() { + return true; + } + + @Override + public String getLanguage() { + return "jaxrs-cxf"; + } + + @Override + public Map createOptions() { + + Map parentOptions = super.createOptions(); + + ImmutableMap.Builder builder = + new ImmutableMap.Builder().putAll(parentOptions); + + builder.put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE); + builder.put("title", "Test title"); + + builder.put(JavaCXFServerCodegen.USE_BEANVALIDATION, JavaOptionsProvider.USE_BEANVALIDATION); + builder.put(JavaCXFServerCodegen.USE_JAXB_ANNOTATIONS, USE_JAXB_ANNOTATIONS); + + builder.put(JavaCXFServerCodegen.GENERATE_SPRING_APPLICATION, GENERATE_SPRING_APPLICATION); + builder.put(JavaCXFServerCodegen.USE_SPRING_ANNOTATION_CONFIG, USE_SPRING_ANNOTATION_CONFIG); + + builder.put(JavaCXFServerCodegen.USE_SWAGGER_FEATURE, USE_SWAGGER_FEATURE); + builder.put(JavaCXFServerCodegen.USE_SWAGGER_UI, USE_SWAGGER_UI); + + builder.put(JavaCXFServerCodegen.USE_WADL_FEATURE, USE_WADL_FEATURE); + builder.put(JavaCXFServerCodegen.USE_MULTIPART_FEATURE, USE_MULTIPART_FEATURE); + builder.put(JavaCXFServerCodegen.USE_GZIP_FEATURE, USE_GZIP_FEATURE); + builder.put(JavaCXFServerCodegen.USE_GZIP_FEATURE_FOR_TESTS, USE_GZIP_FEATURE_FOR_TESTS); + builder.put(JavaCXFServerCodegen.USE_LOGGING_FEATURE, USE_LOGGING_FEATURE); + builder.put(JavaCXFServerCodegen.USE_LOGGING_FEATURE_FOR_TESTS, + USE_LOGGING_FEATURE_FOR_TESTS); + builder.put(JavaCXFServerCodegen.USE_BEANVALIDATION_FEATURE, USE_BEANVALIDATION_FEATURE); + + builder.put(JavaCXFServerCodegen.GENERATE_SPRING_BOOT_APPLICATION, + GENERATE_SPRING_BOOT_APPLICATION); + + builder.put(JavaCXFServerCodegen.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, + GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); + + builder.put(JavaCXFServerCodegen.ADD_CONSUMES_PRODUCES_JSON, ADD_CONSUMES_PRODUCES_JSON); + + builder.put(JavaCXFServerCodegen.USE_ANNOTATED_BASE_PATH, USE_ANNOTATED_BASE_PATH); + + builder.put(JavaCXFServerCodegen.GENERATE_NON_SPRING_APPLICATION, + GENERATE_NON_SPRING_APPLICATION); + + return builder.build(); + + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java index eb60599435c..036cb1128c1 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java @@ -17,20 +17,23 @@ public class JavaOptionsProvider implements OptionsProvider { public static final String DEVELOPER_EMAIL_VALUE = "apiteam@swagger.io"; public static final String DEVELOPER_ORGANIZATION_VALUE = "Swagger"; public static final String DEVELOPER_ORGANIZATION_URL_VALUE = "http://swagger.io"; - public static final String SCM_CONNECTION_VALUE = "scm:git:git@github.com:swagger-api/swagger-codegen.git"; - public static final String SCM_DEVELOPER_CONNECTION_VALUE = "scm:git:git@github.com:swagger-api/swagger-codegen.git"; + public static final String SCM_CONNECTION_VALUE = + "scm:git:git@github.com:swagger-api/swagger-codegen.git"; + public static final String SCM_DEVELOPER_CONNECTION_VALUE = + "scm:git:git@github.com:swagger-api/swagger-codegen.git"; public static final String SCM_URL_VALUE = "https://github.com/swagger-api/swagger-codegen"; public static final String SORT_PARAMS_VALUE = "false"; public static final String GROUP_ID_VALUE = "io.swagger.test"; public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; - public static final String ARTIFACT_URL_VALUE = "https://github.com/swagger-api/swagger-codegen"; + public static final String ARTIFACT_URL_VALUE = + "https://github.com/swagger-api/swagger-codegen"; public static final String ARTIFACT_DESCRIPTION_VALUE = "Swagger Java Client Test"; public static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; public static final String LOCAL_PREFIX_VALUE = "tst"; public static final String SERIALIZABLE_MODEL_VALUE = "false"; public static final String FULL_JAVA_UTIL_VALUE = "true"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - //public static final String SUPPORT_JAVA6 = "true"; + // public static final String SUPPORT_JAVA6 = "true"; public static final String USE_BEANVALIDATION = "false"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; @@ -41,46 +44,49 @@ public class JavaOptionsProvider implements OptionsProvider { * Create an options provider with the default options. */ public JavaOptionsProvider() { - options = new ImmutableMap.Builder() - .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) - .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) - .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) - .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) - .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) - .put(CodegenConstants.ARTIFACT_URL, ARTIFACT_URL_VALUE) - .put(CodegenConstants.ARTIFACT_DESCRIPTION, ARTIFACT_DESCRIPTION_VALUE) - .put(CodegenConstants.SCM_CONNECTION, SCM_CONNECTION_VALUE) - .put(CodegenConstants.SCM_DEVELOPER_CONNECTION, SCM_DEVELOPER_CONNECTION_VALUE) - .put(CodegenConstants.SCM_URL, SCM_URL_VALUE) - .put(CodegenConstants.DEVELOPER_NAME, DEVELOPER_NAME_VALUE) - .put(CodegenConstants.DEVELOPER_EMAIL, DEVELOPER_EMAIL_VALUE) - .put(CodegenConstants.DEVELOPER_ORGANIZATION, DEVELOPER_ORGANIZATION_VALUE) - .put(CodegenConstants.DEVELOPER_ORGANIZATION_URL, DEVELOPER_ORGANIZATION_URL_VALUE) - .put(CodegenConstants.LICENSE_NAME, LICENSE_NAME_VALUE) - .put(CodegenConstants.LICENSE_URL, LICENSE_URL_VALUE) - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE) - .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) - .put(JavaClientCodegen.FULL_JAVA_UTIL, FULL_JAVA_UTIL_VALUE) - .put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true") - .put(JavaClientCodegen.DATE_LIBRARY, "joda") - .put("hideGenerationTimestamp", "true") - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - //.put("supportJava6", "true") - .build(); + options = + new ImmutableMap.Builder() + .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) + .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) + .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) + .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.ARTIFACT_URL, ARTIFACT_URL_VALUE) + .put(CodegenConstants.ARTIFACT_DESCRIPTION, ARTIFACT_DESCRIPTION_VALUE) + .put(CodegenConstants.SCM_CONNECTION, SCM_CONNECTION_VALUE) + .put(CodegenConstants.SCM_DEVELOPER_CONNECTION, + SCM_DEVELOPER_CONNECTION_VALUE) + .put(CodegenConstants.SCM_URL, SCM_URL_VALUE) + .put(CodegenConstants.DEVELOPER_NAME, DEVELOPER_NAME_VALUE) + .put(CodegenConstants.DEVELOPER_EMAIL, DEVELOPER_EMAIL_VALUE) + .put(CodegenConstants.DEVELOPER_ORGANIZATION, DEVELOPER_ORGANIZATION_VALUE) + .put(CodegenConstants.DEVELOPER_ORGANIZATION_URL, + DEVELOPER_ORGANIZATION_URL_VALUE) + .put(CodegenConstants.LICENSE_NAME, LICENSE_NAME_VALUE) + .put(CodegenConstants.LICENSE_URL, LICENSE_URL_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE) + .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) + .put(JavaClientCodegen.FULL_JAVA_UTIL, FULL_JAVA_UTIL_VALUE) + .put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true") + .put(JavaClientCodegen.DATE_LIBRARY, "joda") + .put("hideGenerationTimestamp", "true") + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, + ALLOW_UNICODE_IDENTIFIERS_VALUE) + // .put("supportJava6", "true") + .build(); } /** * Use the default options, but override the ones found in additionalOptions. */ public JavaOptionsProvider(Map additionalOptions) { - options = new ImmutableMap.Builder() - .putAll(options) - .putAll(additionalOptions) - .build(); + options = + new ImmutableMap.Builder().putAll(options) + .putAll(additionalOptions).build(); } @Override diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaResteasyServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaResteasyServerOptionsProvider.java index eae8a6dcccf..e99984d49d6 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaResteasyServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaResteasyServerOptionsProvider.java @@ -9,13 +9,13 @@ import io.swagger.codegen.languages.JavaResteasyServerCodegen; public class JavaResteasyServerOptionsProvider extends JavaOptionsProvider { - + public static final String GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR = "true"; public static final String IMPL_FOLDER_VALUE = "src/main/java"; - + public static final String USE_BEANVALIDATION = "true"; - + @Override public boolean isServer() { return true; @@ -28,19 +28,20 @@ public String getLanguage() { @Override public Map createOptions() { - - Map parentOptions = super.createOptions(); - - ImmutableMap.Builder builder = new ImmutableMap.Builder() - .putAll(parentOptions); - + + Map parentOptions = super.createOptions(); + + ImmutableMap.Builder builder = + new ImmutableMap.Builder().putAll(parentOptions); + builder.put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE); builder.put("title", "Test title"); - - builder.put(JavaCXFServerCodegen.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); + + builder.put(JavaCXFServerCodegen.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, + GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); builder.put(JavaResteasyServerCodegen.USE_BEANVALIDATION, USE_BEANVALIDATION); return builder.build(); - + } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java index 02f1f102ed4..313bfd11a7e 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java @@ -18,11 +18,12 @@ public class JavaScriptOptionsProvider implements OptionsProvider { public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String SOURCE_FOLDER_VALUE = "src/main/javascript"; public static final String LOCAL_PREFIX_VALUE = "_"; -// public static final String SERIALIZABLE_MODEL_VALUE = "false"; + // public static final String SERIALIZABLE_MODEL_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String PROJECT_NAME_VALUE = "JavaScript Client Test"; public static final String MODULE_NAME_VALUE = "JavaScriptClient"; - public static final String PROJECT_DESCRIPTION_VALUE = "Tests JavaScript code generator options"; + public static final String PROJECT_DESCRIPTION_VALUE = + "Tests JavaScript code generator options"; public static final String PROJECT_VERSION_VALUE = "1.0.0"; public static final String PROJECT_LICENSE_NAME_VALUE = "Apache"; public static final String USE_PROMISES_VALUE = "true"; @@ -39,40 +40,41 @@ public class JavaScriptOptionsProvider implements OptionsProvider { */ public JavaScriptOptionsProvider() { // Commented generic options not yet supported by JavaScript codegen. - options = new ImmutableMap.Builder() - .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) - .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) - .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) -// .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) -// .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) -// .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE) -// .put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true") - .put(JavascriptClientCodegen.PROJECT_NAME, PROJECT_NAME_VALUE) - .put(JavascriptClientCodegen.MODULE_NAME, MODULE_NAME_VALUE) - .put(JavascriptClientCodegen.PROJECT_DESCRIPTION, PROJECT_DESCRIPTION_VALUE) - .put(JavascriptClientCodegen.PROJECT_VERSION, PROJECT_VERSION_VALUE) - .put(JavascriptClientCodegen.PROJECT_LICENSE_NAME, PROJECT_LICENSE_NAME_VALUE) - .put(JavascriptClientCodegen.USE_PROMISES, USE_PROMISES_VALUE) - .put(JavascriptClientCodegen.USE_INHERITANCE, USE_INHERITANCE_VALUE) - .put(JavascriptClientCodegen.EMIT_MODEL_METHODS, EMIT_MODEL_METHODS_VALUE) - .put(JavascriptClientCodegen.EMIT_JS_DOC, EMIT_JS_DOC_VALUE) - .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) - .build(); + options = + new ImmutableMap.Builder() + .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) + .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + // .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) + // .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) + // .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE) + // .put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true") + .put(JavascriptClientCodegen.PROJECT_NAME, PROJECT_NAME_VALUE) + .put(JavascriptClientCodegen.MODULE_NAME, MODULE_NAME_VALUE) + .put(JavascriptClientCodegen.PROJECT_DESCRIPTION, PROJECT_DESCRIPTION_VALUE) + .put(JavascriptClientCodegen.PROJECT_VERSION, PROJECT_VERSION_VALUE) + .put(JavascriptClientCodegen.PROJECT_LICENSE_NAME, + PROJECT_LICENSE_NAME_VALUE) + .put(JavascriptClientCodegen.USE_PROMISES, USE_PROMISES_VALUE) + .put(JavascriptClientCodegen.USE_INHERITANCE, USE_INHERITANCE_VALUE) + .put(JavascriptClientCodegen.EMIT_MODEL_METHODS, EMIT_MODEL_METHODS_VALUE) + .put(JavascriptClientCodegen.EMIT_JS_DOC, EMIT_JS_DOC_VALUE) + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, + ALLOW_UNICODE_IDENTIFIERS_VALUE).build(); } /** * Use the default options, but override the ones found in additionalOptions. */ public JavaScriptOptionsProvider(Map additionalOptions) { - options = new ImmutableMap.Builder() - .putAll(options) - .putAll(additionalOptions) - .build(); + options = + new ImmutableMap.Builder().putAll(options) + .putAll(additionalOptions).build(); } @Override diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java index 3aeebceef90..cc8c02633bb 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java @@ -15,14 +15,17 @@ public class JaxRSServerOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String GROUP_ID_VALUE = "io.swagger.test"; public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; - public static final String ARTIFACT_URL_VALUE = "https://github.com/swagger-api/swagger-codegen"; + public static final String ARTIFACT_URL_VALUE = + "https://github.com/swagger-api/swagger-codegen"; public static final String ARTIFACT_DESCRIPTION_VALUE = "Swagger Java Client Test"; public static final String DEVELOPER_NAME_VALUE = "Swagger"; public static final String DEVELOPER_EMAIL_VALUE = "apiteam@swagger.io"; public static final String DEVELOPER_ORGANIZATION_VALUE = "Swagger"; public static final String DEVELOPER_ORGANIZATION_URL_VALUE = "http://swagger.io"; - public static final String SCM_CONNECTION_VALUE = "scm:git:git@github.com:swagger-api/swagger-codegen.git"; - public static final String SCM_DEVELOPER_CONNECTION_VALUE = "scm:git:git@github.com:swagger-api/swagger-codegen.git"; + public static final String SCM_CONNECTION_VALUE = + "scm:git:git@github.com:swagger-api/swagger-codegen.git"; + public static final String SCM_DEVELOPER_CONNECTION_VALUE = + "scm:git:git@github.com:swagger-api/swagger-codegen.git"; public static final String SCM_URL_VALUE = "https://github.com/swagger-api/swagger-codegen"; public static final String LICENSE_NAME_VALUE = "Apache License, Version 2.0"; public static final String LICENSE_URL_VALUE = "http://www.apache.org/licenses/LICENSE-2.0"; @@ -53,38 +56,40 @@ public String getLanguage() { public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); builder.put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE) - .put(JavaClientCodegen.DATE_LIBRARY, "joda") //java.lang.IllegalArgumentException: Multiple entries with same key: dateLibrary=joda and dateLibrary=joda - .put(JavaClientCodegen.SUPPORT_JAVA6, "false") - .put("title", "Test title") - .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) - .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) - .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) - .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) - .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) - .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) - .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) - .put(CodegenConstants.ARTIFACT_URL, ARTIFACT_URL_VALUE) - .put(CodegenConstants.ARTIFACT_DESCRIPTION, ARTIFACT_DESCRIPTION_VALUE) - .put(CodegenConstants.SCM_CONNECTION, SCM_CONNECTION_VALUE) - .put(CodegenConstants.SCM_DEVELOPER_CONNECTION, SCM_DEVELOPER_CONNECTION_VALUE) - .put(CodegenConstants.SCM_URL, SCM_URL_VALUE) - .put(CodegenConstants.DEVELOPER_NAME, DEVELOPER_NAME_VALUE) - .put(CodegenConstants.DEVELOPER_EMAIL, DEVELOPER_EMAIL_VALUE) - .put(CodegenConstants.DEVELOPER_ORGANIZATION, DEVELOPER_ORGANIZATION_VALUE) - .put(CodegenConstants.DEVELOPER_ORGANIZATION_URL, DEVELOPER_ORGANIZATION_URL_VALUE) - .put(CodegenConstants.LICENSE_NAME, LICENSE_NAME_VALUE) - .put(CodegenConstants.LICENSE_URL, LICENSE_URL_VALUE) - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE) - .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) - .put(JavaClientCodegen.FULL_JAVA_UTIL, FULL_JAVA_UTIL_VALUE) - .put(CodegenConstants.LIBRARY, JAXRS_DEFAULT_LIBRARY_VALUE) - .put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true") - //.put(JavaClientCodegen.DATE_LIBRARY, "joda") - .put("hideGenerationTimestamp", "true") - .put(JavaCXFServerCodegen.USE_BEANVALIDATION, USE_BEANVALIDATION) - .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE); + .put(JavaClientCodegen.DATE_LIBRARY, "joda") + // java.lang.IllegalArgumentException: Multiple entries with same key: + // dateLibrary=joda and dateLibrary=joda + .put(JavaClientCodegen.SUPPORT_JAVA6, "false") + .put("title", "Test title") + .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) + .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) + .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) + .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.ARTIFACT_URL, ARTIFACT_URL_VALUE) + .put(CodegenConstants.ARTIFACT_DESCRIPTION, ARTIFACT_DESCRIPTION_VALUE) + .put(CodegenConstants.SCM_CONNECTION, SCM_CONNECTION_VALUE) + .put(CodegenConstants.SCM_DEVELOPER_CONNECTION, SCM_DEVELOPER_CONNECTION_VALUE) + .put(CodegenConstants.SCM_URL, SCM_URL_VALUE) + .put(CodegenConstants.DEVELOPER_NAME, DEVELOPER_NAME_VALUE) + .put(CodegenConstants.DEVELOPER_EMAIL, DEVELOPER_EMAIL_VALUE) + .put(CodegenConstants.DEVELOPER_ORGANIZATION, DEVELOPER_ORGANIZATION_VALUE) + .put(CodegenConstants.DEVELOPER_ORGANIZATION_URL, DEVELOPER_ORGANIZATION_URL_VALUE) + .put(CodegenConstants.LICENSE_NAME, LICENSE_NAME_VALUE) + .put(CodegenConstants.LICENSE_URL, LICENSE_URL_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE) + .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) + .put(JavaClientCodegen.FULL_JAVA_UTIL, FULL_JAVA_UTIL_VALUE) + .put(CodegenConstants.LIBRARY, JAXRS_DEFAULT_LIBRARY_VALUE) + .put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true") + // .put(JavaClientCodegen.DATE_LIBRARY, "joda") + .put("hideGenerationTimestamp", "true") + .put(JavaCXFServerCodegen.USE_BEANVALIDATION, USE_BEANVALIDATION) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE); return builder.build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/LumenServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/LumenServerOptionsProvider.java index eefe050e708..dfc4297acd9 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/LumenServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/LumenServerOptionsProvider.java @@ -30,8 +30,10 @@ public String getLanguage() { @Override public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) - .put(AbstractPhpCodegen.VARIABLE_NAMING_CONVENTION, VARIABLE_NAMING_CONVENTION_VALUE) + return builder + .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(AbstractPhpCodegen.VARIABLE_NAMING_CONVENTION, + VARIABLE_NAMING_CONVENTION_VALUE) .put(AbstractPhpCodegen.PACKAGE_PATH, PACKAGE_PATH_VALUE) .put(AbstractPhpCodegen.SRC_BASE_PATH, SRC_BASE_PATH_VALUE) .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NancyFXServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NancyFXServerOptionsProvider.java index 950e92a5a91..94407a24d8c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NancyFXServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NancyFXServerOptionsProvider.java @@ -23,12 +23,9 @@ public Map createOptions() { final ImmutableMap.Builder builder = ImmutableMap.builder(); return builder.put(PACKAGE_NAME, PACKAGE_NAME_VALUE) .put(PACKAGE_VERSION, PACKAGE_VERSION_VALUE) - .put(SOURCE_FOLDER, SOURCE_FOLDER_VALUE) - .put(SORT_PARAMS_BY_REQUIRED_FLAG, "true") - .put(USE_DATETIME_OFFSET, "true") - .put(USE_COLLECTION, "false") - .put(RETURN_ICOLLECTION, "false") - .put(INTERFACE_PREFIX, "X") + .put(SOURCE_FOLDER, SOURCE_FOLDER_VALUE).put(SORT_PARAMS_BY_REQUIRED_FLAG, "true") + .put(USE_DATETIME_OFFSET, "true").put(USE_COLLECTION, "false") + .put(RETURN_ICOLLECTION, "false").put(INTERFACE_PREFIX, "X") .put(ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java index 667fc1c9027..479620005ed 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java @@ -14,7 +14,8 @@ public class ObjcClientOptionsProvider implements OptionsProvider { public static final String POD_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String AUTHOR_NAME_VALUE = "SwaggerObjc"; public static final String AUTHOR_EMAIL_VALUE = "objc@swagger.io"; - public static final String GIT_REPO_URL_VALUE = "https://github.com/swagger-api/swagger-codegen"; + public static final String GIT_REPO_URL_VALUE = + "https://github.com/swagger-api/swagger-codegen"; @Override public String getLanguage() { @@ -31,8 +32,7 @@ public Map createOptions() { .put(ObjcClientCodegen.AUTHOR_EMAIL, AUTHOR_EMAIL_VALUE) .put(ObjcClientCodegen.GIT_REPO_URL, GIT_REPO_URL_VALUE) .put(ObjcClientCodegen.CORE_DATA, CORE_DATA_VALUE) - .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") - .build(); + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true").build(); } @Override diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/OptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/OptionsProvider.java index 5521a78432b..071f96c45c6 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/OptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/OptionsProvider.java @@ -4,6 +4,8 @@ public interface OptionsProvider { String getLanguage(); + Map createOptions(); + boolean isServer(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PerlClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PerlClientOptionsProvider.java index d1a0def86d3..b6f5bea834c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PerlClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PerlClientOptionsProvider.java @@ -24,8 +24,7 @@ public Map createOptions() { .put(PerlClientCodegen.MODULE_VERSION, MODULE_VERSION_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, "true") - .put("hideGenerationTimestamp", "true") - .build(); + .put("hideGenerationTimestamp", "true").build(); } @Override diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java index 7ad1a05752a..1383d5de087 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java @@ -24,8 +24,7 @@ public Map createOptions() { .put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") - .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") - .build(); + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true").build(); } @Override diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java index c75053b84e2..8f24b36397d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java @@ -12,7 +12,7 @@ public String getLanguage() { @Override public Map createOptions() { - //Rails5ServerCodegen doesn't have its own options and base options are cleared + // Rails5ServerCodegen doesn't have its own options and base options are cleared return ImmutableMap.of(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java index d0e6b78e081..374a91e42e6 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java @@ -18,7 +18,7 @@ public class RubyClientOptionsProvider implements OptionsProvider { public static final String GEM_HOMEPAGE_VALUE = "homepage"; public static final String GEM_SUMMARY_VALUE = "summary"; public static final String GEM_DESCRIPTION_VALUE = "description"; - public static final String GEM_AUTHOR_VALUE = "foo"; + public static final String GEM_AUTHOR_VALUE = "foo"; public static final String GEM_AUTHOR_EMAIL_VALUE = "foo"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SinatraServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SinatraServerOptionsProvider.java index d4a830dc203..d3c42c62d40 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SinatraServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SinatraServerOptionsProvider.java @@ -12,7 +12,7 @@ public String getLanguage() { @Override public Map createOptions() { - //SinatraServerCodegen doesn't have its own options and base options are cleared + // SinatraServerCodegen doesn't have its own options and base options are cleared return ImmutableMap.of(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java index 3bad178c416..3236f2e0f2f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java @@ -10,7 +10,7 @@ public class SpringOptionsProvider extends JavaOptionsProvider { public static final String TITLE = "swagger"; public static final String CONFIG_PACKAGE_VALUE = "configPackage"; public static final String BASE_PACKAGE_VALUE = "basePackage"; - public static final String LIBRARY_VALUE = "spring-mvc"; //FIXME hidding value from super class + public static final String LIBRARY_VALUE = "spring-mvc"; // FIXME hidding value from super class public static final String INTERFACE_ONLY = "true"; public static final String DELEGATE_PATTERN = "true"; public static final String SINGLE_CONTENT_TYPES = "true"; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticHtmlOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticHtmlOptionsProvider.java index 423c13f8a4d..8de7f3d68b5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticHtmlOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticHtmlOptionsProvider.java @@ -26,8 +26,7 @@ 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("appName", "Swagger Sample") - .put("appDescription", "A sample swagger server") + .put("appName", "Swagger Sample").put("appDescription", "A sample swagger server") .put("infoUrl", "https://helloreverb.com") .put("infoEmail", "hello@helloreverb.com") .put("licenseInfo", "All rights reserved") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Swift3OptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Swift3OptionsProvider.java index 4e4bed0f826..04138c7b4e2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Swift3OptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Swift3OptionsProvider.java @@ -13,8 +13,9 @@ public class Swift3OptionsProvider implements OptionsProvider { public static final String PROJECT_NAME_VALUE = "Swagger"; public static final String RESPONSE_AS_VALUE = "test"; public static final String UNWRAP_REQUIRED_VALUE = "true"; - public static final String POD_SOURCE_VALUE = "{ :git => 'git@github.com:swagger-api/swagger-mustache.git'," + - " :tag => 'v1.0.0-SNAPSHOT' }"; + public static final String POD_SOURCE_VALUE = + "{ :git => 'git@github.com:swagger-api/swagger-mustache.git'," + + " :tag => 'v1.0.0-SNAPSHOT' }"; public static final String POD_VERSION_VALUE = "v1.0.0-SNAPSHOT"; public static final String POD_AUTHORS_VALUE = "podAuthors"; public static final String POD_SOCIAL_MEDIA_URL_VALUE = "podSocialMediaURL"; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java index 8229e97aee8..49fa02b7906 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java @@ -13,8 +13,9 @@ public class SwiftOptionsProvider implements OptionsProvider { public static final String PROJECT_NAME_VALUE = "Swagger"; public static final String RESPONSE_AS_VALUE = "test"; public static final String UNWRAP_REQUIRED_VALUE = "true"; - public static final String POD_SOURCE_VALUE = "{ :git => 'git@github.com:swagger-api/swagger-mustache.git'," + - " :tag => 'v1.0.0-SNAPSHOT' }"; + public static final String POD_SOURCE_VALUE = + "{ :git => 'git@github.com:swagger-api/swagger-mustache.git'," + + " :tag => 'v1.0.0-SNAPSHOT' }"; public static final String POD_VERSION_VALUE = "v1.0.0-SNAPSHOT"; public static final String POD_AUTHORS_VALUE = "podAuthors"; public static final String POD_SOCIAL_MEDIA_URL_VALUE = "podSocialMediaURL"; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/perl/PerlClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/perl/PerlClientOptionsTest.java index b277acbbe5c..b56c592d448 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/perl/PerlClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/perl/PerlClientOptionsTest.java @@ -25,11 +25,13 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModuleName(PerlClientOptionsProvider.MODULE_NAME_VALUE); - times = 1; - clientCodegen.setModuleVersion(PerlClientOptionsProvider.MODULE_VERSION_VALUE); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setModuleName(PerlClientOptionsProvider.MODULE_NAME_VALUE); + times = 1; + clientCodegen.setModuleVersion(PerlClientOptionsProvider.MODULE_VERSION_VALUE); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java index 76f31deaacd..f2002062ac9 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java @@ -25,31 +25,37 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(PhpClientOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(PhpClientOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(PhpClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setParameterNamingConvention(PhpClientOptionsProvider.VARIABLE_NAMING_CONVENTION_VALUE); - times = 1; - clientCodegen.setInvokerPackage(PhpClientOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setPackagePath(PhpClientOptionsProvider.PACKAGE_PATH_VALUE); - times = 1; - clientCodegen.setSrcBasePath(PhpClientOptionsProvider.SRC_BASE_PATH_VALUE); - times = 1; - clientCodegen.setComposerVendorName(PhpClientOptionsProvider.COMPOSER_VENDOR_NAME_VALUE); - times = 1; - clientCodegen.setGitUserId(PhpClientOptionsProvider.GIT_USER_ID_VALUE); - times = 1; - clientCodegen.setComposerProjectName(PhpClientOptionsProvider.COMPOSER_PROJECT_NAME_VALUE); - times = 1; - clientCodegen.setGitRepoId(PhpClientOptionsProvider.GIT_REPO_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(PhpClientOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setModelPackage(PhpClientOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(PhpClientOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(PhpClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen + .setParameterNamingConvention(PhpClientOptionsProvider.VARIABLE_NAMING_CONVENTION_VALUE); + times = 1; + clientCodegen.setInvokerPackage(PhpClientOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setPackagePath(PhpClientOptionsProvider.PACKAGE_PATH_VALUE); + times = 1; + clientCodegen.setSrcBasePath(PhpClientOptionsProvider.SRC_BASE_PATH_VALUE); + times = 1; + clientCodegen + .setComposerVendorName(PhpClientOptionsProvider.COMPOSER_VENDOR_NAME_VALUE); + times = 1; + clientCodegen.setGitUserId(PhpClientOptionsProvider.GIT_USER_ID_VALUE); + times = 1; + clientCodegen + .setComposerProjectName(PhpClientOptionsProvider.COMPOSER_PROJECT_NAME_VALUE); + times = 1; + clientCodegen.setGitRepoId(PhpClientOptionsProvider.GIT_REPO_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(PhpClientOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java index 0d121315e85..581ba03071e 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java @@ -32,13 +32,11 @@ public class PhpModelTest { @Test(description = "convert a simple php 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()) - .required("id") - .required("name"); + final Model model = + new ModelImpl().description("a sample model").property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()).required("id") + .required("name"); final DefaultCodegen codegen = new PhpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -47,7 +45,7 @@ public void simpleModelTest() { Assert.assertEquals(cm.description, "a sample model"); Assert.assertEquals(cm.vars.size(), 3); // {{imports}} is not used in template - //Assert.assertEquals(cm.imports.size(), 1); + // Assert.assertEquals(cm.imports.size(), 1); final CodegenProperty property1 = cm.vars.get(0); Assert.assertEquals(property1.baseName, "id"); @@ -85,12 +83,10 @@ public void simpleModelTest() { @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 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 PhpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -124,11 +120,12 @@ public void listPropertyTest() { @Test(description = "convert a model with a map property") public void mapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); + final Model model = + new ModelImpl() + .description("a sample model") + .property("translations", + new MapProperty().additionalProperties(new StringProperty())) + .required("id"); final DefaultCodegen codegen = new PhpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -150,9 +147,9 @@ public void mapPropertyTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new PhpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -172,10 +169,9 @@ public void complexPropertyTest() { @Test(description = "convert a model with complex list property") public void complexListProperty() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))); + final Model model = + new ModelImpl().description("a sample model").property("children", + new ArrayProperty().items(new RefProperty("#/definitions/Children"))); final DefaultCodegen codegen = new PhpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -196,10 +192,11 @@ public void complexListProperty() { @Test(description = "convert a model with complex map property") public void complexMapProperty() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new MapProperty() - .additionalProperties(new RefProperty("#/definitions/Children"))); + final Model model = + new ModelImpl().description("a sample model").property( + "children", + new MapProperty().additionalProperties(new RefProperty( + "#/definitions/Children"))); final DefaultCodegen codegen = new PhpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -208,7 +205,8 @@ public void complexMapProperty() { Assert.assertEquals(cm.description, "a sample model"); Assert.assertEquals(cm.vars.size(), 1); // {{imports}} is not used in template - //Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + // Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), + // 1); final CodegenProperty property1 = cm.vars.get(0); Assert.assertEquals(property1.baseName, "children"); @@ -224,9 +222,9 @@ public void complexMapProperty() { @Test(description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Model model = + new ArrayModel().description("an array model").items( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new PhpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -239,9 +237,9 @@ public void arrayModelTest() { @Test(description = "convert an map model") public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + final Model model = + new ModelImpl().description("a map model").additionalProperties( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new PhpClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -250,21 +248,16 @@ public void mapModelTest() { Assert.assertEquals(cm.description, "a map model"); Assert.assertEquals(cm.vars.size(), 0); // {{imports}} is not used in template - //Assert.assertEquals(cm.imports.size(), 2); - //Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + // Assert.assertEquals(cm.imports.size(), 2); + // Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), + // 1); } @DataProvider(name = "modelNames") public static Object[][] primeNumbers() { - return new Object[][] { - {"sample", "Sample"}, - {"sample_name", "SampleName"}, - {"sample__name", "SampleName"}, - {"/sample", "Sample"}, - {"\\sample", "\\Sample"}, - {"sample.name", "SampleName"}, - {"_sample", "Sample"}, - }; + return new Object[][] { {"sample", "Sample"}, {"sample_name", "SampleName"}, + {"sample__name", "SampleName"}, {"/sample", "Sample"}, {"\\sample", "\\Sample"}, + {"sample.name", "SampleName"}, {"_sample", "Sample"},}; } @Test(dataProvider = "modelNames", description = "avoid inner class") @@ -279,11 +272,13 @@ public void modelNameTest(String name, String expectedName) { @Test(description = "test enum array model") public void enumArrayMdoelTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final Swagger model = + new SwaggerParser() + .read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); final DefaultCodegen codegen = new PhpClientCodegen(); final Model definition = model.getDefinitions().get("EnumArrays"); - Property property = definition.getProperties().get("array_enum"); + Property property = definition.getProperties().get("array_enum"); CodegenProperty prope = codegen.fromProperty("array_enum", property); codegen.updateCodegenPropertyEnum(prope); Assert.assertEquals(prope.datatypeWithEnum, "ARRAY_ENUM[]"); @@ -291,10 +286,10 @@ public void enumArrayMdoelTest() { Assert.assertTrue(prope.isEnum); Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList("fish", "crab")); - HashMap fish= new HashMap(); + HashMap fish = new HashMap(); fish.put("name", "FISH"); fish.put("value", "\'fish\'"); - HashMap crab= new HashMap(); + HashMap crab = new HashMap(); crab.put("name", "CRAB"); crab.put("value", "\'crab\'"); Assert.assertEquals(prope.allowableValues.get("enumVars"), Arrays.asList(fish, crab)); @@ -303,18 +298,21 @@ public void enumArrayMdoelTest() { Assert.assertEquals(prope.datatypeWithEnum, "ARRAY_ENUM[]"); Assert.assertEquals(prope.enumName, "ARRAY_ENUM"); Assert.assertTrue(prope.items.isEnum); - Assert.assertEquals(prope.items.allowableValues.get("values"), Arrays.asList("fish", "crab")); + Assert.assertEquals(prope.items.allowableValues.get("values"), + Arrays.asList("fish", "crab")); Assert.assertEquals(prope.items.allowableValues.get("enumVars"), Arrays.asList(fish, crab)); } @Test(description = "test enum model for values (numeric, string, etc)") public void enumMdoelValueTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final Swagger model = + new SwaggerParser() + .read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); final DefaultCodegen codegen = new PhpClientCodegen(); final Model definition = model.getDefinitions().get("Enum_Test"); - Property property = definition.getProperties().get("enum_integer"); + Property property = definition.getProperties().get("enum_integer"); CodegenProperty prope = codegen.fromProperty("enum_integer", property); codegen.updateCodegenPropertyEnum(prope); Assert.assertEquals(prope.datatypeWithEnum, "ENUM_INTEGER"); @@ -336,5 +334,4 @@ public void enumMdoelValueTest() { - } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java index 80fc53ac993..95670810e1a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java @@ -25,13 +25,15 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setPackageName(PythonClientOptionsProvider.PACKAGE_NAME_VALUE); - times = 1; - clientCodegen.setPackageVersion(PythonClientOptionsProvider.PACKAGE_VERSION_VALUE); - times = 1; - clientCodegen.setPackageUrl(PythonClientOptionsProvider.PACKAGE_URL_VALUE); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setPackageName(PythonClientOptionsProvider.PACKAGE_NAME_VALUE); + times = 1; + clientCodegen.setPackageVersion(PythonClientOptionsProvider.PACKAGE_VERSION_VALUE); + times = 1; + clientCodegen.setPackageUrl(PythonClientOptionsProvider.PACKAGE_URL_VALUE); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonTest.java index cde532e6135..e950e014820 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonTest.java @@ -33,32 +33,35 @@ public void modelTest() { final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/v1beta3.json"); final DefaultCodegen codegen = new PythonClientCodegen(); - final CodegenModel simpleName = codegen.fromModel("v1beta3.Binding", swagger.getDefinitions().get("v1beta3.Binding")); + final CodegenModel simpleName = + codegen.fromModel("v1beta3.Binding", swagger.getDefinitions() + .get("v1beta3.Binding")); Assert.assertEquals(simpleName.name, "v1beta3.Binding"); Assert.assertEquals(simpleName.classname, "V1beta3Binding"); Assert.assertEquals(simpleName.classVarName, "v1beta3_binding"); - final CodegenModel compoundName = codegen.fromModel("v1beta3.ComponentStatus", swagger.getDefinitions().get("v1beta3.ComponentStatus")); + final CodegenModel compoundName = + codegen.fromModel("v1beta3.ComponentStatus", + swagger.getDefinitions().get("v1beta3.ComponentStatus")); Assert.assertEquals(compoundName.name, "v1beta3.ComponentStatus"); Assert.assertEquals(compoundName.classname, "V1beta3ComponentStatus"); Assert.assertEquals(compoundName.classVarName, "v1beta3_component_status"); final String path = "/api/v1beta3/namespaces/{namespaces}/bindings"; final Operation operation = swagger.getPaths().get(path).getPost(); - final CodegenOperation codegenOperation = codegen.fromOperation(path, "get", operation, swagger.getDefinitions()); + final CodegenOperation codegenOperation = + codegen.fromOperation(path, "get", operation, swagger.getDefinitions()); Assert.assertEquals(codegenOperation.returnType, "V1beta3Binding"); Assert.assertEquals(codegenOperation.returnBaseType, "V1beta3Binding"); } @Test(description = "convert a simple java 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()) - .required("id") - .required("name"); + final Model model = + new ModelImpl().description("a sample model").property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()).required("id") + .required("name"); final DefaultCodegen codegen = new PythonClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -102,12 +105,10 @@ public void simpleModelTest() { @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 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 PythonClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -142,11 +143,12 @@ public void listPropertyTest() { @Test(description = "convert a model with a map property") public void mapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); + final Model model = + new ModelImpl() + .description("a sample model") + .property("translations", + new MapProperty().additionalProperties(new StringProperty())) + .required("id"); final DefaultCodegen codegen = new PythonClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -168,9 +170,9 @@ public void mapPropertyTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new PythonClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -190,10 +192,9 @@ public void complexPropertyTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new ArrayProperty().items(new RefProperty("#/definitions/Children"))); final DefaultCodegen codegen = new PythonClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -215,10 +216,11 @@ public void complexListPropertyTest() { @Test(description = "convert a model with complex map property") public void complexMapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new MapProperty() - .additionalProperties(new RefProperty("#/definitions/Children"))); + final Model model = + new ModelImpl().description("a sample model").property( + "children", + new MapProperty().additionalProperties(new RefProperty( + "#/definitions/Children"))); final DefaultCodegen codegen = new PythonClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -244,9 +246,9 @@ public void complexMapPropertyTest() { // should not start with 'null'. need help from the community to investigate further @Test(enabled = false, description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Model model = + new ArrayModel().description("an array model").items( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new PythonClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -262,9 +264,9 @@ public void arrayModelTest() { // should not start with 'null'. need help from the community to investigate further @Test(enabled = false, description = "convert an map model") public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + final Model model = + new ModelImpl().description("a map model").additionalProperties( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new PythonClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/qtfivecpp/Qt5CPPOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/qtfivecpp/Qt5CPPOptionsTest.java index 1bc1147cd00..90684d0db3f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/qtfivecpp/Qt5CPPOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/qtfivecpp/Qt5CPPOptionsTest.java @@ -25,9 +25,12 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(Qt5CPPOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(Qt5CPPOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientCodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientCodegenTest.java index bf69f043b54..7bde9b2eece 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientCodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientCodegenTest.java @@ -26,41 +26,44 @@ */ public class RubyClientCodegenTest { - public TemporaryFolder folder = new TemporaryFolder(); + public TemporaryFolder folder = new TemporaryFolder(); - @BeforeMethod - public void setUp() throws Exception { - folder.create(); - } + @BeforeMethod + public void setUp() throws Exception { + folder.create(); + } - @AfterMethod - public void tearDown() throws Exception { - folder.delete(); - } + @AfterMethod + public void tearDown() throws Exception { + folder.delete(); + } - @Test - public void testGenerateRubyClientWithHtmlEntity() throws Exception { - final File output = folder.getRoot(); + @Test + public void testGenerateRubyClientWithHtmlEntity() throws Exception { + final File output = folder.getRoot(); - final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/pathWithHtmlEntity.yaml"); - CodegenConfig codegenConfig = new RubyClientCodegen(); - codegenConfig.setOutputDir(output.getAbsolutePath()); + final Swagger swagger = + new SwaggerParser().read("src/test/resources/2_0/pathWithHtmlEntity.yaml"); + CodegenConfig codegenConfig = new RubyClientCodegen(); + codegenConfig.setOutputDir(output.getAbsolutePath()); - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); + ClientOptInput clientOptInput = + new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); - boolean apiFileGenerated = false; - for (File file : files) { - if (file.getName().equals("default_api.rb")) { - apiFileGenerated = true; - // Ruby client should set the path unescaped in the api file - assertTrue(FileUtils.readFileToString(file, StandardCharsets.UTF_8).contains("local_var_path = \"/foo=bar\"")); + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(clientOptInput).generate(); + boolean apiFileGenerated = false; + for (File file : files) { + if (file.getName().equals("default_api.rb")) { + apiFileGenerated = true; + // Ruby client should set the path unescaped in the api file + assertTrue(FileUtils.readFileToString(file, StandardCharsets.UTF_8).contains( + "local_var_path = \"/foo=bar\"")); + } } - } - if (!apiFileGenerated) { - fail("Default api file is not generated!"); - } - } + if (!apiFileGenerated) { + fail("Default api file is not generated!"); + } + } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java index 9bf7eea4c94..1f320bfe783 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java @@ -25,28 +25,31 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setGemName(RubyClientOptionsProvider.GEM_NAME_VALUE); - times = 1; - clientCodegen.setModuleName(RubyClientOptionsProvider.MODULE_NAME_VALUE); - times = 1; - clientCodegen.setGemVersion(RubyClientOptionsProvider.GEM_VERSION_VALUE); - times = 1; - clientCodegen.setGemLicense(RubyClientOptionsProvider.GEM_LICENSE_VALUE); - times = 1; - clientCodegen.setGemRequiredRubyVersion(RubyClientOptionsProvider.GEM_REQUIRED_RUBY_VERSION_VALUE); - times = 1; - clientCodegen.setGemHomepage(RubyClientOptionsProvider.GEM_HOMEPAGE_VALUE); - times = 1; - clientCodegen.setGemDescription(RubyClientOptionsProvider.GEM_DESCRIPTION_VALUE); - times = 1; - clientCodegen.setGemSummary(RubyClientOptionsProvider.GEM_SUMMARY_VALUE); - times = 1; - clientCodegen.setGemAuthor(RubyClientOptionsProvider.GEM_AUTHOR_VALUE); - times = 1; - clientCodegen.setGemAuthorEmail(RubyClientOptionsProvider.GEM_AUTHOR_EMAIL_VALUE); - times = 1; - - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setGemName(RubyClientOptionsProvider.GEM_NAME_VALUE); + times = 1; + clientCodegen.setModuleName(RubyClientOptionsProvider.MODULE_NAME_VALUE); + times = 1; + clientCodegen.setGemVersion(RubyClientOptionsProvider.GEM_VERSION_VALUE); + times = 1; + clientCodegen.setGemLicense(RubyClientOptionsProvider.GEM_LICENSE_VALUE); + times = 1; + clientCodegen + .setGemRequiredRubyVersion(RubyClientOptionsProvider.GEM_REQUIRED_RUBY_VERSION_VALUE); + times = 1; + clientCodegen.setGemHomepage(RubyClientOptionsProvider.GEM_HOMEPAGE_VALUE); + times = 1; + clientCodegen.setGemDescription(RubyClientOptionsProvider.GEM_DESCRIPTION_VALUE); + times = 1; + clientCodegen.setGemSummary(RubyClientOptionsProvider.GEM_SUMMARY_VALUE); + times = 1; + clientCodegen.setGemAuthor(RubyClientOptionsProvider.GEM_AUTHOR_VALUE); + times = 1; + clientCodegen.setGemAuthorEmail(RubyClientOptionsProvider.GEM_AUTHOR_EMAIL_VALUE); + times = 1; + + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java index d03cfee7ee7..bfbc2f4c9d2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java @@ -25,17 +25,21 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(ScalaClientOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(ScalaClientOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(ScalaClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setModelPropertyNaming(ScalaClientOptionsProvider.MODEL_PROPERTY_NAMING); - times = 1; - clientCodegen.setSourceFolder(ScalaClientOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setModelPackage(ScalaClientOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(ScalaClientOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(ScalaClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen + .setModelPropertyNaming(ScalaClientOptionsProvider.MODEL_PROPERTY_NAMING); + times = 1; + clientCodegen.setSourceFolder(ScalaClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java index 95e08c6b362..74f6de1d507 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java @@ -23,13 +23,11 @@ public class ScalaModelTest { @Test(description = "convert a simple scala 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()) - .required("id") - .required("name"); + final Model model = + new ModelImpl().description("a sample model").property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()).required("id") + .required("name"); final DefaultCodegen codegen = new ScalaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -77,12 +75,10 @@ public void simpleModelTest() { @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 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 ScalaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -106,11 +102,12 @@ public void listPropertyTest() { @Test(description = "convert a model with a map property") public void mapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id"); + final Model model = + new ModelImpl() + .description("a sample model") + .property("translations", + new MapProperty().additionalProperties(new StringProperty())) + .required("id"); final DefaultCodegen codegen = new ScalaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -134,9 +131,9 @@ public void mapPropertyTest() { @Test(description = "convert a model with complex properties") public void complexPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")); + final Model model = + new ModelImpl().description("a sample model").property("children", + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new ScalaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -159,10 +156,9 @@ public void complexPropertyTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new ArrayProperty().items(new RefProperty("#/definitions/Children"))); final DefaultCodegen codegen = new ScalaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -187,10 +183,11 @@ public void complexListPropertyTest() { @Test(description = "convert a model with complex map property") public void complexMapPropertyTest() { - final Model model = new ModelImpl() - .description("a sample model") - .property("children", new MapProperty() - .additionalProperties(new RefProperty("#/definitions/Children"))); + final Model model = + new ModelImpl().description("a sample model").property( + "children", + new MapProperty().additionalProperties(new RefProperty( + "#/definitions/Children"))); final DefaultCodegen codegen = new ScalaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -217,9 +214,9 @@ public void complexMapPropertyTest() { @Test(description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Model model = + new ArrayModel().description("an array model").items( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new ScalaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -229,14 +226,15 @@ public void arrayModelTest() { Assert.assertEquals(cm.vars.size(), 0); Assert.assertEquals(cm.parent, "ListBuffer[Children]"); Assert.assertEquals(cm.imports.size(), 2); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("ListBuffer", "Children")).size(), 2); + Assert.assertEquals(Sets + .intersection(cm.imports, Sets.newHashSet("ListBuffer", "Children")).size(), 2); } @Test(description = "convert an map model") public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + final Model model = + new ModelImpl().description("a map model").additionalProperties( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new ScalaClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -246,6 +244,7 @@ public void mapModelTest() { Assert.assertEquals(cm.vars.size(), 0); Assert.assertEquals(cm.parent, "HashMap[String, Children]"); Assert.assertEquals(cm.imports.size(), 2); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("HashMap", "Children")).size(), 2); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("HashMap", "Children")) + .size(), 2); } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java index 53ff0ce48e5..9421a6d6205 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java @@ -25,15 +25,18 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(ScalatraServerOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(ScalatraServerOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(ScalatraServerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setSourceFolder(ScalatraServerOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setModelPackage(ScalatraServerOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(ScalatraServerOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(ScalatraServerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setSourceFolder(ScalatraServerOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/silex/SilexServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/silex/SilexServerOptionsTest.java index c32ef13fd82..5fd78341b94 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/silex/SilexServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/silex/SilexServerOptionsTest.java @@ -25,9 +25,12 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SilexServerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(SilexServerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/sinatra/SinatraServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/sinatra/SinatraServerOptionsTest.java index 56e81aba251..b7290fad7a5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/sinatra/SinatraServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/sinatra/SinatraServerOptionsTest.java @@ -25,7 +25,9 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - }}; + new Expectations(clientCodegen) { + { + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/slim/SlimFrameworkServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/slim/SlimFrameworkServerOptionsTest.java index 554f4ca0db5..14fee5b3d72 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/slim/SlimFrameworkServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/slim/SlimFrameworkServerOptionsTest.java @@ -25,9 +25,12 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SlimFrameworkServerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(SlimFrameworkServerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java index b69f958aef5..905e9cde6e2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java @@ -25,54 +25,63 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(SpringOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(SpringOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SpringOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(SpringOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(SpringOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(SpringOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(SpringOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setSourceFolder(SpringOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(SpringOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen.setSerializableModel(Boolean.valueOf(SpringOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - clientCodegen.setLibrary(SpringOptionsProvider.LIBRARY_VALUE); - times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(SpringOptionsProvider.FULL_JAVA_UTIL_VALUE)); - times = 1; - clientCodegen.setTitle(SpringOptionsProvider.TITLE); - times = 1; - clientCodegen.setConfigPackage(SpringOptionsProvider.CONFIG_PACKAGE_VALUE); - times = 1; - clientCodegen.setBasePackage(SpringOptionsProvider.BASE_PACKAGE_VALUE); - times = 1; - clientCodegen.setInterfaceOnly(Boolean.valueOf(SpringOptionsProvider.INTERFACE_ONLY)); - times = 1; - clientCodegen.setDelegatePattern(Boolean.valueOf(SpringOptionsProvider.DELEGATE_PATTERN)); - times = 1; - clientCodegen.setSingleContentTypes(Boolean.valueOf(SpringOptionsProvider.SINGLE_CONTENT_TYPES)); - times = 1; - clientCodegen.setJava8(Boolean.valueOf(SpringOptionsProvider.JAVA_8)); - times = 1; - clientCodegen.setAsync(Boolean.valueOf(SpringOptionsProvider.ASYNC)); - times = 1; - clientCodegen.setResponseWrapper(SpringOptionsProvider.RESPONSE_WRAPPER); - times = 1; - clientCodegen.setUseTags(Boolean.valueOf(SpringOptionsProvider.USE_TAGS)); - times = 1; - clientCodegen.setUseBeanValidation(Boolean.valueOf(SpringOptionsProvider.USE_BEANVALIDATION)); - times = 1; + new Expectations(clientCodegen) { + { + clientCodegen.setModelPackage(SpringOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(SpringOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(SpringOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setInvokerPackage(SpringOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(SpringOptionsProvider.GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(SpringOptionsProvider.ARTIFACT_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(SpringOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen.setSourceFolder(SpringOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setLocalVariablePrefix(SpringOptionsProvider.LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean + .valueOf(SpringOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + times = 1; + clientCodegen.setLibrary(SpringOptionsProvider.LIBRARY_VALUE); + times = 1; + clientCodegen.setFullJavaUtil(Boolean + .valueOf(SpringOptionsProvider.FULL_JAVA_UTIL_VALUE)); + times = 1; + clientCodegen.setTitle(SpringOptionsProvider.TITLE); + times = 1; + clientCodegen.setConfigPackage(SpringOptionsProvider.CONFIG_PACKAGE_VALUE); + times = 1; + clientCodegen.setBasePackage(SpringOptionsProvider.BASE_PACKAGE_VALUE); + times = 1; + clientCodegen.setInterfaceOnly(Boolean + .valueOf(SpringOptionsProvider.INTERFACE_ONLY)); + times = 1; + clientCodegen.setDelegatePattern(Boolean + .valueOf(SpringOptionsProvider.DELEGATE_PATTERN)); + times = 1; + clientCodegen.setSingleContentTypes(Boolean + .valueOf(SpringOptionsProvider.SINGLE_CONTENT_TYPES)); + times = 1; + clientCodegen.setJava8(Boolean.valueOf(SpringOptionsProvider.JAVA_8)); + times = 1; + clientCodegen.setAsync(Boolean.valueOf(SpringOptionsProvider.ASYNC)); + times = 1; + clientCodegen.setResponseWrapper(SpringOptionsProvider.RESPONSE_WRAPPER); + times = 1; + clientCodegen.setUseTags(Boolean.valueOf(SpringOptionsProvider.USE_TAGS)); + times = 1; + clientCodegen.setUseBeanValidation(Boolean + .valueOf(SpringOptionsProvider.USE_BEANVALIDATION)); + times = 1; - }}; + } + }; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticDocOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticDocOptionsTest.java index 9f9f6da27a1..e7d027a2ee1 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticDocOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticDocOptionsTest.java @@ -25,9 +25,12 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(StaticDocOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(StaticDocOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlOptionsTest.java index 91ba418fb91..974734ee4cf 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlOptionsTest.java @@ -25,9 +25,12 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(StaticHtmlOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(StaticHtmlOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlTagsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlTagsTest.java index 0ba3d9e2fee..7ce960a8bee 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlTagsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlTagsTest.java @@ -44,90 +44,92 @@ public void setUp() throws Exception { public void tearDown() throws Exception { folder.delete(); } - - @Test + + @Test public void testApiTags() throws Exception { final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/petstore.json"); final int maxTagsToTest = 2; // how to flip it randomly from 2 to 1, and shuffle ops? - // if an op has a few tags it will be duplicated here, but it's exactly what we expect in doc + // if an op has a few tags it will be duplicated here, but it's exactly what we expect in + // doc final List expectedOperations = new ArrayList(); - - final String capitalCommatizedTags = pickupFewTagsAndOps(swagger, - maxTagsToTest, expectedOperations); - + + final String capitalCommatizedTags = + pickupFewTagsAndOps(swagger, maxTagsToTest, expectedOperations); + final Collection seenOperations = new ArrayList(); - CodegenConfig codegenConfig = new StaticHtmlGenerator(){ // new StaticDocCodegen(){ - public Map postProcessSupportingFileData(Map objs) { - //System.out.println(getOperations(objs)); - final Collection actualOperations = getOperations(objs); - seenOperations.addAll(actualOperations); - assertEquals(actualOperations.size(), expectedOperations.size(), - "Expectig the same size of ops for -Dapis="+capitalCommatizedTags + - " in fact, actual "+actualOperations+" doesn't seem like expecting " - + expectedOperations); - return objs; - } - }; + CodegenConfig codegenConfig = new StaticHtmlGenerator() { // new StaticDocCodegen(){ + public Map postProcessSupportingFileData( + Map objs) { + // System.out.println(getOperations(objs)); + final Collection actualOperations = getOperations(objs); + seenOperations.addAll(actualOperations); + assertEquals(actualOperations.size(), expectedOperations.size(), + "Expectig the same size of ops for -Dapis=" + capitalCommatizedTags + + " in fact, actual " + actualOperations + + " doesn't seem like expecting " + expectedOperations); + return objs; + } + }; codegenConfig.setOutputDir(folder.getRoot().getAbsolutePath()); - - ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger) - .config(codegenConfig); + + ClientOptInput clientOptInput = + new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); final String apisBackup = System.setProperty("apis", capitalCommatizedTags); try { DefaultGenerator gen = new DefaultGenerator(); gen.opts(clientOptInput); gen.generate(); - assertEquals(seenOperations.isEmpty(), false, + assertEquals(seenOperations.isEmpty(), false, "something has been changed in code and now code bypass the mock above..."); } finally { - if (apisBackup!=null) { + if (apisBackup != null) { System.setProperty("apis", apisBackup); - }else{ - System.clearProperty("apis"); + } else { + System.clearProperty("apis"); } } } - protected String pickupFewTagsAndOps(final Swagger swagger, - final int maxTagsToTest, final Collection expectedOperations) { + protected String pickupFewTagsAndOps(final Swagger swagger, final int maxTagsToTest, + final Collection expectedOperations) { Set expectedTags = new HashSet(); - for ( Path path:swagger.getPaths().values() ) { - for ( Operation op : path.getOperations() ) { - for ( String tag : op.getTags() ) { + for (Path path : swagger.getPaths().values()) { + for (Operation op : path.getOperations()) { + for (String tag : op.getTags()) { if (expectedTags.size() < maxTagsToTest) { expectedTags.add(tag); expectedOperations.add(op); } else { - if ( expectedTags.contains(tag) ) { + if (expectedTags.contains(tag)) { expectedOperations.add(op); } } } } } - - final String capitalCommatizedTags = StringUtils.join( - Lists.transform(Lists.newArrayList(expectedTags), - new Function() { - @Nullable - @Override - public String apply(final String input) { - return StringUtils.capitalize(input); - } - }), ","); + + final String capitalCommatizedTags = + StringUtils.join(Lists.transform(Lists.newArrayList(expectedTags), + new Function() { + @Nullable + @Override + public String apply(final String input) { + return StringUtils.capitalize(input); + } + }), ","); return capitalCommatizedTags; } - - @SuppressWarnings({ "rawtypes", "unchecked" }) + + @SuppressWarnings({"rawtypes", "unchecked"}) protected static Collection getOperations(Map objs) { final ArrayList rez = new ArrayList(); - final Map apiInfo = (Map)objs.get("apiInfo"); - for(Object apiElem : ((List)apiInfo.get("apis"))){ + final Map apiInfo = (Map) objs.get("apiInfo"); + for (Object apiElem : ((List) apiInfo.get("apis"))) { Map api = (Map) apiElem; - rez.addAll( (Collection) // what if the same op goes on two tags?? - ((Map)api.get("operations")).get("operation")); + rez.addAll((Collection) // what if the same op goes on two tags?? + ((Map) api.get("operations")).get("operation")); } return rez; } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swagger/SwaggerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swagger/SwaggerOptionsTest.java index ba142d314e9..b6572355cc3 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swagger/SwaggerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swagger/SwaggerOptionsTest.java @@ -25,9 +25,12 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SwaggerOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(SwaggerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swaggeryaml/SwaggerYamlOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swaggeryaml/SwaggerYamlOptionsTest.java index 0ed24654f0a..6c0778f9d2a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swaggeryaml/SwaggerYamlOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swaggeryaml/SwaggerYamlOptionsTest.java @@ -25,9 +25,12 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SwaggerYamlOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(SwaggerYamlOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java index 62a6fb58482..da96e9456b0 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java @@ -56,7 +56,8 @@ public void testSlash() throws Exception { @Test(description = "returns NSData when response format is binary") public void binaryDataTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); + final Swagger model = + new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); final DefaultCodegen codegen = new SwiftCodegen(); final String path = "/tests/binaryResponse"; final Operation p = model.getPaths().get(path).getPost(); @@ -76,7 +77,8 @@ public void testDefaultPodAuthors() throws Exception { swiftCodegen.processOpts(); // Then - final String podAuthors = (String) swiftCodegen.additionalProperties().get(SwiftCodegen.POD_AUTHORS); + final String podAuthors = + (String) swiftCodegen.additionalProperties().get(SwiftCodegen.POD_AUTHORS); Assert.assertEquals(podAuthors, SwiftCodegen.DEFAULT_POD_AUTHORS); } @@ -90,8 +92,9 @@ public void testPodAuthors() throws Exception { swiftCodegen.processOpts(); // Then - final String podAuthors = (String) swiftCodegen.additionalProperties().get(SwiftCodegen.POD_AUTHORS); + final String podAuthors = + (String) swiftCodegen.additionalProperties().get(SwiftCodegen.POD_AUTHORS); Assert.assertEquals(podAuthors, swaggerDevs); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java index 43f7103f312..bd7816cf33f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java @@ -13,17 +13,14 @@ public class SwiftModelTest { @Test(description = "convert a simple java 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("binary", new BinaryProperty()) - .property("byte", new ByteArrayProperty()) - .property("uuid", new UUIDProperty()) - .required("id") - .required("name") - .discriminator("test"); + final Model model = + new ModelImpl().description("a sample model").property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .property("binary", new BinaryProperty()) + .property("byte", new ByteArrayProperty()) + .property("uuid", new UUIDProperty()).required("id").required("name") + .discriminator("test"); final DefaultCodegen codegen = new SwiftCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -31,7 +28,7 @@ public void simpleModelTest() { Assert.assertEquals(cm.classname, "Sample"); Assert.assertEquals(cm.description, "a sample model"); Assert.assertEquals(cm.vars.size(), 6); - Assert.assertEquals(cm.discriminator,"test"); + Assert.assertEquals(cm.discriminator, "test"); final CodegenProperty property1 = cm.vars.get(0); Assert.assertEquals(property1.baseName, "id"); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftOptionsTest.java index 7b8ccb61632..74511b93d32 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftOptionsTest.java @@ -25,15 +25,19 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SwiftOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setProjectName(SwiftOptionsProvider.PROJECT_NAME_VALUE); - times = 1; - clientCodegen.setResponseAs(SwiftOptionsProvider.RESPONSE_AS_VALUE.split(",")); - times = 1; - clientCodegen.setUnwrapRequired(Boolean.valueOf(SwiftOptionsProvider.UNWRAP_REQUIRED_VALUE)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(SwiftOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setProjectName(SwiftOptionsProvider.PROJECT_NAME_VALUE); + times = 1; + clientCodegen.setResponseAs(SwiftOptionsProvider.RESPONSE_AS_VALUE.split(",")); + times = 1; + clientCodegen.setUnwrapRequired(Boolean + .valueOf(SwiftOptionsProvider.UNWRAP_REQUIRED_VALUE)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3CodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3CodegenTest.java index 6fd6afa66f2..f5e5835871f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3CodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3CodegenTest.java @@ -65,7 +65,8 @@ public void testLowercaseWithUnderscore() throws Exception { @Test(description = "returns NSData when response format is binary") public void binaryDataTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); + final Swagger model = + new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); final DefaultCodegen codegen = new Swift3Codegen(); final String path = "/tests/binaryResponse"; final Operation p = model.getPaths().get(path).getPost(); @@ -85,7 +86,8 @@ public void testDefaultPodAuthors() throws Exception { swiftCodegen.processOpts(); // Then - final String podAuthors = (String) swiftCodegen.additionalProperties().get(Swift3Codegen.POD_AUTHORS); + final String podAuthors = + (String) swiftCodegen.additionalProperties().get(Swift3Codegen.POD_AUTHORS); Assert.assertEquals(podAuthors, Swift3Codegen.DEFAULT_POD_AUTHORS); } @@ -99,8 +101,9 @@ public void testPodAuthors() throws Exception { swiftCodegen.processOpts(); // Then - final String podAuthors = (String) swiftCodegen.additionalProperties().get(Swift3Codegen.POD_AUTHORS); + final String podAuthors = + (String) swiftCodegen.additionalProperties().get(Swift3Codegen.POD_AUTHORS); Assert.assertEquals(podAuthors, swaggerDevs); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3ModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3ModelTest.java index 277d16ad654..86290a61b98 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3ModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3ModelTest.java @@ -15,17 +15,14 @@ public class Swift3ModelTest { @Test(description = "convert a simple java 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("binary", new BinaryProperty()) - .property("byte", new ByteArrayProperty()) - .property("uuid", new UUIDProperty()) - .required("id") - .required("name") - .discriminator("test"); + final Model model = + new ModelImpl().description("a sample model").property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .property("binary", new BinaryProperty()) + .property("byte", new ByteArrayProperty()) + .property("uuid", new UUIDProperty()).required("id").required("name") + .discriminator("test"); final DefaultCodegen codegen = new Swift3Codegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -33,7 +30,7 @@ public void simpleModelTest() { Assert.assertEquals(cm.classname, "Sample"); Assert.assertEquals(cm.description, "a sample model"); Assert.assertEquals(cm.vars.size(), 6); - Assert.assertEquals(cm.discriminator,"test"); + Assert.assertEquals(cm.discriminator, "test"); final CodegenProperty property1 = cm.vars.get(0); Assert.assertEquals(property1.baseName, "id"); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3OptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3OptionsTest.java index ddfc65bc908..5fc40835405 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3OptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3OptionsTest.java @@ -24,15 +24,19 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(Swift3OptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setProjectName(Swift3OptionsProvider.PROJECT_NAME_VALUE); - times = 1; - clientCodegen.setResponseAs(Swift3OptionsProvider.RESPONSE_AS_VALUE.split(",")); - times = 1; - clientCodegen.setUnwrapRequired(Boolean.valueOf(Swift3OptionsProvider.UNWRAP_REQUIRED_VALUE)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(Swift3OptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setProjectName(Swift3OptionsProvider.PROJECT_NAME_VALUE); + times = 1; + clientCodegen.setResponseAs(Swift3OptionsProvider.RESPONSE_AS_VALUE.split(",")); + times = 1; + clientCodegen.setUnwrapRequired(Boolean + .valueOf(Swift3OptionsProvider.UNWRAP_REQUIRED_VALUE)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/AssertFile.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/AssertFile.java index aca2beb2dc5..77d7a273d62 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/AssertFile.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/AssertFile.java @@ -30,14 +30,14 @@ private AssertFile() { } /** - * Asserts that two directories are recursively equal. If they are not, an {@link AssertionError} is thrown with the - * given message.
- * There will be a textual comparison of all files under expected with all files under actual. File attributes will - * not be considered.
+ * Asserts that two directories are recursively equal. If they are not, an + * {@link AssertionError} is thrown with the given message.
+ * There will be a textual comparison of all files under expected with all files under actual. + * File attributes will not be considered.
* Missing or additional files are considered an error.
* * @param expected Path expected directory - * @param actual Path actual directory + * @param actual Path actual directory */ public static void assertPathEqualsRecursively(final Path expected, final Path actual) { Assert.assertNotNull(expected); @@ -48,24 +48,28 @@ public static void assertPathEqualsRecursively(final Path expected, final Path a Files.walkFileTree(expected, new FileVisitor() { @Override - public FileVisitResult preVisitDirectory(Path expectedDir, BasicFileAttributes attrs) throws IOException { - Path relativeExpectedDir = absoluteExpected.relativize(expectedDir.toAbsolutePath()); + public FileVisitResult preVisitDirectory(Path expectedDir, BasicFileAttributes attrs) + throws IOException { + Path relativeExpectedDir = + absoluteExpected.relativize(expectedDir.toAbsolutePath()); Path actualDir = absoluteActual.resolve(relativeExpectedDir); if (!Files.exists(actualDir)) { fail(String.format("Directory '%s' is missing.", actualDir)); } - assertEquals(expectedDir.toFile().list(), - actualDir.toFile().list(), - String.format("Directory content of '%s' and '%s' differ.", expectedDir, actualDir)); + assertEquals(expectedDir.toFile().list(), actualDir.toFile().list(), String + .format("Directory content of '%s' and '%s' differ.", expectedDir, + actualDir)); return FileVisitResult.CONTINUE; } @Override - public FileVisitResult visitFile(Path expectedFile, BasicFileAttributes attrs) throws IOException { - Path relativeExpectedFile = absoluteExpected.relativize(expectedFile.toAbsolutePath()); + public FileVisitResult visitFile(Path expectedFile, BasicFileAttributes attrs) + throws IOException { + Path relativeExpectedFile = + absoluteExpected.relativize(expectedFile.toAbsolutePath()); Path actualFile = absoluteActual.resolve(relativeExpectedFile); if (!Files.exists(actualFile)) { @@ -78,13 +82,15 @@ public FileVisitResult visitFile(Path expectedFile, BasicFileAttributes attrs) t } @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { + public FileVisitResult visitFileFailed(Path file, IOException exc) + throws IOException { fail(exc.getMessage()); return FileVisitResult.TERMINATE; } @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + public FileVisitResult postVisitDirectory(Path dir, IOException exc) + throws IOException { return FileVisitResult.CONTINUE; } @@ -97,11 +103,11 @@ public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOEx public static void assertFilesAreEqual(final Path expected, final Path actual) { - if(!Files.isRegularFile(expected)) { + if (!Files.isRegularFile(expected)) { fail("expected: '%s' is not a readable file"); } - if(!Files.isRegularFile(actual)) { + if (!Files.isRegularFile(actual)) { fail("actual: '%s' is not a readable file"); } @@ -110,14 +116,16 @@ public static void assertFilesAreEqual(final Path expected, final Path actual) { List actualLines = Files.readAllLines(actual, Charset.defaultCharset()); Patch diff = DiffUtils.diff(expectedLines, actualLines); List deltas = diff.getDeltas(); - if(!deltas.isEmpty()) { + if (!deltas.isEmpty()) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("files diff:\n"); - stringBuilder.append("\tfile: '").append(expected.toAbsolutePath().toString()).append("' \n"); - stringBuilder.append("\tfile: '").append(actual.toAbsolutePath().toString()).append("' \n"); + stringBuilder.append("\tfile: '").append(expected.toAbsolutePath().toString()) + .append("' \n"); + stringBuilder.append("\tfile: '").append(actual.toAbsolutePath().toString()) + .append("' \n"); stringBuilder.append("\tdiffs:\n"); - for (Delta delta: deltas) { + for (Delta delta : deltas) { stringBuilder.append(delta.toString()).append("\n"); } @@ -129,4 +137,3 @@ public static void assertFilesAreEqual(final Path expected, final Path actual) { } } } - diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/IntegrationTestPathsConfig.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/IntegrationTestPathsConfig.java index 4335c69dd2d..b53d63be298 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/IntegrationTestPathsConfig.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/IntegrationTestPathsConfig.java @@ -4,7 +4,8 @@ import java.nio.file.Paths; public class IntegrationTestPathsConfig { - private static final Path INTEGRATION_TEST_PATH = Paths.get("target/test-classes/integrationtests").toAbsolutePath(); + private static final Path INTEGRATION_TEST_PATH = Paths.get( + "target/test-classes/integrationtests").toAbsolutePath(); private final Path outputPath; private final Path specPath; private final Path expectedPath; @@ -13,7 +14,8 @@ public IntegrationTestPathsConfig(String location) { this(location + "-spec.json", location + "-result", location + "-expected"); } - public IntegrationTestPathsConfig(String specLocation, String outputLocation, String expectedLocation) { + public IntegrationTestPathsConfig(String specLocation, String outputLocation, + String expectedLocation) { outputPath = INTEGRATION_TEST_PATH.resolve(outputLocation); expectedPath = INTEGRATION_TEST_PATH.resolve(expectedLocation); specPath = INTEGRATION_TEST_PATH.resolve(specLocation); @@ -30,4 +32,4 @@ public Path getSpecPath() { public Path getExpectedPath() { return expectedPath; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/tizen/TizenClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/tizen/TizenClientOptionsTest.java index 35262568fa5..5841e306e39 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/tizen/TizenClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/tizen/TizenClientOptionsTest.java @@ -25,9 +25,12 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TizenClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(TizenClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java index c2744cc8258..eb519667ff4 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java @@ -24,13 +24,18 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptFetchClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setModelPropertyNaming(TypeScriptFetchClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); - times = 1; - clientCodegen.setSupportsES6(TypeScriptFetchClientOptionsProvider.SUPPORTS_ES6_VALUE); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(TypeScriptFetchClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen + .setModelPropertyNaming(TypeScriptFetchClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); + times = 1; + clientCodegen + .setSupportsES6(TypeScriptFetchClientOptionsProvider.SUPPORTS_ES6_VALUE); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java index d5125805adb..0b00d91a54b 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java @@ -29,13 +29,11 @@ public class TypeScriptFetchModelTest { @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()) - .required("id") - .required("name"); + final Model model = + new ModelImpl().description("a sample model").property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()).required("id") + .required("name"); final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -77,11 +75,10 @@ public void simpleModelTest() { @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 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 TypeScriptFetchClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -112,9 +109,9 @@ public void listPropertyTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -135,10 +132,9 @@ public void complexPropertyTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new ArrayProperty().items(new RefProperty("#/definitions/Children"))); final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -159,9 +155,9 @@ public void complexListPropertyTest() { @Test(description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Model model = + new ArrayModel().description("an array model").items( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -173,9 +169,9 @@ public void arrayModelTest() { @Test(description = "convert a map model") public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + final Model model = + new ModelImpl().description("a map model").additionalProperties( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -189,11 +185,13 @@ public void mapModelTest() { @Test(description = "test enum array model") public void enumArrayMdoelTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final Swagger model = + new SwaggerParser() + .read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); final Model definition = model.getDefinitions().get("EnumArrays"); - Property property = definition.getProperties().get("array_enum"); + Property property = definition.getProperties().get("array_enum"); CodegenProperty prope = codegen.fromProperty("array_enum", property); codegen.updateCodegenPropertyEnum(prope); Assert.assertEquals(prope.datatypeWithEnum, "Array"); @@ -201,10 +199,10 @@ public void enumArrayMdoelTest() { Assert.assertTrue(prope.isEnum); Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList("fish", "crab")); - HashMap fish= new HashMap(); + HashMap fish = new HashMap(); fish.put("name", "Fish"); fish.put("value", "'fish'"); - HashMap crab= new HashMap(); + HashMap crab = new HashMap(); crab.put("name", "Crab"); crab.put("value", "'crab'"); Assert.assertEquals(prope.allowableValues.get("enumVars"), Arrays.asList(fish, crab)); @@ -213,21 +211,24 @@ public void enumArrayMdoelTest() { Assert.assertEquals(prope.datatypeWithEnum, "Array"); Assert.assertEquals(prope.enumName, "ArrayEnumEnum"); Assert.assertTrue(prope.items.isEnum); - Assert.assertEquals(prope.items.allowableValues.get("values"), Arrays.asList("fish", "crab")); + Assert.assertEquals(prope.items.allowableValues.get("values"), + Arrays.asList("fish", "crab")); Assert.assertEquals(prope.items.allowableValues.get("enumVars"), Arrays.asList(fish, crab)); - //IMPORTANT: these are not final enum values, which may be further updated - //by postProcessModels + // IMPORTANT: these are not final enum values, which may be further updated + // by postProcessModels } @Test(description = "test enum model for values (numeric, string, etc)") public void enumMdoelValueTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + final Swagger model = + new SwaggerParser() + .read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); final Model definition = model.getDefinitions().get("Enum_Test"); - Property property = definition.getProperties().get("enum_integer"); + Property property = definition.getProperties().get("enum_integer"); CodegenProperty prope = codegen.fromProperty("enum_integer", property); codegen.updateCodegenPropertyEnum(prope); Assert.assertEquals(prope.datatypeWithEnum, "EnumIntegerEnum"); @@ -245,8 +246,8 @@ public void enumMdoelValueTest() { minusOne.put("value", "-1"); Assert.assertEquals(prope.allowableValues.get("enumVars"), Arrays.asList(one, minusOne)); - //IMPORTANT: these are not final enum values, which may be further updated - //by postProcessModels + // IMPORTANT: these are not final enum values, which may be further updated + // by postProcessModels } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java index 2a68ab37110..8e46cc2e9d4 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java @@ -25,13 +25,18 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptAngularClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setModelPropertyNaming(TypeScriptAngularClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); - times = 1; - clientCodegen.setSupportsES6(Boolean.valueOf(TypeScriptAngularClientOptionsProvider.SUPPORTS_ES6_VALUE)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(TypeScriptAngularClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen + .setModelPropertyNaming(TypeScriptAngularClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); + times = 1; + clientCodegen.setSupportsES6(Boolean + .valueOf(TypeScriptAngularClientOptionsProvider.SUPPORTS_ES6_VALUE)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java index 438d9c8c488..583002668a0 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java @@ -22,13 +22,11 @@ public class TypeScriptAngularModelTest { @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()) - .required("id") - .required("name"); + final Model model = + new ModelImpl().description("a sample model").property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()).required("id") + .required("name"); final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -70,11 +68,10 @@ public void simpleModelTest() { @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 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 TypeScriptAngularClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -105,9 +102,9 @@ public void listPropertyTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -128,10 +125,9 @@ public void complexPropertyTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new ArrayProperty().items(new RefProperty("#/definitions/Children"))); final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -152,9 +148,9 @@ public void complexListPropertyTest() { @Test(description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Model model = + new ArrayModel().description("an array model").items( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -166,9 +162,9 @@ public void arrayModelTest() { @Test(description = "convert a map model") public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + final Model model = + new ModelImpl().description("a map model").additionalProperties( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -177,6 +173,7 @@ public void mapModelTest() { Assert.assertEquals(cm.description, "a map model"); Assert.assertEquals(cm.vars.size(), 0); Assert.assertEquals(cm.imports.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("models.Children")).size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("models.Children")) + .size(), 1); } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ClientOptionsTest.java index 73ace65a207..a8aad70fc31 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ClientOptionsTest.java @@ -25,13 +25,18 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptAngularClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setModelPropertyNaming(TypeScriptAngularClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); - times = 1; - clientCodegen.setSupportsES6(Boolean.valueOf(TypeScriptAngularClientOptionsProvider.SUPPORTS_ES6_VALUE)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(TypeScriptAngularClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen + .setModelPropertyNaming(TypeScriptAngularClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); + times = 1; + clientCodegen.setSupportsES6(Boolean + .valueOf(TypeScriptAngularClientOptionsProvider.SUPPORTS_ES6_VALUE)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ModelTest.java index 4d6a7dcb3b9..c8257e13976 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ModelTest.java @@ -23,13 +23,11 @@ public class TypeScriptAngular2ModelTest { @Test(description = "convert a simple TypeScript Angular2 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()) - .required("id") - .required("name"); + final Model model = + new ModelImpl().description("a sample model").property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()).required("id") + .required("name"); final DefaultCodegen codegen = new TypeScriptAngular2ClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -71,11 +69,10 @@ public void simpleModelTest() { @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 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 TypeScriptAngular2ClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -106,9 +103,9 @@ public void listPropertyTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new TypeScriptAngular2ClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -129,10 +126,9 @@ public void complexPropertyTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new ArrayProperty().items(new RefProperty("#/definitions/Children"))); final DefaultCodegen codegen = new TypeScriptAngular2ClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -153,9 +149,9 @@ public void complexListPropertyTest() { @Test(description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Model model = + new ArrayModel().description("an array model").items( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new TypeScriptAngular2ClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -167,9 +163,9 @@ public void arrayModelTest() { @Test(description = "convert a map model") public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + final Model model = + new ModelImpl().description("a map model").additionalProperties( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new TypeScriptAngular2ClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -179,6 +175,7 @@ public void mapModelTest() { Assert.assertEquals(cm.vars.size(), 0); Assert.assertEquals(cm.imports.size(), 1); Assert.assertEquals(cm.additionalPropertiesType, "models.Children"); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("models.Children")).size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("models.Children")) + .size(), 1); } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java index 4872e1d419d..674381a8c17 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java @@ -25,13 +25,18 @@ protected CodegenConfig getCodegenConfig() { @SuppressWarnings("unused") @Override protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptNodeClientOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setModelPropertyNaming(TypeScriptNodeClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); - times = 1; - clientCodegen.setSupportsES6(Boolean.valueOf(TypeScriptNodeClientOptionsProvider.SUPPORTS_ES6_VALUE)); - times = 1; - }}; + new Expectations(clientCodegen) { + { + clientCodegen.setSortParamsByRequiredFlag(Boolean + .valueOf(TypeScriptNodeClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen + .setModelPropertyNaming(TypeScriptNodeClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); + times = 1; + clientCodegen.setSupportsES6(Boolean + .valueOf(TypeScriptNodeClientOptionsProvider.SUPPORTS_ES6_VALUE)); + times = 1; + } + }; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java index 18fb8e256bb..51ee5199463 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java @@ -22,13 +22,11 @@ public class TypeScriptNodeModelTest { @Test(description = "convert a simple TypeScript Node 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()) - .required("id") - .required("name"); + final Model model = + new ModelImpl().description("a sample model").property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()).required("id") + .required("name"); final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -70,11 +68,10 @@ public void simpleModelTest() { @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 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 TypeScriptNodeClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -105,9 +102,9 @@ public void listPropertyTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -127,10 +124,9 @@ public void complexPropertyTest() { @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 Model model = + new ModelImpl().description("a sample model").property("children", + new ArrayProperty().items(new RefProperty("#/definitions/Children"))); final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -151,9 +147,9 @@ public void complexListPropertyTest() { @Test(description = "convert an array model") public void arrayModelTest() { - final Model model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")); + final Model model = + new ArrayModel().description("an array model").items( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); @@ -165,9 +161,9 @@ public void arrayModelTest() { @Test(description = "convert a map model") public void mapModelTest() { - final Model model = new ModelImpl() - .description("a map model") - .additionalProperties(new RefProperty("#/definitions/Children")); + final Model model = + new ModelImpl().description("a map model").additionalProperties( + new RefProperty("#/definitions/Children")); final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); final CodegenModel cm = codegen.fromModel("sample", model); diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java index c0af8dc56c9..a48a21355fc 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java @@ -1,17 +1,15 @@ /** * Copyright 2016 SmartBear Software *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package io.swagger.generator; @@ -32,13 +30,13 @@ public void init(ServletConfig config) throws ServletException { DynamicSwaggerConfig bc = new DynamicSwaggerConfig(); bc.setBasePath("/api"); bc.setTitle("Swagger Generator"); - bc.setDescription("This is an online swagger codegen server. You can find out more " + - "at https://github.com/swagger-api/swagger-codegen or on [irc.freenode.net, #swagger](http://swagger.io/irc/)."); + bc.setDescription("This is an online swagger codegen server. You can find out more " + + "at https://github.com/swagger-api/swagger-codegen or on [irc.freenode.net, #swagger](http://swagger.io/irc/)."); bc.setTermsOfServiceUrl("http://swagger.io/terms/"); bc.setContact("apiteam@swagger.io"); bc.setLicense("Apache 2.0"); InputStream stream = getClass().getResourceAsStream("/version.prop"); - if(stream == null) { + if (stream == null) { bc.setVersion("0.0.0"); } else { try { diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java b/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java index cc768bc6d10..35d143d4b7e 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java @@ -21,7 +21,8 @@ public class DynamicSwaggerConfig extends BeanConfig { static { List extensions = Codegen.getExtensions(); for (CodegenConfig config : extensions) { - if (config.getTag().equals(CodegenType.CLIENT) || config.getTag().equals(CodegenType.DOCUMENTATION)) { + if (config.getTag().equals(CodegenType.CLIENT) + || config.getTag().equals(CodegenType.DOCUMENTATION)) { clients.add(config.getName()); } else if (config.getTag().equals(CodegenType.SERVER)) { servers.add(config.getName()); @@ -44,7 +45,7 @@ public Swagger configure(Swagger swagger) { } Operation get = clientPath.getGet(); - if(get != null) { + if (get != null) { framework = get.getParameters().get(0); if (framework instanceof PathParameter) { PathParameter param = (PathParameter) framework; @@ -63,7 +64,7 @@ public Swagger configure(Swagger swagger) { } Operation get = serverPath.getGet(); - if(get != null) { + if (get != null) { framework = get.getParameters().get(0); if (framework instanceof PathParameter) { PathParameter param = (PathParameter) framework; @@ -72,8 +73,6 @@ public Swagger configure(Swagger swagger) { } } - return swagger.info(getInfo()) - .host(getHost()) - .basePath("/api"); + return swagger.info(getInfo()).host(getHost()).basePath("/api"); } } diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java index 11932b26295..ee5df08dade 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java @@ -1,17 +1,15 @@ /** * Copyright 2016 SmartBear Software *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package io.swagger.generator.exception; @@ -25,8 +23,7 @@ public ApiException(int code, String msg) { this.code = code; } - public int getCode() - { + public int getCode() { return code; } } diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java index 2adf97b8bf4..6fa19c94c64 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java @@ -1,17 +1,15 @@ /** * Copyright 2016 SmartBear Software *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package io.swagger.generator.exception; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java index d3747be7d9a..f41d1402a48 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java @@ -1,17 +1,15 @@ /** * Copyright 2016 SmartBear Software *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package io.swagger.generator.exception; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java index 424b9dd2b0a..28d4bdc0b1a 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java @@ -1,17 +1,15 @@ /** * Copyright 2016 SmartBear Software *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package io.swagger.generator.model; @@ -30,8 +28,7 @@ public class ApiResponse { String type; String message; - public ApiResponse() { - } + public ApiResponse() {} public ApiResponse(int code, String message) { this.code = code; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java index f48be6a77da..b1d68a5da17 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java @@ -1,17 +1,15 @@ /** * Copyright 2016 SmartBear Software *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package io.swagger.generator.model; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java index fabde1e3104..439c730c8bd 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java @@ -57,4 +57,4 @@ public SecuritySchemeDefinition getSecurityDefinition() { public void setSecurityDefinition(SecuritySchemeDefinition auth) { this.auth = auth; } -} \ No newline at end of file +} diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java index 33df1bc5071..371f21a9a8c 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java @@ -1,17 +1,15 @@ /** * Copyright 2016 SmartBear Software *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package io.swagger.generator.model; @@ -22,8 +20,7 @@ public class InputOption { private Boolean required; private String defaultValue; - public InputOption() { - } + public InputOption() {} public InputOption(String name, String description, String defaultValue, Boolean required) { this.name = name; diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ResponseCode.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ResponseCode.java index 0fcc5312dac..37f20c9c04c 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ResponseCode.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ResponseCode.java @@ -6,15 +6,15 @@ public class ResponseCode { private String code; private String link; - public ResponseCode() { - } + public ResponseCode() {} public ResponseCode(String code, String link) { setCode(code); setLink(link); } - @ApiModelProperty(value = "File download code", example = "d40029be-eda6-4d62-b1ef-d05e2e91a72a") + @ApiModelProperty(value = "File download code", + example = "d40029be-eda6-4d62-b1ef-d05e2e91a72a") public String getCode() { return code; } @@ -23,7 +23,9 @@ public void setCode(String code) { this.code = code; } - @ApiModelProperty(value = "URL for fetching the generated client", example = "http://generator.swagger.io:80/api/gen/download/d40029be-eda6-4d62-b1ef-d05e2e91a72a") + @ApiModelProperty( + value = "URL for fetching the generated client", + example = "http://generator.swagger.io:80/api/gen/download/d40029be-eda6-4d62-b1ef-d05e2e91a72a") public String getLink() { return link; } @@ -31,4 +33,4 @@ public String getLink() { public void setLink(String link) { this.link = link; } -} \ No newline at end of file +} diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java b/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java index fecd5706361..2435a3170ca 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java @@ -28,7 +28,8 @@ public static Map getOptions(String language) throws ApiExcep try { config = CodegenConfigLoader.forName(language); } catch (Exception e) { - throw new BadRequestException(String.format("Unsupported target %s supplied. %s", language, e)); + throw new BadRequestException(String.format("Unsupported target %s supplied. %s", + language, e)); } Map map = new LinkedHashMap(); for (CliOption option : config.cliOptions()) { @@ -38,8 +39,7 @@ public static Map getOptions(String language) throws ApiExcep } public enum Type { - CLIENT("client"), - SERVER("server"); + CLIENT("client"), SERVER("server"); private String name; @@ -60,37 +60,39 @@ public static String generateServer(String language, GeneratorInput opts) throws return generate(language, opts, Type.SERVER); } - private static String generate(String language, GeneratorInput opts, Type type) throws ApiException { + private static String generate(String language, GeneratorInput opts, Type type) + throws ApiException { LOGGER.debug(String.format("generate %s for %s", type.getTypeName(), language)); if (opts == null) { throw new BadRequestException("No options were supplied"); } JsonNode node = opts.getSpec(); - if(node != null && "{}".equals(node.toString())) { + if (node != null && "{}".equals(node.toString())) { LOGGER.debug("ignoring empty spec"); node = null; } Swagger swagger; if (node == null) { if (opts.getSwaggerUrl() != null) { - if(opts.getAuthorizationValue() != null) { - List authorizationValues = new ArrayList(); + if (opts.getAuthorizationValue() != null) { + List authorizationValues = + new ArrayList(); authorizationValues.add(opts.getAuthorizationValue()); - swagger = new SwaggerParser().read(opts.getSwaggerUrl(), authorizationValues, true); - } - else { + swagger = + new SwaggerParser().read(opts.getSwaggerUrl(), authorizationValues, + true); + } else { swagger = new SwaggerParser().read(opts.getSwaggerUrl()); } } else { throw new BadRequestException("No swagger specification was supplied"); } - } else if(opts.getAuthorizationValue() != null) { + } else if (opts.getAuthorizationValue() != null) { List authorizationValues = new ArrayList(); authorizationValues.add(opts.getAuthorizationValue()); swagger = new SwaggerParser().read(node, authorizationValues, true); - } - else { + } else { swagger = new SwaggerParser().read(node, true); } if (swagger == null) { @@ -99,12 +101,11 @@ private static String generate(String language, GeneratorInput opts, Type type) String destPath = null; - if(opts != null && opts.getOptions() != null) { + if (opts != null && opts.getOptions() != null) { destPath = opts.getOptions().get("outputFolder"); } - if(destPath == null) { - destPath = language + "-" - + type.getTypeName(); + if (destPath == null) { + destPath = language + "-" + type.getTypeName(); } ClientOptInput clientOptInput = new ClientOptInput(); @@ -112,14 +113,12 @@ private static String generate(String language, GeneratorInput opts, Type type) String outputFolder = getTmpFolder().getAbsolutePath() + File.separator + destPath; String outputFilename = outputFolder + "-bundle.zip"; - clientOptInput - .opts(clientOpts) - .swagger(swagger); + clientOptInput.opts(clientOpts).swagger(swagger); - CodegenConfig codegenConfig=null; + CodegenConfig codegenConfig = null; try { codegenConfig = CodegenConfigLoader.forName(language); - } catch(RuntimeException e) { + } catch (RuntimeException e) { throw new BadRequestException("Unsupported target " + language + " supplied"); } @@ -143,20 +142,19 @@ private static String generate(String language, GeneratorInput opts, Type type) ZipUtil zip = new ZipUtil(); zip.compressFiles(filesToAdd, outputFilename); } else { - throw new BadRequestException("A target generation was attempted, but no files were created!"); + throw new BadRequestException( + "A target generation was attempted, but no files were created!"); } - for(File file: files) { + for (File file : files) { try { file.delete(); - } - catch(Exception e) { + } catch (Exception e) { LOGGER.error("unable to delete file " + file.getAbsolutePath()); } } try { new File(outputFolder).delete(); - } - catch (Exception e) { + } catch (Exception e) { LOGGER.error("unable to delete output folder " + outputFolder); } } catch (Exception e) { diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/ExceptionWriter.java b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/ExceptionWriter.java index 122561ddd94..e2fac57d7d0 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/ExceptionWriter.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/ExceptionWriter.java @@ -17,35 +17,26 @@ public class ExceptionWriter implements ExceptionMapper { public Response toResponse(Exception exception) { if (exception instanceof javax.ws.rs.WebApplicationException) { javax.ws.rs.WebApplicationException e = (javax.ws.rs.WebApplicationException) exception; - return Response - .status(e.getResponse().getStatus()) - .entity(new ApiResponse(e.getResponse().getStatus(), - exception.getMessage())).build(); + return Response.status(e.getResponse().getStatus()) + .entity(new ApiResponse(e.getResponse().getStatus(), exception.getMessage())) + .build(); } else if (exception instanceof com.fasterxml.jackson.core.JsonParseException) { - return Response.status(400) - .entity(new ApiResponse(400, "bad input")).build(); + return Response.status(400).entity(new ApiResponse(400, "bad input")).build(); } else if (exception instanceof ValidationException) { ValidationException e = (ValidationException) exception; return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build(); } else if (exception instanceof NotFoundException) { - return Response - .status(Status.NOT_FOUND) - .entity(new ApiResponse(ApiResponse.ERROR, exception - .getMessage())).build(); + return Response.status(Status.NOT_FOUND) + .entity(new ApiResponse(ApiResponse.ERROR, exception.getMessage())).build(); } else if (exception instanceof BadRequestException) { - return Response - .status(Status.BAD_REQUEST) - .entity(new ApiResponse(ApiResponse.ERROR, exception - .getMessage())).build(); + return Response.status(Status.BAD_REQUEST) + .entity(new ApiResponse(ApiResponse.ERROR, exception.getMessage())).build(); } else if (exception instanceof ApiException) { - return Response - .status(Status.BAD_REQUEST) - .entity(new ApiResponse(ApiResponse.ERROR, exception - .getMessage())).build(); + return Response.status(Status.BAD_REQUEST) + .entity(new ApiResponse(ApiResponse.ERROR, exception.getMessage())).build(); } else { - return Response.status(500) - .entity(new ApiResponse(500, "something bad happened")) + return Response.status(500).entity(new ApiResponse(500, "something bad happened")) .build(); } } -} \ No newline at end of file +} diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java index ad6529bd36a..4220e1034a6 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java @@ -34,7 +34,8 @@ public class SwaggerResource { static { List extensions = Codegen.getExtensions(); for (CodegenConfig config : extensions) { - if (config.getTag().equals(CodegenType.CLIENT) || config.getTag().equals(CodegenType.DOCUMENTATION)) { + if (config.getTag().equals(CodegenType.CLIENT) + || config.getTag().equals(CodegenType.DOCUMENTATION)) { clients.add(config.getName()); } else if (config.getTag().equals(CodegenType.SERVER)) { servers.add(config.getName()); @@ -48,12 +49,11 @@ public class SwaggerResource { @GET @Path("/download/{fileId}") @Produces({MediaType.APPLICATION_OCTET_STREAM}) - @ApiOperation(value = "Downloads a pre-generated file", - notes = "A valid `fileId` is generated by the `/clients/{language}` or `/servers/{language}` POST " + - "operations. The fileId code can be used just once, after which a new `fileId` will need to " + - "be requested.", - response = String.class, - tags = {"clients", "servers"}) + @ApiOperation( + value = "Downloads a pre-generated file", + notes = "A valid `fileId` is generated by the `/clients/{language}` or `/servers/{language}` POST " + + "operations. The fileId code can be used just once, after which a new `fileId` will need to " + + "be requested.", response = String.class, tags = {"clients", "servers"}) public Response downloadFile(@PathParam("fileId") String fileId) throws Exception { Generated g = fileMap.get(fileId); System.out.println("looking for fileId " + fileId); @@ -64,16 +64,15 @@ public Response downloadFile(@PathParam("fileId") String fileId) throws Exceptio try { FileUtils.deleteDirectory(file.getParentFile()); - } - catch (Exception e) { + } catch (Exception e) { System.out.println("failed to delete file " + file.getAbsolutePath()); } - return Response.ok(bytes, "application/zip") - .header("Content-Disposition", "attachment; filename=\"" + g.getFriendlyName() + "-generated.zip\"") - .header("Accept-Range", "bytes") - .header("Content-Length", bytes.length) - .build(); + return Response + .ok(bytes, "application/zip") + .header("Content-Disposition", + "attachment; filename=\"" + g.getFriendlyName() + "-generated.zip\"") + .header("Accept-Range", "bytes").header("Content-Length", bytes.length).build(); } else { return Response.status(404).build(); } @@ -84,23 +83,22 @@ public Response downloadFile(@PathParam("fileId") String fileId) throws Exceptio @ApiOperation( value = "Generates a client library", notes = "Accepts a `GeneratorInput` options map for spec location and generation options", - response = ResponseCode.class, - tags = "clients") + response = ResponseCode.class, tags = "clients") public Response generateClient( @Context HttpServletRequest request, @ApiParam(value = "The target language for the client library", required = true) @PathParam("language") String language, - @ApiParam(value = "Configuration for building the client library", required = true) GeneratorInput opts) throws Exception { + @ApiParam(value = "Configuration for building the client library", required = true) GeneratorInput opts) + throws Exception { String filename = Generator.generateClient(language, opts); String host = System.getenv("GENERATOR_HOST"); - if(StringUtils.isBlank(host)) { + if (StringUtils.isBlank(host)) { String scheme = request.getHeader("X-SSL"); String port = ""; - if("1".equals(scheme)) { + if ("1".equals(scheme)) { scheme = "https"; - } - else { + } else { scheme = request.getScheme(); port = ":" + request.getServerPort(); } @@ -124,15 +122,12 @@ public Response generateClient( @GET @Path("/clients/{language}") @Produces({MediaType.APPLICATION_JSON}) - @ApiOperation( - value = "Returns options for a client library", - response = CliOption.class, - responseContainer = "map", - tags = "clients") + @ApiOperation(value = "Returns options for a client library", response = CliOption.class, + responseContainer = "map", tags = "clients") public Response getClientOptions( @SuppressWarnings("unused") @Context HttpServletRequest request, - @ApiParam(value = "The target language for the client library", required = true) - @PathParam("language") String language) throws Exception { + @ApiParam(value = "The target language for the client library", required = true) @PathParam("language") String language) + throws Exception { Map opts = Generator.getOptions(language); @@ -146,15 +141,12 @@ public Response getClientOptions( @GET @Path("/servers/{framework}") @Produces({MediaType.APPLICATION_JSON}) - @ApiOperation( - value = "Returns options for a server framework", - response = CliOption.class, - responseContainer = "map", - tags = "servers") + @ApiOperation(value = "Returns options for a server framework", response = CliOption.class, + responseContainer = "map", tags = "servers") public Response getServerOptions( @SuppressWarnings("unused") @Context HttpServletRequest request, - @ApiParam(value = "The target language for the server framework", required = true) - @PathParam("framework") String framework) throws Exception { + @ApiParam(value = "The target language for the server framework", required = true) @PathParam("framework") String framework) + throws Exception { Map opts = Generator.getOptions(framework); @@ -168,9 +160,7 @@ public Response getServerOptions( @GET @Path("/clients") @ApiOperation(value = "Gets languages supported by the client generator", - response = String.class, - responseContainer = "List", - tags = "clients") + response = String.class, responseContainer = "List", tags = "clients") public Response clientOptions() { String[] languages = new String[clients.size()]; languages = clients.toArray(languages); @@ -180,9 +170,7 @@ public Response clientOptions() { @GET @Path("/servers") @ApiOperation(value = "Gets languages supported by the server generator", - response = String.class, - responseContainer = "List", - tags = "servers") + response = String.class, responseContainer = "List", tags = "servers") public Response serverOptions() { String[] languages = new String[servers.size()]; languages = servers.toArray(languages); @@ -191,22 +179,22 @@ public Response serverOptions() { @POST @Path("/servers/{framework}") - @ApiOperation(value = "Generates a server library", + @ApiOperation( + value = "Generates a server library", notes = "Accepts a `GeneratorInput` options map for spec location and generation options.", - response = ResponseCode.class, - tags = "servers") - public Response generateServerForLanguage( - @Context HttpServletRequest request, - @ApiParam(value = "framework", required = true) @PathParam("framework") String framework, - @ApiParam(value = "parameters", required = true) GeneratorInput opts) - throws Exception { + response = ResponseCode.class, tags = "servers") + public Response generateServerForLanguage(@Context HttpServletRequest request, @ApiParam( + value = "framework", required = true) @PathParam("framework") String framework, + @ApiParam(value = "parameters", required = true) GeneratorInput opts) throws Exception { if (framework == null) { throw new BadRequestException("Framework is required"); } String filename = Generator.generateServer(framework, opts); System.out.println("generated name: " + filename); - String host = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); + String host = + request.getScheme() + "://" + request.getServerName() + ":" + + request.getServerPort(); if (filename != null) { String code = String.valueOf(UUID.randomUUID().toString()); diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java index aca470bd89b..b4eb8d92ff7 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java @@ -1,17 +1,15 @@ /** * Copyright 2016 SmartBear Software *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package io.swagger.generator.util; @@ -26,8 +24,8 @@ public class ApiOriginFilter implements javax.servlet.Filter { @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) response; res.addHeader("Access-Control-Allow-Origin", "*"); res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); @@ -36,10 +34,8 @@ public void doFilter(ServletRequest request, ServletResponse response, } @Override - public void destroy() { - } + public void destroy() {} @Override - public void init(FilterConfig filterConfig) throws ServletException { - } -} \ No newline at end of file + public void init(FilterConfig filterConfig) throws ServletException {} +} diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/JacksonJsonProvider.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/JacksonJsonProvider.java index 713ee2455c4..c26f11aa6d2 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/JacksonJsonProvider.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/JacksonJsonProvider.java @@ -17,4 +17,4 @@ public class JacksonJsonProvider extends JacksonJaxbJsonProvider { public JacksonJsonProvider() { super.setMapper(commonMapper); } -} \ No newline at end of file +} diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationException.java index 631541f6c01..99eb397e996 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationException.java @@ -25,4 +25,4 @@ public String getMessage() { public void setMessage(String msg) { this.msg = msg; } -} \ No newline at end of file +} diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationMessage.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationMessage.java index 9e0218e3809..40b26562501 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationMessage.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationMessage.java @@ -26,4 +26,4 @@ public String getSeverity() { public void setSeverity(String severity) { this.severity = severity; } -} \ No newline at end of file +} diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java index 3295be5d898..439388100fa 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java @@ -1,17 +1,15 @@ /** * Copyright 2016 SmartBear Software *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package io.swagger.generator.util; @@ -27,8 +25,9 @@ import java.util.zip.ZipOutputStream; /** - * This utility compresses a list of files to standard ZIP format file. - * It is able to compresses all sub files and sub directories, recursively. + * This utility compresses a list of files to standard ZIP format file. It is able to compresses all + * sub files and sub directories, recursively. + * * @author Ha Minh Nam * */ @@ -40,12 +39,14 @@ public class ZipUtil { /** * Compresses a collection of files to a destination zip file + * * @param listFiles A collection of files and directories * @param destZipFile The path of the destination zip file * @throws FileNotFoundException * @throws IOException */ - public void compressFiles(List listFiles, String destZipFile) throws FileNotFoundException, IOException { + public void compressFiles(List listFiles, String destZipFile) + throws FileNotFoundException, IOException { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destZipFile)); @@ -63,14 +64,15 @@ public void compressFiles(List listFiles, String destZipFile) throws FileN /** * Adds a directory to the current zip output stream - * @param folder the directory to be added + * + * @param folder the directory to be added * @param parentFolder the path of parent directory * @param zos the current zip output stream * @throws FileNotFoundException * @throws IOException */ - private void addFolderToZip(File folder, String parentFolder, - ZipOutputStream zos) throws FileNotFoundException, IOException { + private void addFolderToZip(File folder, String parentFolder, ZipOutputStream zos) + throws FileNotFoundException, IOException { for (File file : folder.listFiles()) { if (file.isDirectory()) { addFolderToZip(file, parentFolder + "/" + file.getName(), zos); @@ -79,8 +81,7 @@ private void addFolderToZip(File folder, String parentFolder, zos.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName())); - BufferedInputStream bis = new BufferedInputStream( - new FileInputStream(file)); + BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); long bytesRead = 0; byte[] bytesIn = new byte[BUFFER_SIZE]; @@ -98,17 +99,17 @@ private void addFolderToZip(File folder, String parentFolder, /** * Adds a file to the current zip output stream + * * @param file the file to be added * @param zos the current zip output stream * @throws FileNotFoundException * @throws IOException */ - private static void addFileToZip(File file, ZipOutputStream zos) - throws FileNotFoundException, IOException { + private static void addFileToZip(File file, ZipOutputStream zos) throws FileNotFoundException, + IOException { zos.putNextEntry(new ZipEntry(file.getName())); - BufferedInputStream bis = new BufferedInputStream(new FileInputStream( - file)); + BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); byte[] bytesIn = new byte[BUFFER_SIZE]; int read = 0; @@ -119,4 +120,4 @@ private static void addFileToZip(File file, ZipOutputStream zos) zos.closeEntry(); } -} \ No newline at end of file +} diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java index 900f659848f..c24307ea4fd 100644 --- a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java @@ -32,32 +32,35 @@ public class OnlineGeneratorOptionsTest { @DataProvider(name = OPTIONS_PROVIDER) private static Object[][] listOptions() { - return new Object[][]{{new AkkaScalaClientOptionsProvider()}, {new AndroidClientOptionsProvider()}, - {new AsyncScalaClientOptionsProvider()}, {new CSharpClientOptionsProvider()}, - {new CsharpDotNet2ClientOptionsProvider()}, {new DartClientOptionsProvider()}, - {new FlashClienOptionsProvider()}, {new JavaInflectorServerOptionsProvider()}, + return new Object[][] { + {new AkkaScalaClientOptionsProvider()}, + {new AndroidClientOptionsProvider()}, + {new AsyncScalaClientOptionsProvider()}, + {new CSharpClientOptionsProvider()}, + {new CsharpDotNet2ClientOptionsProvider()}, + {new DartClientOptionsProvider()}, + {new FlashClienOptionsProvider()}, + {new JavaInflectorServerOptionsProvider()}, { new JavaOptionsProvider(), - new JavaOptionsProvider(ImmutableMap.of(CodegenConstants.LIBRARY, JavaClientCodegen.RETROFIT_2) - ), - new JavaOptionsProvider(ImmutableMap.of( - CodegenConstants.LIBRARY, JavaClientCodegen.RETROFIT_2, - JavaClientCodegen.USE_RX_JAVA, "true") - ) - }, - {new JaxRSServerOptionsProvider()}, - {new NodeJSServerOptionsProvider()}, {new ObjcClientOptionsProvider()}, - {new PerlClientOptionsProvider()}, {new PhpClientOptionsProvider()}, - {new PythonClientOptionsProvider()}, {new Qt5CPPOptionsProvider()}, - {new RubyClientOptionsProvider()}, {new ScalaClientOptionsProvider()}, - {new ScalatraServerOptionsProvider()}, {new SilexServerOptionsProvider()}, - {new SinatraServerOptionsProvider()}, {new SlimFrameworkServerOptionsProvider()}, - {new SpringOptionsProvider()}, {new StaticDocOptionsProvider()}, - {new StaticHtmlOptionsProvider()}, {new SwaggerOptionsProvider()}, - {new SwaggerYamlOptionsProvider()}, {new SwiftOptionsProvider()}, - {new TizenClientOptionsProvider()}, {new TypeScriptAngularClientOptionsProvider()}, - {new TypeScriptNodeClientOptionsProvider()}, {new LumenServerOptionsProvider()} - }; + new JavaOptionsProvider(ImmutableMap.of(CodegenConstants.LIBRARY, + JavaClientCodegen.RETROFIT_2)), + new JavaOptionsProvider( + ImmutableMap.of(CodegenConstants.LIBRARY, + JavaClientCodegen.RETROFIT_2, + JavaClientCodegen.USE_RX_JAVA, "true"))}, + {new JaxRSServerOptionsProvider()}, {new NodeJSServerOptionsProvider()}, + {new ObjcClientOptionsProvider()}, {new PerlClientOptionsProvider()}, + {new PhpClientOptionsProvider()}, {new PythonClientOptionsProvider()}, + {new Qt5CPPOptionsProvider()}, {new RubyClientOptionsProvider()}, + {new ScalaClientOptionsProvider()}, {new ScalatraServerOptionsProvider()}, + {new SilexServerOptionsProvider()}, {new SinatraServerOptionsProvider()}, + {new SlimFrameworkServerOptionsProvider()}, {new SpringOptionsProvider()}, + {new StaticDocOptionsProvider()}, {new StaticHtmlOptionsProvider()}, + {new SwaggerOptionsProvider()}, {new SwaggerYamlOptionsProvider()}, + {new SwiftOptionsProvider()}, {new TizenClientOptionsProvider()}, + {new TypeScriptAngularClientOptionsProvider()}, + {new TypeScriptNodeClientOptionsProvider()}, {new LumenServerOptionsProvider()}}; } @Test(dataProvider = OPTIONS_PROVIDER) @@ -83,15 +86,15 @@ public String transformEntry(String key, InvocationCounter value) { outputFilename = Generator.generateClient(provider.getLanguage(), input); } final File dir = new File(new File(outputFilename).getParent()); - + try { FileUtils.deleteDirectory(dir); } catch (Exception e) { // directory can't be deleted for some reasons e.printStackTrace(); } for (InvocationCounter option : options.values()) { - assertNotEquals(option.getCounter(), 0, String.format("Option \"%s\" wasn't processed.", - option.getValue())); + assertNotEquals(option.getCounter(), 0, + String.format("Option \"%s\" wasn't processed.", option.getValue())); } } @@ -135,24 +138,27 @@ public String getValue() { public static void getOptionsTest(OptionsProvider provider) throws ApiException { final Map opts = Generator.getOptions(provider.getLanguage()); - final Function cliOptionWrapper = new Function() { - @Nullable - @Override - public CliOptionProxy apply(@Nullable CliOption option) { - return new CliOptionProxy(option); - } - }; + final Function cliOptionWrapper = + new Function() { + @Nullable + @Override + public CliOptionProxy apply(@Nullable CliOption option) { + return new CliOptionProxy(option); + } + }; - final List actual = Lists.transform(new ArrayList(opts.values()), cliOptionWrapper); - final List expected = Lists.transform( - CodegenConfigLoader.forName(provider.getLanguage()).cliOptions(), cliOptionWrapper); + final List actual = + Lists.transform(new ArrayList(opts.values()), cliOptionWrapper); + final List expected = + Lists.transform(CodegenConfigLoader.forName(provider.getLanguage()).cliOptions(), + cliOptionWrapper); assertEquals(actual, expected); } protected static class CliOptionProxy { private final CliOption wrapped; - public CliOptionProxy(CliOption wrapped){ + public CliOptionProxy(CliOption wrapped) { this.wrapped = wrapped; } diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java index c58844fb1da..e3ad18ecbdc 100644 --- a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java @@ -18,7 +18,8 @@ public class OnlineJavaClientOptionsTest { @Test public void getOptionsTest() throws ApiException { - final Map options = Generator.getOptions(new JavaOptionsProvider().getLanguage()); + final Map options = + Generator.getOptions(new JavaOptionsProvider().getLanguage()); assertNotNull(options); final CliOption opt = options.get(CodegenConstants.LIBRARY); assertNotNull(opt);