>() {};
- try {
- List<$method.returnClassName$> responseObject = (List<$method.returnClassName$>) APIInvoker.mapper.readValue(response, typeRef);
- return responseObject;
- } catch (IOException ioe) {
- String[] args = new String[]{response, typeRef.toString()};
- throw new APIException(APIExceptionCodes.ERROR_CONVERTING_JSON_TO_JAVA, args, "Error in converting response json value to java object : " + ioe.getMessage(), ioe);
- }
-$endif$
-$endif$
- }
-
-}$
-
-}
diff --git a/conf/java/templates/VersionChecker.st b/conf/java/templates/VersionChecker.st
deleted file mode 100644
index f2954a50642..00000000000
--- a/conf/java/templates/VersionChecker.st
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * Copyright 2011 Wordnik, Inc.
- *
- * 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.
- */
-
-package $packageName$;
-
-/**
- *
- * Maintains the compatible server version against which the drive is written
- * NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
- * @author ramesh
- *
- */
-public class VersionChecker {
-
- private String compatibleVersion = "$apiVersion$";
-
- /**
- * Gets the version against which the library code was written
- */
- public String getCompatibleVersion() {
- return compatibleVersion;
- }
-}
\ No newline at end of file
diff --git a/install-ivy b/install-ivy
deleted file mode 100644
index 9a1e7f7e746..00000000000
--- a/install-ivy
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/ivy.xml b/ivy.xml
deleted file mode 100644
index ea132b8cbcd..00000000000
--- a/ivy.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/ivysettings.xml b/ivysettings.xml
deleted file mode 100644
index ea8e09b9f5b..00000000000
--- a/ivysettings.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/modules/swagger-codegen-cli/pom.xml b/modules/swagger-codegen-cli/pom.xml
new file mode 100644
index 00000000000..c118a6325ef
--- /dev/null
+++ b/modules/swagger-codegen-cli/pom.xml
@@ -0,0 +1,103 @@
+
+
+ io.swagger
+ swagger-codegen-project
+ 2.1.6-SNAPSHOT
+ ../..
+
+ 4.0.0
+
+ swagger-codegen-cli
+ jar
+
+ swagger-codegen (executable)
+
+
+ swagger-codegen-cli
+
+
+ src/main/resources
+
+ logback.xml
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+
+
+
+ io.swagger.codegen.SwaggerCodegen
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-shade-plugin
+ 2.3
+
+
+ process-resources
+ package
+
+ shade
+
+
+ false
+ true
+
+ ${java.io.tmpdir}/dependency-reduced-pom.xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ io.swagger
+ swagger-codegen
+ ${project.version}
+
+
+
+ io.airlift
+ airline
+ 0.7
+
+
+ com.googlecode.lambdaj
+ lambdaj
+ 2.3.3
+
+
+ org.slf4j
+ slf4j-simple
+ ${slf4j-version}
+
+
+ org.testng
+ testng
+
+ test
+
+
+ org.jmockit
+ jmockit
+
+ test
+
+
+
+
\ No newline at end of file
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
new file mode 100644
index 00000000000..98c0b8c05b5
--- /dev/null
+++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java
@@ -0,0 +1,38 @@
+package io.swagger.codegen;
+
+import io.airlift.airline.Cli;
+import io.airlift.airline.Help;
+import io.swagger.codegen.cmd.ConfigHelp;
+import io.swagger.codegen.cmd.Generate;
+import io.swagger.codegen.cmd.Langs;
+import io.swagger.codegen.cmd.Meta;
+
+/**
+ * User: lanwen
+ * Date: 24.03.15
+ * Time: 17:56
+ *
+ * Command line interface for swagger codegen
+ * use `swagger-codegen-cli.jar help` for more info
+ *
+ * @since 2.1.3-M1
+ */
+public class SwaggerCodegen {
+
+
+ public static void main(String[] args) {
+ @SuppressWarnings("unchecked")
+ Cli.CliBuilder builder = Cli.builder("swagger-codegen-cli")
+ .withDescription("Swagger code generator CLI. More info on swagger.io")
+ .withDefaultCommand(Langs.class)
+ .withCommands(
+ Generate.class,
+ Meta.class,
+ Langs.class,
+ Help.class,
+ ConfigHelp.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
new file mode 100644
index 00000000000..eb2f8afea92
--- /dev/null
+++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java
@@ -0,0 +1,27 @@
+package io.swagger.codegen.cmd;
+
+import io.airlift.airline.Command;
+import io.airlift.airline.Option;
+import io.swagger.codegen.CliOption;
+import io.swagger.codegen.CodegenConfig;
+import io.swagger.codegen.CodegenConfigLoader;
+
+@Command(name = "config-help", description = "Config help for chosen lang")
+public class ConfigHelp implements Runnable {
+
+ @Option(name = {"-l", "--lang"}, title = "language", required = true,
+ description = "language to get config help for")
+ private String lang;
+
+ @Override
+ public void run() {
+ System.out.println();
+ CodegenConfig config = CodegenConfigLoader.forName(lang);
+ 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();
+ }
+ }
+}
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
new file mode 100644
index 00000000000..04d60e2ec88
--- /dev/null
+++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java
@@ -0,0 +1,249 @@
+package io.swagger.codegen.cmd;
+
+import io.airlift.airline.Command;
+import io.airlift.airline.Option;
+import io.swagger.codegen.ClientOptInput;
+import io.swagger.codegen.CodegenConstants;
+import io.swagger.codegen.DefaultGenerator;
+import io.swagger.codegen.utils.OptionUtils;
+import io.swagger.codegen.config.CodegenConfigurator;
+import org.apache.commons.lang3.tuple.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.apache.commons.lang3.StringUtils.isNotEmpty;
+
+/**
+ * User: lanwen
+ * Date: 24.03.15
+ * Time: 20:22
+ */
+
+@Command(name = "generate", description = "Generate code with chosen lang")
+public class Generate implements Runnable {
+
+ public static final Logger LOG = LoggerFactory.getLogger(Generate.class);
+
+ @Option(name = {"-v", "--verbose"}, description = "verbose mode")
+ private Boolean verbose;
+
+ @Option(name = {"-l", "--lang"}, title = "language", required = true,
+ description = "client language to generate (maybe class name in classpath, required)")
+ private String lang;
+
+ @Option(name = {"-o", "--output"}, title = "output directory",
+ description = "where to write the generated files (current dir by default)")
+ private String output = "";
+
+ @Option(name = {"-i", "--input-spec"}, title = "spec file", required = true,
+ description = "location of the swagger spec, as URL or file (required)")
+ private String spec;
+
+ @Option(name = {"-t", "--template-dir"}, title = "template directory",
+ 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")
+ private String auth;
+
+ @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.")
+ private String configFile;
+
+ @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)
+ private String apiPackage;
+
+ @Option(name = {"--model-package"}, title = "model package", description = CodegenConstants.MODEL_PACKAGE_DESC)
+ private String modelPackage;
+
+ @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")
+ 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")
+ private String additionalProperties;
+
+ @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",
+ 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)
+ 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)
+ private String artifactId;
+
+ @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;
+
+ @Override
+ public void run() {
+
+ //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
+ configurator = new CodegenConfigurator();
+ }
+
+ //now override with any specified parameters
+ if (verbose != null) {
+ configurator.setVerbose(verbose);
+ }
+
+ if(skipOverwrite != null) {
+ configurator.setSkipOverwrite(skipOverwrite);
+ }
+
+ if(isNotEmpty(spec)) {
+ configurator.setInputSpec(spec);
+ }
+
+ if(isNotEmpty(lang)) {
+ configurator.setLang(lang);
+ }
+
+ if(isNotEmpty(output)) {
+ configurator.setOutputDir(output);
+ }
+
+ if(isNotEmpty(auth)) {
+ configurator.setAuth(auth);
+ }
+
+ if(isNotEmpty(templateDir)) {
+ configurator.setTemplateDir(templateDir);
+ }
+
+ if(isNotEmpty(apiPackage)) {
+ configurator.setApiPackage(apiPackage);
+ }
+
+ if(isNotEmpty(modelPackage)) {
+ configurator.setModelPackage(modelPackage);
+ }
+
+ if(isNotEmpty(invokerPackage)) {
+ configurator.setInvokerPackage(invokerPackage);
+ }
+
+ if(isNotEmpty(groupId)) {
+ configurator.setGroupId(groupId);
+ }
+
+ if(isNotEmpty(artifactId)) {
+ configurator.setArtifactId(artifactId);
+ }
+
+ if(isNotEmpty(artifactVersion)) {
+ configurator.setArtifactVersion(artifactVersion);
+ }
+
+ if(isNotEmpty(library)) {
+ configurator.setLibrary(library);
+ }
+
+ setSystemProperties(configurator);
+ setInstantiationTypes(configurator);
+ setImportMappings(configurator);
+ setTypeMappings(configurator);
+ setAdditionalProperties(configurator);
+ setLanguageSpecificPrimitives(configurator);
+
+ final ClientOptInput clientOptInput = configurator.toClientOptInput();
+
+ new DefaultGenerator().opts(clientOptInput).generate();
+ }
+
+ private void setSystemProperties(CodegenConfigurator configurator) {
+ final Map map = createMapFromKeyValuePairs(systemProperties);
+ for (Map.Entry entry : map.entrySet()) {
+ configurator.addSystemProperty(entry.getKey(), entry.getValue());
+ }
+ }
+
+ private void setInstantiationTypes(CodegenConfigurator configurator) {
+ final Map map = createMapFromKeyValuePairs(instantiationTypes);
+ for (Map.Entry entry : map.entrySet()) {
+ configurator.addInstantiationType(entry.getKey(), entry.getValue());
+ }
+ }
+
+ private void setImportMappings(CodegenConfigurator configurator) {
+ final Map map = createMapFromKeyValuePairs(importMappings);
+ for (Map.Entry entry : map.entrySet()) {
+ configurator.addImportMapping(entry.getKey(), entry.getValue());
+ }
+ }
+
+ private void setTypeMappings(CodegenConfigurator configurator) {
+ final Map map = createMapFromKeyValuePairs(typeMappings);
+ for (Map.Entry entry : map.entrySet()) {
+ configurator.addTypeMapping(entry.getKey(), entry.getValue());
+ }
+ }
+
+ private void setAdditionalProperties(CodegenConfigurator configurator) {
+ final Map map = createMapFromKeyValuePairs(additionalProperties);
+ for (Map.Entry entry : map.entrySet()) {
+ configurator.addAdditionalProperty(entry.getKey(), entry.getValue());
+ }
+ }
+
+ private void setLanguageSpecificPrimitives(CodegenConfigurator configurator) {
+ final Set set = createSetFromCsvList(languageSpecificPrimitives);
+ for (String item : set) {
+ configurator.addLanguageSpecificPrimitive(item);
+ }
+ }
+
+ 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);
+
+ Map result = new HashMap();
+
+ for (Pair pair : pairs) {
+ result.put(pair.getLeft(), pair.getRight());
+ }
+
+ return result;
+ }
+}
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
new file mode 100644
index 00000000000..c3d7391579e
--- /dev/null
+++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Langs.java
@@ -0,0 +1,23 @@
+package io.swagger.codegen.cmd;
+
+import ch.lambdaj.collection.LambdaIterable;
+import io.airlift.airline.Command;
+import io.swagger.codegen.CodegenConfig;
+
+import static ch.lambdaj.Lambda.on;
+import static ch.lambdaj.collection.LambdaCollections.with;
+import static java.util.ServiceLoader.load;
+
+/**
+ * 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());
+ 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
new file mode 100644
index 00000000000..c2dffbe6200
--- /dev/null
+++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java
@@ -0,0 +1,155 @@
+package io.swagger.codegen.cmd;
+
+import ch.lambdaj.function.convert.Converter;
+import com.google.common.base.CaseFormat;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.samskivert.mustache.Mustache;
+import io.airlift.airline.Command;
+import io.airlift.airline.Option;
+import io.swagger.codegen.DefaultGenerator;
+import io.swagger.codegen.SupportingFile;
+import org.apache.commons.io.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.Reader;
+import java.util.List;
+import java.util.Map;
+
+import static ch.lambdaj.collection.LambdaCollections.with;
+import static com.google.common.base.Joiner.on;
+
+/**
+ * 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.")
+public class Meta implements Runnable {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(Meta.class);
+
+ private static final String TEMPLATE_DIR_CLASSPATH = "codegen";
+ private static final String MUSTACHE_EXTENSION = ".mustache";
+
+ @Option(name = {"-o", "--output"}, title = "output directory",
+ description = "where to write the generated files (current dir by default)")
+ private String outputFolder = "";
+
+ @Option(name = {"-n", "--name"}, title = "name",
+ description = "the human-readable name of the generator")
+ private String name = "default";
+
+ @Option(name = {"-p", "--package"}, title = "package",
+ description = "the package to put the main class into (defaults to io.swagger.codegen)")
+ private String targetPackage = "io.swagger.codegen";
+
+ @Override
+ public void run() {
+ final File targetDir = new File(outputFolder);
+ LOGGER.info("writing to folder [{}]", targetDir.getAbsolutePath());
+
+ 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")
+ );
+
+ String swaggerVersion = this.getClass().getPackage().getImplementationVersion();
+ // if the code is running outside of the jar (i.e. from the IDE), it will not have the version available.
+ // let's default it with something.
+ if (swaggerVersion==null) {
+ swaggerVersion = "2.1.3";
+ }
+ 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
+ *
+ * @param targetDir - destination directory
+ * @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) {
+ 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 outputFile = new File(destinationFolder, support.destinationFilename);
+
+ 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);
+ } else {
+ LOGGER.info("copying file to {}", outputFile.getAbsolutePath());
+ }
+
+ FileUtils.writeStringToFile(outputFile, formatted);
+ return outputFile;
+
+ } catch (IOException e) {
+ throw new RuntimeException("Can't generate project", e);
+ }
+ }
+ };
+ }
+
+ /**
+ * Creates mustache loader for template using classpath loader
+ *
+ * @param generator - class with reader getter
+ * @return loader for template
+ */
+ 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));
+ }
+ };
+ }
+
+ /**
+ * Converts package name to path on file system
+ *
+ * @param packageName - package name to convert
+ * @return relative path
+ */
+ private static String asPath(String packageName) {
+ return packageName.replace(".", File.separator);
+ }
+}
diff --git a/modules/swagger-codegen-cli/src/main/resources/logback.xml b/modules/swagger-codegen-cli/src/main/resources/logback.xml
new file mode 100644
index 00000000000..3bd0c92d369
--- /dev/null
+++ b/modules/swagger-codegen-cli/src/main/resources/logback.xml
@@ -0,0 +1,12 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
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
new file mode 100644
index 00000000000..36a560b776d
--- /dev/null
+++ b/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/GenerateTest.java
@@ -0,0 +1,358 @@
+package io.swagger.codegen.cmd;
+
+import io.swagger.codegen.ClientOptInput;
+import io.swagger.codegen.DefaultGenerator;
+import io.swagger.codegen.SwaggerCodegen;
+import io.swagger.codegen.config.CodegenConfigurator;
+import mockit.Expectations;
+import mockit.FullVerifications;
+import mockit.Injectable;
+import mockit.Mocked;
+import mockit.Verifications;
+import org.apache.commons.lang3.ArrayUtils;
+import org.testng.annotations.Test;
+
+@SuppressWarnings("unused")
+public class GenerateTest {
+
+ @Mocked
+ CodegenConfigurator configurator;
+
+ @Injectable
+ ClientOptInput clientOptInput;
+
+ @Mocked
+ DefaultGenerator generator;
+
+ @Test
+ public void testVerbose() throws Exception {
+ setupAndRunGenericTest("-v");
+
+ new FullVerifications() {{
+ configurator.setVerbose(true);
+ times = 1;
+ }};
+
+ setupAndRunGenericTest("--verbose");
+
+ 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() {{
+ }};
+ }
+
+ @Test
+ public void testRequiredArgs_LongArgs() throws Exception {
+ setupAndRunTest("--input-spec", "swagger.yaml", "--lang", "java", "--output", "src/main/java", false, null);
+ new FullVerifications() {{
+ }};
+ }
+
+ @Test
+ public void testTemplateDir() throws Exception {
+
+ final String templateDir = "src/main/resources/customTemplates";
+
+ setupAndRunGenericTest("--template-dir", templateDir);
+
+ new FullVerifications() {{
+ configurator.setTemplateDir(templateDir);
+ times = 1;
+ }};
+
+ setupAndRunGenericTest("-t", templateDir);
+
+ new FullVerifications() {{
+ configurator.setTemplateDir(templateDir);
+ times = 1;
+ }};
+ }
+
+ @Test
+ public void testAuth() throws Exception {
+
+ final String auth = "hello:world";
+
+ setupAndRunGenericTest("--auth", auth);
+
+ new FullVerifications() {{
+ configurator.setAuth(auth);
+ times = 1;
+ }};
+
+ setupAndRunGenericTest("-a", auth);
+
+ new FullVerifications() {{
+ configurator.setAuth(auth);
+ times = 1;
+ }};
+
+ setupAndRunGenericTest();
+
+ new FullVerifications() {{
+ configurator.setAuth(anyString);
+ times = 0;
+ }};
+ }
+
+ @Test
+ 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;
+ }};
+
+ 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;
+ }};
+ }
+
+
+ @Test
+ public void testConfig() throws Exception {
+
+ setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", true, "config.json", "-c", "config.json");
+
+ new FullVerifications(){{}};
+
+ setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", true, "config.json", "--config", "config.json");
+
+ new FullVerifications(){{}};
+ }
+
+ @Test
+ public void testSkipOverwrite() throws Exception {
+
+ setupAndRunGenericTest("-s");
+ new FullVerifications(){{
+ configurator.setSkipOverwrite(true); times=1;
+ }};
+
+ setupAndRunGenericTest("--skip-overwrite");
+ new FullVerifications(){{
+ configurator.setSkipOverwrite(true); times=1;
+ }};
+ }
+
+ @Test
+ public void testApiPackage() throws Exception {
+ final String value = "io.foo.bar.api";
+ setupAndRunGenericTest("--api-package", value);
+
+ new FullVerifications(){{
+ configurator.setApiPackage(value); times=1;
+ }};
+ }
+
+ @Test
+ public void testModelPackage() throws Exception {
+ final String value = "io.foo.bar.api";
+ setupAndRunGenericTest("--model-package", value);
+
+ new FullVerifications(){{
+ configurator.setModelPackage(value); times=1;
+ }};
+ }
+
+ @Test
+ 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;
+ }};
+ }
+
+ @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;
+ }};
+ }
+
+ @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;
+ }};
+ }
+
+ @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;
+ }};
+ }
+
+ @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;
+ }};
+ }
+
+ @Test
+ public void testInvokerPackage() throws Exception {
+ final String value = "io.foo.bar.api";
+ setupAndRunGenericTest("--invoker-package", value);
+
+ new FullVerifications(){{
+ configurator.setInvokerPackage(value); times=1;
+ }};
+ }
+
+ @Test
+ public void testGroupId() throws Exception {
+ final String value = "io.foo.bar.api";
+ setupAndRunGenericTest("--group-id", value);
+
+ new FullVerifications(){{
+ configurator.setGroupId(value); times=1;
+ }};
+ }
+
+ @Test
+ public void testArtifactId() throws Exception {
+ final String value = "awesome-api";
+ setupAndRunGenericTest("--artifact-id", value);
+
+ new FullVerifications(){{
+ configurator.setArtifactId(value); times=1;
+ }};
+ }
+
+ @Test
+ public void testArtifactVersion() throws Exception {
+ final String value = "1.2.3";
+ setupAndRunGenericTest("--artifact-version", value);
+
+ new FullVerifications(){{
+ configurator.setArtifactVersion(value); times=1;
+ }};
+ }
+
+ @Test
+ public void testLibrary() throws Exception {
+ final String value = "library1";
+ setupAndRunGenericTest("--library", value);
+
+ 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};
+
+ String[] argsToUse = ArrayUtils.addAll(commonArgs, additionalParameters);
+
+ if (configuratorFromFile) {
+
+ 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() {{
+
+ configurator.toClientOptInput();
+ times = 1;
+ result = clientOptInput;
+
+ new DefaultGenerator();
+ times = 1;
+ result = generator;
+
+ generator.opts(clientOptInput);
+ times = 1;
+ result = generator;
+
+ generator.generate();
+ times = 1;
+
+ }};
+
+ SwaggerCodegen.main(argsToUse);
+
+ 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);
+ }
+}
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
new file mode 100644
index 00000000000..db88cdcdb9d
--- /dev/null
+++ b/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/utils/OptionUtilsTest.java
@@ -0,0 +1,54 @@
+package io.swagger.codegen.cmd.utils;
+
+import io.swagger.codegen.utils.OptionUtils;
+import org.apache.commons.lang3.tuple.Pair;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+
+@SuppressWarnings("static-method")
+public class OptionUtilsTest {
+
+ @Test
+ public void splitCommaSeparatedList() throws Exception {
+ doCommaSeparatedListTest("a,b,c", Arrays.asList("a", "b", "c"));
+ doCommaSeparatedListTest("a,,c", Arrays.asList("a", "c"));
+ doCommaSeparatedListTest("", new ArrayList());
+ doCommaSeparatedListTest(null, new ArrayList());
+ }
+
+ @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,,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")));
+ doTupleListTest("", new ArrayList>());
+ doTupleListTest(null, new ArrayList>());
+ }
+
+ private static void doTupleListTest(String input, List> expectedResults) {
+ final List> result = OptionUtils.parseCommaSeparatedTuples(input);
+ assertNotNull(result);
+ assertEquals(result.size(), expectedResults.size());
+ for (int i = 0; i < expectedResults.size(); i++) {
+ final Pair actualPair = result.get(i);
+ final Pair expected = expectedResults.get(i);
+ assertEquals(actualPair, expected);
+ }
+ }
+
+ private static void doCommaSeparatedListTest(String csvStr, List expectedResults) {
+ final List result = OptionUtils.splitCommaSeparatedList(csvStr);
+ assertNotNull(result);
+ assertEquals(result.size(), expectedResults.size());
+ for (int i = 0; i < expectedResults.size(); i++) {
+ assertEquals(result.get(i), expectedResults.get(i));
+ }
+ }
+}
diff --git a/modules/swagger-codegen-maven-plugin/README.md b/modules/swagger-codegen-maven-plugin/README.md
new file mode 100644
index 00000000000..488148727b2
--- /dev/null
+++ b/modules/swagger-codegen-maven-plugin/README.md
@@ -0,0 +1,53 @@
+swagger-codegen-maven-plugin
+============================
+
+A Maven plugin to support the [swagger](http://swagger.io) code generation project
+
+Usage
+============================
+
+Add to your `build->plugins` section (default phase is `generate-sources` phase)
+```xml
+
+ io.swagger
+ swagger-codegen-maven-plugin
+ 2.1.5-SNAPSHOT
+
+
+
+ generate
+
+
+ src/main/resources/api.yaml
+ java
+
+ src/gen/java/main
+
+
+
+
+
+```
+
+Followed by:
+
+```
+mvn clean compile
+```
+
+### General Configuration parameters
+
+- `inputSpec` - OpenAPI Spec file path
+- `language` - target generation language
+- `output` - target output path (default is `${project.build.directory}/generated-sources/swagger`)
+- `templateDirectory` - directory with mustache templates
+- `addCompileSourceRoot` - add the output directory to the project as a source root (`true` by default)
+- `modelPackage` - the package to use for generated model objects/classes
+- `apiPackage` - the package to use for generated api objects/classes
+- `invokerPackage` - the package to use for the generated invoker objects
+- `configOptions` - a map of language-specific parameters (see below)
+- `configHelp` - dumps the configuration help for the specified library (generates no sources)
+
+### Sample configuration
+
+- Please see [an example configuration](examples) for using the plugin
\ No newline at end of file
diff --git a/modules/swagger-codegen-maven-plugin/examples/java-client.xml b/modules/swagger-codegen-maven-plugin/examples/java-client.xml
new file mode 100644
index 00000000000..5c093372f3b
--- /dev/null
+++ b/modules/swagger-codegen-maven-plugin/examples/java-client.xml
@@ -0,0 +1,115 @@
+
+ 4.0.0
+ io.swagger
+ sample-project
+ jar
+ 1.0-SNAPSHOT
+ sample-project
+ http://maven.apache.org
+
+
+
+
+ io.swagger
+ swagger-codegen-maven-plugin
+ 2.1.5-SNAPSHOT
+
+
+
+ generate
+
+
+
+ swagger.yaml
+
+
+ java
+
+
+
+ java8
+
+
+
+ jersey2
+
+
+
+
+
+
+
+
+
+ io.swagger
+ swagger-annotations
+ ${swagger-annotations-version}
+
+
+
+
+ org.glassfish.jersey.core
+ jersey-client
+ ${jersey-version}
+
+
+ org.glassfish.jersey.media
+ jersey-media-multipart
+ ${jersey-version}
+
+
+ org.glassfish.jersey.media
+ jersey-media-json-jackson
+ 2.22.1
+
+
+
+
+ com.fasterxml.jackson.core
+ jackson-core
+ ${jackson-version}
+
+
+ com.fasterxml.jackson.core
+ jackson-annotations
+ ${jackson-version}
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${jackson-version}
+
+
+ com.fasterxml.jackson.datatype
+ jackson-datatype-joda
+ 2.1.5
+
+
+ joda-time
+ joda-time
+ ${jodatime-version}
+
+
+
+
+ com.brsanthu
+ migbase64
+ 2.2
+
+
+
+ junit
+ junit
+ ${junit-version}
+ test
+
+
+
+ 1.5.0
+ 2.12
+ 2.4.2
+ 2.3
+ 1.0.0
+ 4.8.1
+
+
\ No newline at end of file
diff --git a/modules/swagger-codegen-maven-plugin/examples/swagger.yaml b/modules/swagger-codegen-maven-plugin/examples/swagger.yaml
new file mode 100644
index 00000000000..c6eeffab7d7
--- /dev/null
+++ b/modules/swagger-codegen-maven-plugin/examples/swagger.yaml
@@ -0,0 +1,702 @@
+---
+swagger: "2.0"
+info:
+ description: "This is a sample server Petstore server. You can find out more about\
+ \ Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).\
+ \ For this sample, you can use the api key `special-key` to test the authorization\
+ \ filters."
+ version: "1.0.0"
+ title: "Swagger Petstore"
+ termsOfService: "http://swagger.io/terms/"
+ contact:
+ email: "apiteam@swagger.io"
+ license:
+ name: "Apache 2.0"
+ url: "http://www.apache.org/licenses/LICENSE-2.0.html"
+host: "petstore.swagger.io"
+basePath: "/v2"
+tags:
+- name: "pet"
+ description: "Everything about your Pets"
+ externalDocs:
+ description: "Find out more"
+ url: "http://swagger.io"
+- name: "store"
+ description: "Access to Petstore orders"
+- name: "user"
+ description: "Operations about user"
+ externalDocs:
+ description: "Find out more about our store"
+ url: "http://swagger.io"
+schemes:
+- "http"
+paths:
+ /pet:
+ post:
+ tags:
+ - "pet"
+ summary: "Add a new pet to the store"
+ description: ""
+ operationId: "addPet"
+ consumes:
+ - "application/json"
+ - "application/xml"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - in: "body"
+ name: "body"
+ description: "Pet object that needs to be added to the store"
+ required: true
+ schema:
+ $ref: "#/definitions/Pet"
+ responses:
+ 405:
+ description: "Invalid input"
+ security:
+ - petstore_auth:
+ - "write:pets"
+ - "read:pets"
+ put:
+ tags:
+ - "pet"
+ summary: "Update an existing pet"
+ description: ""
+ operationId: "updatePet"
+ consumes:
+ - "application/json"
+ - "application/xml"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - in: "body"
+ name: "body"
+ description: "Pet object that needs to be added to the store"
+ required: true
+ schema:
+ $ref: "#/definitions/Pet"
+ responses:
+ 400:
+ description: "Invalid ID supplied"
+ 404:
+ description: "Pet not found"
+ 405:
+ description: "Validation exception"
+ security:
+ - petstore_auth:
+ - "write:pets"
+ - "read:pets"
+ /pet/findByStatus:
+ get:
+ tags:
+ - "pet"
+ summary: "Finds Pets by status"
+ description: "Multiple status values can be provided with comma seperated strings"
+ operationId: "findPetsByStatus"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - name: "status"
+ in: "query"
+ description: "Status values that need to be considered for filter"
+ required: true
+ type: "array"
+ items:
+ type: "string"
+ enum:
+ - "available"
+ - "pending"
+ - "sold"
+ default: "available"
+ collectionFormat: "csv"
+ responses:
+ 200:
+ description: "successful operation"
+ schema:
+ type: "array"
+ items:
+ $ref: "#/definitions/Pet"
+ 400:
+ description: "Invalid status value"
+ security:
+ - petstore_auth:
+ - "write:pets"
+ - "read:pets"
+ /pet/findByTags:
+ get:
+ tags:
+ - "pet"
+ summary: "Finds Pets by tags"
+ description: "Muliple tags can be provided with comma seperated strings. Use\
+ \ tag1, tag2, tag3 for testing."
+ operationId: "findPetsByTags"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - name: "tags"
+ in: "query"
+ description: "Tags to filter by"
+ required: true
+ type: "array"
+ items:
+ type: "string"
+ collectionFormat: "csv"
+ responses:
+ 200:
+ description: "successful operation"
+ schema:
+ type: "array"
+ items:
+ $ref: "#/definitions/Pet"
+ 400:
+ description: "Invalid tag value"
+ security:
+ - petstore_auth:
+ - "write:pets"
+ - "read:pets"
+ /pet/{petId}:
+ get:
+ tags:
+ - "pet"
+ summary: "Find pet by ID"
+ description: "Returns a single pet"
+ operationId: "getPetById"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - name: "petId"
+ in: "path"
+ description: "ID of pet to return"
+ required: true
+ type: "integer"
+ format: "int64"
+ responses:
+ 200:
+ description: "successful operation"
+ schema:
+ $ref: "#/definitions/Pet"
+ 400:
+ description: "Invalid ID supplied"
+ 404:
+ description: "Pet not found"
+ security:
+ - api_key: []
+ post:
+ tags:
+ - "pet"
+ summary: "Updates a pet in the store with form data"
+ description: ""
+ operationId: "updatePetWithForm"
+ consumes:
+ - "application/x-www-form-urlencoded"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - name: "petId"
+ in: "path"
+ description: "ID of pet that needs to be updated"
+ required: true
+ type: "integer"
+ format: "int64"
+ - name: "name"
+ in: "formData"
+ description: "Updated name of the pet"
+ required: false
+ type: "string"
+ - name: "status"
+ in: "formData"
+ description: "Updated status of the pet"
+ required: false
+ type: "string"
+ responses:
+ 405:
+ description: "Invalid input"
+ security:
+ - petstore_auth:
+ - "write:pets"
+ - "read:pets"
+ delete:
+ tags:
+ - "pet"
+ summary: "Deletes a pet"
+ description: ""
+ operationId: "deletePet"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - name: "api_key"
+ in: "header"
+ required: false
+ type: "string"
+ - name: "petId"
+ in: "path"
+ description: "Pet id to delete"
+ required: true
+ type: "integer"
+ format: "int64"
+ responses:
+ 400:
+ description: "Invalid pet value"
+ security:
+ - petstore_auth:
+ - "write:pets"
+ - "read:pets"
+ /pet/{petId}/uploadImage:
+ post:
+ tags:
+ - "pet"
+ summary: "uploads an image"
+ description: ""
+ operationId: "uploadFile"
+ consumes:
+ - "multipart/form-data"
+ produces:
+ - "application/json"
+ parameters:
+ - name: "petId"
+ in: "path"
+ description: "ID of pet to update"
+ required: true
+ type: "integer"
+ format: "int64"
+ - name: "additionalMetadata"
+ in: "formData"
+ description: "Additional data to pass to server"
+ required: false
+ type: "string"
+ - name: "file"
+ in: "formData"
+ description: "file to upload"
+ required: false
+ type: "file"
+ responses:
+ 200:
+ description: "successful operation"
+ schema:
+ $ref: "#/definitions/ApiResponse"
+ security:
+ - petstore_auth:
+ - "write:pets"
+ - "read:pets"
+ /store/inventory:
+ get:
+ tags:
+ - "store"
+ summary: "Returns pet inventories by status"
+ description: "Returns a map of status codes to quantities"
+ operationId: "getInventory"
+ produces:
+ - "application/json"
+ parameters: []
+ responses:
+ 200:
+ description: "successful operation"
+ schema:
+ type: "object"
+ additionalProperties:
+ type: "integer"
+ format: "int32"
+ security:
+ - api_key: []
+ /store/order:
+ post:
+ tags:
+ - "store"
+ summary: "Place an order for a pet"
+ description: ""
+ operationId: "placeOrder"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - in: "body"
+ name: "body"
+ description: "order placed for purchasing the pet"
+ required: true
+ schema:
+ $ref: "#/definitions/Order"
+ responses:
+ 200:
+ description: "successful operation"
+ schema:
+ $ref: "#/definitions/Order"
+ 400:
+ description: "Invalid Order"
+ /store/order/{orderId}:
+ get:
+ tags:
+ - "store"
+ summary: "Find purchase order by ID"
+ description: "For valid response try integer IDs with value <= 5 or > 10. Other\
+ \ values will generated exceptions"
+ operationId: "getOrderById"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - name: "orderId"
+ in: "path"
+ description: "ID of pet that needs to be fetched"
+ required: true
+ type: "integer"
+ maximum: 5.0
+ minimum: 1.0
+ format: "int64"
+ responses:
+ 200:
+ description: "successful operation"
+ schema:
+ $ref: "#/definitions/Order"
+ 400:
+ description: "Invalid ID supplied"
+ 404:
+ description: "Order not found"
+ delete:
+ tags:
+ - "store"
+ summary: "Delete purchase order by ID"
+ description: "For valid response try integer IDs with value < 1000. Anything\
+ \ above 1000 or nonintegers will generate API errors"
+ operationId: "deleteOrder"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - name: "orderId"
+ in: "path"
+ description: "ID of the order that needs to be deleted"
+ required: true
+ type: "string"
+ minimum: 1.0
+ responses:
+ 400:
+ description: "Invalid ID supplied"
+ 404:
+ description: "Order not found"
+ /user:
+ post:
+ tags:
+ - "user"
+ summary: "Create user"
+ description: "This can only be done by the logged in user."
+ operationId: "createUser"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - in: "body"
+ name: "body"
+ description: "Created user object"
+ required: true
+ schema:
+ $ref: "#/definitions/User"
+ responses:
+ default:
+ description: "successful operation"
+ /user/createWithArray:
+ post:
+ tags:
+ - "user"
+ summary: "Creates list of users with given input array"
+ description: ""
+ operationId: "createUsersWithArrayInput"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - in: "body"
+ name: "body"
+ description: "List of user object"
+ required: true
+ schema:
+ type: "array"
+ items:
+ $ref: "#/definitions/User"
+ responses:
+ default:
+ description: "successful operation"
+ /user/createWithList:
+ post:
+ tags:
+ - "user"
+ summary: "Creates list of users with given input array"
+ description: ""
+ operationId: "createUsersWithListInput"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - in: "body"
+ name: "body"
+ description: "List of user object"
+ required: true
+ schema:
+ type: "array"
+ items:
+ $ref: "#/definitions/User"
+ responses:
+ default:
+ description: "successful operation"
+ /user/login:
+ get:
+ tags:
+ - "user"
+ summary: "Logs user into the system"
+ description: ""
+ operationId: "loginUser"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - name: "username"
+ in: "query"
+ description: "The user name for login"
+ required: true
+ type: "string"
+ - name: "password"
+ in: "query"
+ description: "The password for login in clear text"
+ required: true
+ type: "string"
+ responses:
+ 200:
+ description: "successful operation"
+ schema:
+ type: "string"
+ headers:
+ X-Rate-Limit:
+ type: "integer"
+ format: "int32"
+ description: "calls per hour allowed by the user"
+ X-Expires-After:
+ type: "string"
+ format: "date-time"
+ description: "date in UTC when toekn expires"
+ 400:
+ description: "Invalid username/password supplied"
+ /user/logout:
+ get:
+ tags:
+ - "user"
+ summary: "Logs out current logged in user session"
+ description: ""
+ operationId: "logoutUser"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters: []
+ responses:
+ default:
+ description: "successful operation"
+ /user/{username}:
+ get:
+ tags:
+ - "user"
+ summary: "Get user by user name"
+ description: ""
+ operationId: "getUserByName"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - name: "username"
+ in: "path"
+ description: "The name that needs to be fetched. Use user1 for testing. "
+ required: true
+ type: "string"
+ responses:
+ 200:
+ description: "successful operation"
+ schema:
+ $ref: "#/definitions/User"
+ 400:
+ description: "Invalid username supplied"
+ 404:
+ description: "User not found"
+ put:
+ tags:
+ - "user"
+ summary: "Updated user"
+ description: "This can only be done by the logged in user."
+ operationId: "updateUser"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - name: "username"
+ in: "path"
+ description: "name that need to be deleted"
+ required: true
+ type: "string"
+ - in: "body"
+ name: "body"
+ description: "Updated user object"
+ required: true
+ schema:
+ $ref: "#/definitions/User"
+ responses:
+ 400:
+ description: "Invalid user supplied"
+ 404:
+ description: "User not found"
+ delete:
+ tags:
+ - "user"
+ summary: "Delete user"
+ description: "This can only be done by the logged in user."
+ operationId: "deleteUser"
+ produces:
+ - "application/xml"
+ - "application/json"
+ parameters:
+ - name: "username"
+ in: "path"
+ description: "The name that needs to be deleted"
+ required: true
+ type: "string"
+ responses:
+ 400:
+ description: "Invalid username supplied"
+ 404:
+ description: "User not found"
+securityDefinitions:
+ petstore_auth:
+ type: "oauth2"
+ authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog"
+ flow: "implicit"
+ scopes:
+ write:pets: "modify pets in your account"
+ read:pets: "read your pets"
+ api_key:
+ type: "apiKey"
+ name: "api_key"
+ in: "header"
+definitions:
+ Order:
+ type: "object"
+ properties:
+ id:
+ type: "integer"
+ format: "int64"
+ petId:
+ type: "integer"
+ format: "int64"
+ quantity:
+ type: "integer"
+ format: "int32"
+ shipDate:
+ type: "string"
+ format: "date-time"
+ status:
+ type: "string"
+ description: "Order Status"
+ enum:
+ - "placed"
+ - "approved"
+ - "delivered"
+ complete:
+ type: "boolean"
+ default: false
+ xml:
+ name: "Order"
+ Category:
+ type: "object"
+ properties:
+ id:
+ type: "integer"
+ format: "int64"
+ name:
+ type: "string"
+ xml:
+ name: "Category"
+ User:
+ type: "object"
+ properties:
+ id:
+ type: "integer"
+ format: "int64"
+ username:
+ type: "string"
+ firstName:
+ type: "string"
+ lastName:
+ type: "string"
+ email:
+ type: "string"
+ password:
+ type: "string"
+ phone:
+ type: "string"
+ userStatus:
+ type: "integer"
+ format: "int32"
+ description: "User Status"
+ xml:
+ name: "User"
+ Tag:
+ type: "object"
+ properties:
+ id:
+ type: "integer"
+ format: "int64"
+ name:
+ type: "string"
+ xml:
+ name: "Tag"
+ Pet:
+ type: "object"
+ required:
+ - "name"
+ - "photoUrls"
+ properties:
+ id:
+ type: "integer"
+ format: "int64"
+ category:
+ $ref: "#/definitions/Category"
+ name:
+ type: "string"
+ example: "doggie"
+ photoUrls:
+ type: "array"
+ xml:
+ name: "photoUrl"
+ wrapped: true
+ items:
+ type: "string"
+ tags:
+ type: "array"
+ xml:
+ name: "tag"
+ wrapped: true
+ items:
+ $ref: "#/definitions/Tag"
+ status:
+ type: "string"
+ description: "pet status in the store"
+ enum:
+ - "available"
+ - "pending"
+ - "sold"
+ xml:
+ name: "Pet"
+ ApiResponse:
+ type: "object"
+ properties:
+ code:
+ type: "integer"
+ format: "int32"
+ type:
+ type: "string"
+ message:
+ type: "string"
+externalDocs:
+ description: "Find out more about Swagger"
+ url: "http://swagger.io"
diff --git a/modules/swagger-codegen-maven-plugin/pom.xml b/modules/swagger-codegen-maven-plugin/pom.xml
new file mode 100644
index 00000000000..52cf252d309
--- /dev/null
+++ b/modules/swagger-codegen-maven-plugin/pom.xml
@@ -0,0 +1,87 @@
+
+
+ 4.0.0
+
+
+ io.swagger
+ swagger-codegen-project
+ 2.1.6-SNAPSHOT
+ ../..
+
+ swagger-codegen-maven-plugin
+ swagger-codegen (maven-plugin)
+ maven-plugin
+ maven plugin to build modules from swagger codegen
+
+ UTF-8
+
+
+
+ org.apache.maven
+ maven-core
+ 3.2.5
+
+
+ org.apache.maven
+ maven-artifact
+ 3.2.5
+ provided
+
+
+ org.apache.maven
+ maven-compat
+ 3.2.5
+
+
+ org.apache.maven
+ maven-plugin-api
+ 3.2.5
+
+
+ org.apache.maven.plugin-tools
+ maven-plugin-annotations
+ 3.4
+
+
+ io.swagger
+ swagger-codegen
+ ${project.version}
+
+
+ junit
+ junit
+
+ test
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-plugin-plugin
+ 3.4
+
+ true
+
+
+
+ mojo-descriptor
+ process-classes
+
+ descriptor
+
+
+
+ help-goal
+
+ helpmojo
+
+
+
+
+
+
+
+
diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/AdditionalParams.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/AdditionalParams.java
new file mode 100644
index 00000000000..7db012f439c
--- /dev/null
+++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/AdditionalParams.java
@@ -0,0 +1,16 @@
+package io.swagger.codegen.plugin;
+
+/**
+ * User: lanwen
+ * Date: 24.03.15
+ * Time: 14:47
+ */
+public final class AdditionalParams {
+ public static final String TEMPLATE_DIR_PARAM = "templateDir";
+ public static final String MODEL_PACKAGE_PARAM = "modelPackage";
+ public static final String API_PACKAGE_PARAM = "apiPackage";
+ public static final String INVOKER_PACKAGE_PARAM = "invokerPackage";
+ public static final String LIBRARY_PARAM = "library";
+
+ private AdditionalParams() {}
+}
\ No newline at end of file
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
new file mode 100644
index 00000000000..f0afc2999da
--- /dev/null
+++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java
@@ -0,0 +1,232 @@
+package io.swagger.codegen.plugin;
+
+/*
+ * 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.
+ */
+
+import config.Config;
+import config.ConfigParser;
+import io.swagger.codegen.*;
+import io.swagger.codegen.utils.OptionUtils;
+import io.swagger.models.Swagger;
+import io.swagger.parser.SwaggerParser;
+import org.apache.commons.lang3.tuple.Pair;
+import org.apache.maven.plugin.AbstractMojo;
+import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugins.annotations.LifecyclePhase;
+import org.apache.maven.plugins.annotations.Mojo;
+import org.apache.maven.plugins.annotations.Parameter;
+import org.apache.maven.project.MavenProject;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static io.swagger.codegen.plugin.AdditionalParams.*;
+
+/**
+ * Goal which generates client/server code from a swagger json/yaml definition.
+ */
+@Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
+public class CodeGenMojo extends AbstractMojo {
+ /**
+ * Location of the output directory.
+ */
+ @Parameter(name = "output",
+ property = "swagger.codegen.maven.plugin.output",
+ defaultValue = "${project.build.directory}/generated-sources/swagger")
+ private File output;
+
+ /**
+ * Location of the swagger spec, as URL or file.
+ */
+ @Parameter(name = "inputSpec", required = true)
+ private String inputSpec;
+
+ /**
+ * Folder containing the template files.
+ */
+ @Parameter(name = "templateDirectory")
+ private File templateDirectory;
+
+ /**
+ * The package to use for generated model objects/classes
+ */
+ @Parameter(name = "modelPackage")
+ private String modelPackage;
+
+ /**
+ * The package to use for generated api objects/classes
+ */
+ @Parameter(name = "apiPackage")
+ private String apiPackage;
+
+ /**
+ * The package to use for the generated invoker objects
+ */
+ @Parameter(name = "invokerPackage")
+ private String invokerPackage;
+
+ /**
+ * Client language to generate.
+ */
+ @Parameter(name = "language", required = true)
+ private String language;
+
+ /**
+ * Path to separate json configuration file.
+ */
+ @Parameter(name = "configurationFile", required = false)
+ private String configurationFile;
+
+ /**
+ * Sets the library
+ */
+ @Parameter(name = "library", required = false)
+ private String library;
+
+ /**
+ * A map of language-specific parameters as passed with the -c option to the command line
+ */
+ @Parameter(name = "configOptions")
+ 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.
+ */
+ @Parameter(defaultValue = "true")
+ private boolean addCompileSourceRoot = true;
+
+ @Parameter
+ protected Map environmentVariables = new HashMap();
+
+ @Parameter
+ private boolean configHelp = false;
+
+ /**
+ * The project being built.
+ */
+ @Parameter(readonly = true, required = true, defaultValue = "${project}")
+ private MavenProject project;
+
+ @Override
+ public void execute() throws MojoExecutionException {
+ Swagger swagger = new SwaggerParser().read(inputSpec);
+
+ CodegenConfig config = CodegenConfigLoader.forName(language);
+ config.setOutputDir(output.getAbsolutePath());
+
+ if (environmentVariables != null) {
+ for(String key : environmentVariables.keySet()) {
+ String value = environmentVariables.get(key);
+ if(value == null) {
+ // don't put null values
+ value = "";
+ }
+ System.setProperty(key, value);
+ }
+ }
+ if (null != library) {
+ config.setLibrary(library);
+ }
+ if (null != templateDirectory) {
+ config.additionalProperties().put(TEMPLATE_DIR_PARAM, templateDirectory.getAbsolutePath());
+ }
+ if (null != modelPackage) {
+ config.additionalProperties().put(MODEL_PACKAGE_PARAM, modelPackage);
+ }
+ if (null != apiPackage) {
+ config.additionalProperties().put(API_PACKAGE_PARAM, apiPackage);
+ }
+ if (null != invokerPackage) {
+ config.additionalProperties().put(INVOKER_PACKAGE_PARAM, invokerPackage);
+ }
+
+ if (configOptions != null) {
+ for (CliOption langCliOption : config.cliOptions()) {
+ if (configOptions.containsKey(langCliOption.getOpt())) {
+ config.additionalProperties().put(langCliOption.getOpt(),
+ configOptions.get(langCliOption.getOpt()));
+ }
+ }
+ if(configOptions.containsKey("import-mappings")) {
+ Map mappings = createMapFromKeyValuePairs(configOptions.get("import-mappings").toString());
+ config.importMapping().putAll(mappings);
+ }
+
+ if(configOptions.containsKey("type-mappings")) {
+ Map mappings = createMapFromKeyValuePairs(configOptions.get("type-mappings").toString());
+ config.typeMapping().putAll(mappings);
+ }
+
+ if(configOptions.containsKey("instantiation-types")) {
+ Map mappings = createMapFromKeyValuePairs(configOptions.get("instantiation-types").toString());
+ config.instantiationTypes().putAll(mappings);
+ }
+ }
+
+ if (null != configurationFile) {
+ Config genConfig = ConfigParser.read(configurationFile);
+ if (null != genConfig) {
+ for (CliOption langCliOption : config.cliOptions()) {
+ if (genConfig.hasOption(langCliOption.getOpt())) {
+ config.additionalProperties().put(langCliOption.getOpt(), genConfig.getOption(langCliOption.getOpt()));
+ }
+ }
+ } else {
+ throw new RuntimeException("Unable to read configuration file");
+ }
+ }
+
+ ClientOptInput input = new ClientOptInput().opts(new ClientOpts()).swagger(swagger);
+ input.setConfig(config);
+
+ 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();
+ }
+ return;
+ }
+ try {
+ new DefaultGenerator().opts(input).generate();
+ } catch (Exception e) {
+ // 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.");
+ }
+
+ if (addCompileSourceRoot) {
+ project.addCompileSourceRoot(output.toString());
+ }
+ }
+
+ private static Map createMapFromKeyValuePairs(String commaSeparatedKVPairs) {
+ final List> pairs = OptionUtils.parseCommaSeparatedTuples(commaSeparatedKVPairs);
+
+ Map result = new HashMap();
+
+ for (Pair pair : pairs) {
+ result.put(pair.getLeft(), pair.getRight());
+ }
+
+ return result;
+ }
+}
diff --git a/modules/swagger-codegen/.gitignore b/modules/swagger-codegen/.gitignore
new file mode 100644
index 00000000000..d027396de4e
--- /dev/null
+++ b/modules/swagger-codegen/.gitignore
@@ -0,0 +1 @@
+/.settings/
diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml
new file mode 100644
index 00000000000..a5c4eedd740
--- /dev/null
+++ b/modules/swagger-codegen/pom.xml
@@ -0,0 +1,284 @@
+
+
+ io.swagger
+ swagger-codegen-project
+ 2.1.6-SNAPSHOT
+ ../..
+
+ 4.0.0
+ swagger-codegen
+ jar
+ swagger-codegen (core library)
+
+ src/main/java
+ install
+
+
+ src/main/resources
+
+ logback.xml
+
+
+
+
+
+ org.jvnet.wagon-svn
+ wagon-svn
+ 1.8
+
+
+ org.apache.maven.wagon
+ wagon-ssh-external
+ 1.0-alpha-6
+
+
+ org.apache.maven.wagon
+ wagon-webdav
+ 1.0-beta-1
+
+
+ target
+ ${project.artifactId}-${project.version}
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ 1.3.2
+
+
+
+ java
+
+
+
+
+ io.swagger.codegen.Codegen
+
+
+
+ maven-dependency-plugin
+
+
+ package
+
+ copy-dependencies
+
+
+ ${project.build.directory}/lib
+
+
+
+
+
+ maven-compiler-plugin
+ 3.0
+
+ 1.6
+ 1.6
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+ 2.4
+
+
+
+ development
+ ${project.url}
+ ${project.version}
+ io.swagger
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-site-plugin
+ 2.1
+
+
+ org.apache.maven.plugins
+ maven-release-plugin
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+ 2.6
+
+
+
+ test-jar
+
+
+
+
+
+
+
+
+ release-profile
+
+ true
+
+
+
+ release-sign-artifacts
+
+
+ performRelease
+ true
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-gpg-plugin
+
+
+ sign-artifacts
+ verify
+
+ sign
+
+
+
+
+
+
+
+
+
+ target/site
+
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+ 2.9
+
+ true
+ true
+
+ http://java.sun.com/javaee/5/docs/api
+ http://java.sun.com/j2se/1.5.0/docs/api
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-jxr-plugin
+ 2.3
+
+ true
+
+
+
+ org.apache.maven.plugins
+ maven-project-info-reports-plugin
+ 2.6
+
+
+
+ project-team
+
+
+
+
+
+
+
+
+ io.swagger
+ swagger-parser
+ ${swagger-parser-version}
+ compile
+
+
+ io.swagger
+ swagger-compat-spec-parser
+ ${swagger-parser-version}
+
+
+ ${project.groupId}
+ swagger-core
+ ${swagger-core-version}
+
+
+ com.samskivert
+ jmustache
+ ${jmustache-version}
+
+
+ commons-io
+ commons-io
+ ${commons-io-version}
+
+
+ org.apache.maven
+ maven-plugin-tools-api
+ 2.0
+
+
+ org.apache.felix
+ maven-bundle-plugin
+ ${felix-version}
+
+
+ org.slf4j
+ slf4j-ext
+ ${slf4j-version}
+
+
+ org.slf4j
+ slf4j-api
+ ${slf4j-version}
+
+
+ org.slf4j
+ slf4j-simple
+ ${slf4j-version}
+
+
+ commons-lang
+ commons-lang
+ ${commons-lang-version}
+
+
+ commons-cli
+ commons-cli
+ ${commons-cli-version}
+
+
+ org.testng
+ testng
+
+ test
+
+
+ org.reflections
+ reflections
+ ${reflections-version}
+ test
+
+
+ org.jmockit
+ jmockit
+
+ test
+
+
+
+
+ sonatype-snapshots
+ https://oss.sonatype.org/content/repositories/snapshots
+
+ true
+
+
+
+
diff --git a/modules/swagger-codegen/src/main/java/config/Config.java b/modules/swagger-codegen/src/main/java/config/Config.java
new file mode 100644
index 00000000000..8b8f1b36a96
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/config/Config.java
@@ -0,0 +1,34 @@
+package config;
+
+import com.google.common.collect.ImmutableMap;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class Config {
+ private Map options;
+
+ public Config() {
+ this.options = new HashMap();
+ }
+
+ public Config(Map properties) {
+ this.options = properties;
+ }
+
+ public Map getOptions() {
+ return ImmutableMap.copyOf(options);
+ }
+
+ public boolean hasOption(String opt) {
+ return options.containsKey(opt);
+ }
+
+ public String getOption(String opt) {
+ return options.get(opt);
+ }
+
+ public void setOption(String opt, String value) {
+ options.put(opt, value);
+ }
+}
diff --git a/modules/swagger-codegen/src/main/java/config/ConfigParser.java b/modules/swagger-codegen/src/main/java/config/ConfigParser.java
new file mode 100644
index 00000000000..68cbb613f3a
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/config/ConfigParser.java
@@ -0,0 +1,45 @@
+package config;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import java.io.File;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ConfigParser {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(ConfigParser.class);
+
+ public static Config read(String location) {
+
+ LOGGER.info("reading config from " + location);
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ Config config = new Config();
+
+ try {
+ JsonNode rootNode = mapper.readTree(new File(location));
+ Iterator> optionNodes = rootNode.fields();
+
+ while (optionNodes.hasNext()) {
+ Map.Entry optionNode = (Map.Entry) optionNodes.next();
+
+ if (optionNode.getValue().isValueNode()) {
+ config.setOption(optionNode.getKey(), optionNode.getValue().asText());
+ } else {
+ LOGGER.warn("omitting non-value node " + optionNode.getKey());
+ }
+ }
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ return null;
+ }
+
+ return config;
+ }
+}
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
new file mode 100644
index 00000000000..5ed07851338
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java
@@ -0,0 +1,109 @@
+package io.swagger.codegen;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.Reader;
+import java.io.Writer;
+import java.util.Scanner;
+import java.util.regex.Pattern;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public abstract class AbstractGenerator {
+ private static final Logger LOGGER = LoggerFactory.getLogger(AbstractGenerator.class);
+
+ @SuppressWarnings("static-method")
+ public File writeToFile(String filename, String contents) throws IOException {
+ LOGGER.info("writing file " + filename);
+ File output = new File(filename);
+
+ if (output.getParent() != null && !new File(output.getParent()).exists()) {
+ File parent = new File(output.getParent());
+ parent.mkdirs();
+ }
+ Writer out = new BufferedWriter(new OutputStreamWriter(
+ new FileOutputStream(output), "UTF-8"));
+
+ out.write(contents);
+ out.close();
+ return output;
+ }
+
+ public String readTemplate(String name) {
+ try {
+ Reader reader = getTemplateReader(name);
+ if (reader == null) {
+ throw new RuntimeException("no file found");
+ }
+ Scanner s = new Scanner(reader).useDelimiter("\\A");
+ return s.hasNext() ? s.next() : "";
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ }
+ throw new RuntimeException("can't load template " + name);
+ }
+
+ public Reader getTemplateReader(String name) {
+ try {
+ 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
+ }
+ return new InputStreamReader(is);
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ }
+ throw new RuntimeException("can't load template " + name);
+ }
+
+ /**
+ * Get the template file path with template dir prepended, and use the
+ * library template if exists.
+ */
+ public String getFullTemplateFile(CodegenConfig config, String templateFile) {
+ String library = config.getLibrary();
+ if (library != null && !"".equals(library)) {
+ String libTemplateFile = config.templateDir() + File.separator +
+ "libraries" + File.separator + library + File.separator +
+ templateFile;
+
+ if (new File(libTemplateFile).exists()) {
+ return libTemplateFile;
+ }
+
+ 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;
+ }
+ }
+ String template = config.templateDir() + File.separator + templateFile;
+ if (new File(template).exists()) {
+ return template;
+ } else {
+ // Fall back to the template file embedded/packaged in the JAR file...
+ return config.embeddedTemplateDir() + File.separator + templateFile;
+ }
+ }
+
+ public boolean embeddedTemplateExists(String name) {
+ return this.getClass().getClassLoader().getResource(getCPResourcePath(name)) != null;
+ }
+
+ @SuppressWarnings("static-method")
+ public String getCPResourcePath(String name) {
+ if (!"/".equals(File.separator)) {
+ return name.replaceAll(Pattern.quote(File.separator), "/");
+ }
+ return name;
+ }
+}
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
new file mode 100644
index 00000000000..aacae1808e0
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CliOption.java
@@ -0,0 +1,103 @@
+package io.swagger.codegen;
+
+import io.swagger.annotations.ApiModelProperty;
+import io.swagger.models.properties.BooleanProperty;
+import io.swagger.models.properties.StringProperty;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public class CliOption {
+ private final String opt;
+ private String description;
+ private String type;
+ private String defaultValue;
+ private Map enumValues;
+
+ public CliOption(String opt, String description) {
+ this(opt, description, StringProperty.TYPE);
+ }
+
+ public CliOption(String opt, String description, String type) {
+ this.opt = opt;
+ this.description = description;
+ this.type = type;
+ }
+
+ @ApiModelProperty(name = "optionName")
+ public String getOpt() {
+ return opt;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ @ApiModelProperty(value = "Data type is based on the types supported by the JSON-Schema")
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getDefault() {
+ return defaultValue;
+ }
+
+ public void setDefault(String defaultValue) {
+ this.defaultValue = defaultValue;
+ }
+
+ public CliOption defaultValue(String defaultValue) {
+ this.defaultValue = defaultValue;
+ return this;
+ }
+
+ public CliOption addEnum(String value, String description) {
+ if (this.enumValues == null) {
+ this.enumValues = new LinkedHashMap();
+ }
+ if (!enumValues.containsKey(value)) {
+ enumValues.put(value, description);
+ }
+ return this;
+ }
+
+ public Map getEnum() {
+ return enumValues;
+ }
+
+ public void setEnum(Map enumValues) {
+ this.enumValues = enumValues;
+ }
+
+ public static CliOption newBoolean(String opt, String description) {
+ return new CliOption(opt, description, BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString());
+ }
+
+ public static CliOption newString(String opt, String description) {
+ return new CliOption(opt, description, StringProperty.TYPE);
+ }
+
+ @JsonIgnore
+ public String getOptionHelp() {
+ StringBuilder sb = new StringBuilder(description);
+ if(defaultValue != null) {
+ sb.append(" (Default: ").append(defaultValue).append(")");
+ }
+ if (enumValues != null) {
+ for (Map.Entry entry : enumValues.entrySet()) {
+ sb.append("\n ").append(entry.getKey()).append(" - ").append(entry.getValue());
+ }
+ }
+ return sb.toString();
+ }
+}
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
new file mode 100644
index 00000000000..57918dd9b35
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java
@@ -0,0 +1,76 @@
+package io.swagger.codegen;
+
+import io.swagger.annotations.ApiModelProperty;
+import io.swagger.codegen.auth.AuthParser;
+import io.swagger.models.Swagger;
+import io.swagger.models.auth.AuthorizationValue;
+
+import java.util.List;
+
+public class ClientOptInput {
+ private CodegenConfig config;
+ private ClientOpts opts;
+ private Swagger swagger;
+ private List auths;
+
+ public ClientOptInput swagger(Swagger swagger) {
+ this.setSwagger(swagger);
+ return this;
+ }
+
+ public ClientOptInput opts(ClientOpts opts) {
+ this.setOpts(opts);
+ return this;
+ }
+
+ public ClientOptInput config(CodegenConfig codegenConfig) {
+ this.setConfig(codegenConfig);
+ return this;
+ }
+
+ @Deprecated
+ public ClientOptInput auth(String urlEncodedAuthString) {
+ this.setAuth(urlEncodedAuthString);
+ return this;
+ }
+
+ @Deprecated
+ public String getAuth() {
+ return AuthParser.reconstruct(auths);
+ }
+
+ @Deprecated
+ public void setAuth(String urlEncodedAuthString) {
+ this.auths = AuthParser.parse(urlEncodedAuthString);
+ }
+
+ @Deprecated
+ public List getAuthorizationValues() {
+ return auths;
+ }
+
+ public CodegenConfig getConfig() {
+ return config;
+ }
+
+ public void setConfig(CodegenConfig config) {
+ this.config = config;
+ }
+
+ public ClientOpts getOpts() {
+ return opts;
+ }
+
+ public void setOpts(ClientOpts opts) {
+ this.opts = opts;
+ }
+
+ @ApiModelProperty(dataType = "Object")
+ public Swagger getSwagger() {
+ return swagger;
+ }
+
+ 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
new file mode 100644
index 00000000000..9c4d41f7bfd
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOpts.java
@@ -0,0 +1,57 @@
+package io.swagger.codegen;
+
+import io.swagger.codegen.auth.AuthMethod;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class ClientOpts {
+ protected String uri;
+ protected String target;
+ protected AuthMethod auth;
+ protected Map properties = new HashMap();
+ protected String outputDirectory;
+
+ public String getUri() {
+ return uri;
+ }
+
+ public void setUri(String uri) {
+ this.uri = uri;
+ }
+
+ public String getTarget() {
+ return target;
+ }
+
+ public void setTarget(String target) {
+ this.target = target;
+ }
+
+ public Map getProperties() {
+ return properties;
+ }
+
+ public void setProperties(Map properties) {
+ this.properties = properties;
+ }
+
+ public String getOutputDirectory() {
+ return outputDirectory;
+ }
+
+ public void setOutputDirectory(String outputDirectory) {
+ this.outputDirectory = outputDirectory;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("ClientOpts: {\n");
+ sb.append(" uri: ").append(uri).append(",");
+ sb.append(" auth: ").append(auth).append(",");
+ sb.append(properties);
+ sb.append("}");
+ return sb.toString();
+ }
+}
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
new file mode 100644
index 00000000000..649f068d16c
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java
@@ -0,0 +1,168 @@
+package io.swagger.codegen;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.ServiceLoader;
+
+import org.apache.commons.cli.BasicParser;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Options;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import config.Config;
+import config.ConfigParser;
+import io.swagger.models.Swagger;
+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
+public class Codegen extends DefaultGenerator {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(Codegen.class);
+
+ 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";
+
+ @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("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("c", "config", true, "location of the configuration file");
+
+ ClientOptInput clientOptInput = new ClientOptInput();
+ ClientOpts clientOpts = new ClientOpts();
+ Swagger swagger = null;
+
+ CommandLine cmd = null;
+ try {
+ CommandLineParser parser = new BasicParser();
+ CodegenConfig config = null;
+
+ cmd = parser.parse(options, args);
+ if (cmd.hasOption("d")) {
+ usage(options);
+ System.out.println(debugInfoOptions);
+ return;
+ }
+ if (cmd.hasOption("a")) {
+ clientOptInput.setAuth(cmd.getOptionValue("a"));
+ }
+ if (cmd.hasOption("l")) {
+ clientOptInput.setConfig(getConfig(cmd.getOptionValue("l")));
+ } else {
+ usage(options);
+ return;
+ }
+ if (cmd.hasOption("o")) {
+ clientOptInput.getConfig().setOutputDir(cmd.getOptionValue("o"));
+ }
+ if (cmd.hasOption("h")) {
+ if (cmd.hasOption("l")) {
+ config = getConfig(String.valueOf(cmd.getOptionValue("l")));
+ if (config != null) {
+ options.addOption("h", "help", true, config.getHelp());
+ usage(options);
+ return;
+ }
+ }
+ usage(options);
+ return;
+ }
+ if (cmd.hasOption("i")) {
+ swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true);
+ }
+ if (cmd.hasOption("c")) {
+ String configFile = cmd.getOptionValue("c");
+ Config genConfig = ConfigParser.read(configFile);
+ config = clientOptInput.getConfig();
+ if (null != genConfig && null != config) {
+ for (CliOption langCliOption : config.cliOptions()) {
+ if (genConfig.hasOption(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")));
+ }
+ } catch (Exception e) {
+ usage(options);
+ return;
+ }
+ try {
+ clientOptInput
+ .opts(clientOpts)
+ .swagger(swagger);
+ new Codegen().opts(clientOptInput).generate();
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage(), e);
+ }
+ }
+
+ public static List getExtensions() {
+ ServiceLoader loader = ServiceLoader.load(CodegenConfig.class);
+ List output = new ArrayList();
+ Iterator itr = loader.iterator();
+ while (itr.hasNext()) {
+ output.add(itr.next());
+ }
+ return output;
+ }
+
+ static void usage(Options options) {
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.printHelp("Codegen", options);
+ }
+
+ public static CodegenConfig getConfig(String name) {
+ if (configs.containsKey(name)) {
+ return configs.get(name);
+ } else {
+ // see if it's a class
+ try {
+ LOGGER.debug("loading class " + name);
+ Class> customClass = Class.forName(name);
+ LOGGER.debug("loaded");
+ return (CodegenConfig) customClass.newInstance();
+ } catch (Exception e) {
+ throw new RuntimeException("can't load class " + name);
+ }
+ }
+ }
+
+ static {
+ List extensions = getExtensions();
+ StringBuilder sb = new StringBuilder();
+
+ for (CodegenConfig config : extensions) {
+ if (sb.toString().length() != 0) {
+ sb.append(", ");
+ }
+ sb.append(config.getName());
+ configs.put(config.getName(), config);
+ configString = sb.toString();
+ }
+ }
+}
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
new file mode 100644
index 00000000000..720f2f8aa67
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java
@@ -0,0 +1,148 @@
+package io.swagger.codegen;
+
+import io.swagger.models.Model;
+import io.swagger.models.Operation;
+import io.swagger.models.Swagger;
+import io.swagger.models.auth.SecuritySchemeDefinition;
+import io.swagger.models.properties.Property;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public interface CodegenConfig {
+ CodegenType getTag();
+
+ String getName();
+
+ String getHelp();
+
+ Map additionalProperties();
+
+ String testPackage();
+
+ String apiPackage();
+
+ String apiFileFolder();
+
+ String apiTestFileFolder();
+
+ String fileSuffix();
+
+ String outputFolder();
+
+ String templateDir();
+
+ String embeddedTemplateDir();
+
+ String modelFileFolder();
+
+ String modelTestFileFolder();
+
+ String modelPackage();
+
+ String toApiName(String name);
+
+ String toApiVarName(String name);
+
+ String toModelName(String name);
+
+ String toParamName(String name);
+
+ String escapeText(String text);
+
+ String escapeReservedWord(String name);
+
+ String getTypeDeclaration(Property p);
+
+ String getTypeDeclaration(String name);
+
+ void processOpts();
+
+ List cliOptions();
+
+ String generateExamplePath(String path, Operation operation);
+
+ Set reservedWords();
+
+ List supportingFiles();
+
+ String getOutputDir();
+
+ void setOutputDir(String dir);
+
+ CodegenModel fromModel(String name, Model model);
+
+ 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);
+
+ List fromSecurity(Map schemes);
+
+ Set defaultIncludes();
+
+ Map typeMapping();
+
+ Map instantiationTypes();
+
+ Map importMapping();
+
+ Map apiTemplateFiles();
+
+ Map modelTemplateFiles();
+
+ Map apiTestTemplateFiles();
+
+ Map modelTestTemplateFiles();
+
+ Set languageSpecificPrimitives();
+
+ void preprocessSwagger(Swagger swagger);
+
+ void processSwagger(Swagger swagger);
+
+ String toApiFilename(String name);
+
+ String toModelFilename(String name);
+
+ String toApiTestFilename(String name);
+
+ String toModelTestFilename(String name);
+
+ String toModelImport(String name);
+
+ String toApiImport(String name);
+
+ void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations);
+
+ Map postProcessModels(Map objs);
+
+ Map postProcessOperations(Map objs);
+
+ Map postProcessSupportingFileData(Map objs);
+
+ void postProcessModelProperty(CodegenModel model, CodegenProperty property);
+
+ void postProcessParameter(CodegenParameter parameter);
+
+ String apiFilename(String templateName, String tag);
+
+ String apiTestFilename(String templateName, String tag);
+
+ boolean shouldOverwrite(String filename);
+
+ boolean isSkipOverwrite();
+
+ void setSkipOverwrite(boolean skipOverwrite);
+
+ Map supportedLibraries();
+
+ void setLibrary(String library);
+
+ /**
+ * Library template (sub-template).
+ */
+ String getLibrary();
+}
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
new file mode 100644
index 00000000000..45a57e7bb3a
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfigLoader.java
@@ -0,0 +1,34 @@
+package io.swagger.codegen;
+
+import java.util.ServiceLoader;
+
+import static java.util.ServiceLoader.load;
+
+public class CodegenConfigLoader {
+ /**
+ * Tries to load config class with SPI first, then with class name directly from classpath
+ *
+ * @param name name of config, or full qualified class name in classpath
+ * @return config class
+ */
+ public static CodegenConfig forName(String name) {
+ ServiceLoader loader = load(CodegenConfig.class);
+
+ StringBuilder availableConfigs = new StringBuilder();
+
+ for (CodegenConfig config : loader) {
+ if (config.getName().equals(name)) {
+ return config;
+ }
+
+ availableConfigs.append(config.getName()).append("\n");
+ }
+
+ // else try to load directly
+ 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);
+ }
+ }
+}
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
new file mode 100644
index 00000000000..f0d3591ba3f
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java
@@ -0,0 +1,82 @@
+package io.swagger.codegen;
+
+/**
+ * A class for storing constants that are used throughout the project.
+ */
+public class CodegenConstants {
+ public static final String API_PACKAGE = "apiPackage";
+ public static final String API_PACKAGE_DESC = "package for generated api classes";
+
+ public static final String MODEL_PACKAGE = "modelPackage";
+ public static final String MODEL_PACKAGE_DESC = "package for generated models";
+
+ public static final String TEMPLATE_DIR = "templateDir";
+
+
+ public static final String INVOKER_PACKAGE = "invokerPackage";
+ public static final String INVOKER_PACKAGE_DESC = "root package for generated code";
+
+ public static final String GROUP_ID = "groupId";
+ public static final String GROUP_ID_DESC = "groupId in generated pom.xml";
+
+ public static final String ARTIFACT_ID = "artifactId";
+ public static final String ARTIFACT_ID_DESC = "artifactId in generated pom.xml";
+
+ public static final String ARTIFACT_VERSION = "artifactVersion";
+ public static final String ARTIFACT_VERSION_DESC = "artifact version in generated pom.xml";
+
+ public static final String SOURCE_FOLDER = "sourceFolder";
+ public static final String SOURCE_FOLDER_DESC = "source folder for generated code";
+
+ public static final String IMPL_FOLDER = "implFolder";
+ public static final String IMPL_FOLDER_DESC = "folder for generated implementation code";
+
+ public static final String LOCAL_VARIABLE_PREFIX = "localVariablePrefix";
+ public static final String LOCAL_VARIABLE_PREFIX_DESC = "prefix for generated code members and local variables";
+
+ 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 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 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 USE_DATETIME_OFFSET = "useDateTimeOffset";
+ public static final String USE_DATETIME_OFFSET_DESC = "Use DateTimeOffset to model date-time properties";
+
+ public static final String ENSURE_UNIQUE_PARAMS = "ensureUniqueParams";
+ public static final String ENSURE_UNIQUE_PARAMS_DESC = "Whether to ensure parameter names are unique in an operation (rename parameters that are not).";
+
+ public static final String PACKAGE_NAME = "packageName";
+ public static final String PACKAGE_VERSION = "packageVersion";
+ public static final String 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_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 RETURN_ICOLLECTION = "returnICollection";
+ 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 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 enum MODEL_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case, original}
+
+}
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
new file mode 100644
index 00000000000..4df150f81a8
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java
@@ -0,0 +1,23 @@
+package io.swagger.codegen;
+
+import io.swagger.models.ExternalDocs;
+
+import java.util.*;
+
+public class CodegenModel {
+ public String parent, parentSchema;
+ public String name, classname, description, classVarName, modelJson, dataType;
+ public String unescapedDescription;
+ public String defaultValue;
+ public List vars = new ArrayList();
+ public List allowableValues;
+
+ // list of all required parameters
+ public Set mandatory = new HashSet();
+
+ public Set imports = new TreeSet();
+ public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum;
+ public ExternalDocs externalDocs;
+
+ public Map vendorExtensions;
+}
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
new file mode 100644
index 00000000000..4c2b4d4eb87
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java
@@ -0,0 +1,39 @@
+package io.swagger.codegen;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public final class CodegenModelFactory {
+
+ 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
+ */
+ public static void setTypeMapping(CodegenModelType type, Class> implementation) {
+ if (!type.getDefaultImplementation().isAssignableFrom(implementation)) {
+ throw new IllegalArgumentException(implementation.getSimpleName() + " doesn't extend " + type.getDefaultImplementation().getSimpleName());
+ }
+ try {
+ implementation.newInstance();
+ } catch (Exception e) {
+ throw new IllegalArgumentException(e);
+ }
+ typeMapping.put(type, implementation);
+ }
+
+ @SuppressWarnings("unchecked")
+ public static T newInstance(CodegenModelType type) {
+ Class> classType = typeMapping.get(type);
+ try {
+ return (T) (classType != null ? classType : type.getDefaultImplementation()).newInstance();
+ } catch (InstantiationException e) {
+ throw new RuntimeException(e);
+ } catch (IllegalAccessException 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
new file mode 100644
index 00000000000..dce8ab0e2e5
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelType.java
@@ -0,0 +1,21 @@
+package io.swagger.codegen;
+
+public enum CodegenModelType {
+
+ MODEL(CodegenModel.class),
+ OPERATION(CodegenOperation.class),
+ PARAMETER(CodegenParameter.class),
+ PROPERTY(CodegenProperty.class),
+ RESPONSE(CodegenResponse.class),
+ SECURITY(CodegenSecurity.class);
+
+ private final Class> defaultImplementation;
+
+ private CodegenModelType(Class> defaultImplementation) {
+ this.defaultImplementation = defaultImplementation;
+ }
+
+ public Class> getDefaultImplementation() {
+ return 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
new file mode 100644
index 00000000000..956e906b44f
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java
@@ -0,0 +1,90 @@
+package io.swagger.codegen;
+
+import io.swagger.models.ExternalDocs;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class CodegenOperation {
+ public final List responseHeaders = new ArrayList();
+ public Boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams,
+ returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer,
+ isListContainer, isMultipart, hasMore = Boolean.TRUE,
+ isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE;
+ public String path, operationId, returnType, httpMethod, returnBaseType,
+ returnContainer, summary, notes, baseName, defaultResponse;
+ public List> consumes, produces;
+ public CodegenParameter bodyParam;
+ public List allParams = new ArrayList();
+ public List bodyParams = new ArrayList();
+ public List pathParams = new ArrayList();
+ public List queryParams = new ArrayList();
+ public List headerParams = new ArrayList();
+ public List formParams = new ArrayList();
+ public List authMethods;
+ public List tags;
+ public List responses = new ArrayList();
+ public Set imports = new HashSet();
+ public List> examples;
+ public ExternalDocs externalDocs;
+ public Map vendorExtensions;
+ public String nickname; // legacy support
+
+ /**
+ * Check if there's at least one parameter
+ *
+ * @return true if parameter exists, false otherwise
+ */
+ private static boolean nonempty(List params) {
+ return params != null && params.size() > 0;
+ }
+
+ /**
+ * Check if there's at least one body parameter
+ *
+ * @return true if body parameter exists, false otherwise
+ */
+ public boolean getHasBodyParam() {
+ return nonempty(bodyParams);
+ }
+
+ /**
+ * Check if there's at least one query parameter
+ *
+ * @return true if query parameter exists, false otherwise
+ */
+ public boolean getHasQueryParams() {
+ return nonempty(queryParams);
+ }
+
+ /**
+ * Check if there's at least one header parameter
+ *
+ * @return true if header parameter exists, false otherwise
+ */
+ public boolean getHasHeaderParams() {
+ return nonempty(headerParams);
+ }
+
+ /**
+ * Check if there's at least one path parameter
+ *
+ * @return true if path parameter exists, false otherwise
+ */
+ public boolean getHasPathParams() {
+ return nonempty(pathParams);
+ }
+
+ /**
+ * Check if there's at least one form parameter
+ *
+ * @return true if any form parameter exists, false otherwise
+ */
+ public boolean getHasFormParams() {
+ return nonempty(formParams);
+ }
+
+}
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
new file mode 100644
index 00000000000..9bf2858161d
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java
@@ -0,0 +1,118 @@
+package io.swagger.codegen;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.List;
+
+public class CodegenParameter {
+ public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
+ isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer,
+ secondaryParam, isBinary, isCollectionFormatMulti;
+ public String baseName, paramName, dataType, collectionFormat, description, baseType, defaultValue;
+ public String jsonSchema;
+ public boolean isEnum;
+ public List _enum;
+ public Map allowableValues;
+ public Map vendorExtensions;
+
+ /**
+ * 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.
+ */
+ public Number maximum;
+ /**
+ * See http://json-schema.org/latest/json-schema-validation.html#anchor17
+ */
+ public Boolean exclusiveMaximum;
+ /**
+ * See http://json-schema.org/latest/json-schema-validation.html#anchor21
+ */
+ public Number minimum;
+ /**
+ * See http://json-schema.org/latest/json-schema-validation.html#anchor21
+ */
+ public Boolean exclusiveMinimum;
+ /**
+ * See http://json-schema.org/latest/json-schema-validation.html#anchor26
+ */
+ public Integer maxLength;
+ /**
+ * 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
+ */
+ public String pattern;
+ /**
+ * 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
+ */
+ public Integer minItems;
+ /**
+ * See http://json-schema.org/latest/json-schema-validation.html#anchor49
+ */
+ public Boolean uniqueItems;
+ /**
+ * See http://json-schema.org/latest/json-schema-validation.html#anchor14
+ */
+ public Number multipleOf;
+
+ public CodegenParameter copy() {
+ CodegenParameter output = new CodegenParameter();
+ output.isFile = this.isFile;
+ output.notFile = this.notFile;
+ output.hasMore = this.hasMore;
+ output.isContainer = this.isContainer;
+ output.secondaryParam = this.secondaryParam;
+ output.baseName = this.baseName;
+ output.paramName = this.paramName;
+ output.dataType = this.dataType;
+ output.collectionFormat = this.collectionFormat;
+ output.isCollectionFormatMulti = this.isCollectionFormatMulti;
+ output.description = this.description;
+ output.baseType = this.baseType;
+ output.isFormParam = this.isFormParam;
+ output.isQueryParam = this.isQueryParam;
+ output.isPathParam = this.isPathParam;
+ output.isHeaderParam = this.isHeaderParam;
+ output.isCookieParam = this.isCookieParam;
+ output.isBodyParam = this.isBodyParam;
+ output.required = this.required;
+ output.maximum = this.maximum;
+ output.exclusiveMaximum = this.exclusiveMaximum;
+ output.minimum = this.minimum;
+ output.exclusiveMinimum = this.exclusiveMinimum;
+ output.maxLength = this.maxLength;
+ output.minLength = this.minLength;
+ output.pattern = this.pattern;
+ output.maxItems = this.maxItems;
+ output.minItems = this.minItems;
+ output.uniqueItems = this.uniqueItems;
+ output.multipleOf = this.multipleOf;
+ output.jsonSchema = this.jsonSchema;
+ output.defaultValue = this.defaultValue;
+ output.isEnum = this.isEnum;
+ if (this._enum != null) {
+ output._enum = new ArrayList(this._enum);
+ }
+ if (this.allowableValues != null) {
+ output.allowableValues = new HashMap(this.allowableValues);
+ }
+ output.vendorExtensions = this.vendorExtensions;
+ output.isBinary = this.isBinary;
+
+ return output;
+ }
+}
+
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
new file mode 100644
index 00000000000..d80bc38a4c7
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java
@@ -0,0 +1,191 @@
+package io.swagger.codegen;
+
+import java.util.List;
+import java.util.Map;
+
+public class CodegenProperty {
+ public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum,
+ name, min, max, defaultValue, defaultValueWithParam, baseType, containerType;
+
+ public String unescapedDescription;
+
+ /**
+ * 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
+ */
+ public Integer minLength;
+ /**
+ * pattern validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.3
+ */
+ public String pattern;
+ /**
+ * A free-form property to include an example of an instance for this schema.
+ */
+ public String example;
+
+ public String jsonSchema;
+ public Double minimum;
+ public Double maximum;
+ public Boolean exclusiveMinimum;
+ public Boolean exclusiveMaximum;
+ public Boolean hasMore, required, secondaryParam;
+ public Boolean isPrimitiveType, isContainer, isNotContainer;
+ public boolean isEnum;
+ public Boolean isReadOnly = false;
+ public List _enum;
+ public Map allowableValues;
+ public CodegenProperty items;
+ public Map vendorExtensions;
+
+ @Override
+ public int hashCode()
+ {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((_enum == null) ? 0 : _enum.hashCode());
+ result = prime * result + ((allowableValues == null) ? 0 : allowableValues.hashCode());
+ result = prime * result + ((baseName == null) ? 0 : baseName.hashCode());
+ result = prime * result + ((baseType == null) ? 0 : baseType.hashCode());
+ result = prime * result + ((complexType == null) ? 0 : complexType.hashCode());
+ result = prime * result + ((containerType == null) ? 0 : containerType.hashCode());
+ result = prime * result + ((datatype == null) ? 0 : datatype.hashCode());
+ result = prime * result + ((datatypeWithEnum == null) ? 0 : datatypeWithEnum.hashCode());
+ result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode());
+ result = prime * result + ((defaultValueWithParam == null) ? 0 : defaultValueWithParam.hashCode());
+ result = prime * result + ((description == null) ? 0 : description.hashCode());
+ result = prime * result + ((example == null) ? 0 : example.hashCode());
+ result = prime * result + ((exclusiveMaximum == null) ? 0 : exclusiveMaximum.hashCode());
+ result = prime * result + ((exclusiveMinimum == null) ? 0 : exclusiveMinimum.hashCode());
+ result = prime * result + ((getter == null) ? 0 : getter.hashCode());
+ result = prime * result + ((hasMore == null) ? 0 : hasMore.hashCode());
+ result = prime * result + ((isContainer == null) ? 0 : isContainer.hashCode());
+ result = prime * result + (isEnum ? 1231 : 1237);
+ result = prime * result + ((isNotContainer == null) ? 0 : isNotContainer.hashCode());
+ result = prime * result + ((isPrimitiveType == null) ? 0 : isPrimitiveType.hashCode());
+ result = prime * result + ((isReadOnly == null) ? 0 : isReadOnly.hashCode());
+ result = prime * result + ((items == null) ? 0 : items.hashCode());
+ result = prime * result + ((jsonSchema == null) ? 0 : jsonSchema.hashCode());
+ result = prime * result + ((max == null) ? 0 : max.hashCode());
+ result = prime * result + ((maxLength == null) ? 0 : maxLength.hashCode());
+ result = prime * result + ((maximum == null) ? 0 : maximum.hashCode());
+ result = prime * result + ((min == null) ? 0 : min.hashCode());
+ result = prime * result + ((minLength == null) ? 0 : minLength.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 == null) ? 0 : required.hashCode());
+ result = prime * result + ((secondaryParam == null) ? 0 : secondaryParam.hashCode());
+ result = prime * result + ((setter == null) ? 0 : setter.hashCode());
+ result = prime * result + ((unescapedDescription == null) ? 0 : unescapedDescription.hashCode());
+ result = prime * result + ((vendorExtensions == null) ? 0 : vendorExtensions.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ final CodegenProperty other = (CodegenProperty) obj;
+ 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)) {
+ return false;
+ }
+ if ((this.getter == null) ? (other.getter != null) : !this.getter.equals(other.getter)) {
+ return false;
+ }
+ 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)) {
+ return false;
+ }
+ 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)) {
+ return false;
+ }
+ if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
+ return false;
+ }
+ if ((this.min == null) ? (other.min != null) : !this.min.equals(other.min)) {
+ return false;
+ }
+ 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)) {
+ return false;
+ }
+ 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)) {
+ return false;
+ }
+ 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))) {
+ return false;
+ }
+ if ((this.pattern == null) ? (other.pattern != null) : !this.pattern.equals(other.pattern)) {
+ return false;
+ }
+ 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)) {
+ return false;
+ }
+ 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))) {
+ return false;
+ }
+ if (this.exclusiveMinimum != other.exclusiveMinimum && (this.exclusiveMinimum == null || !this.exclusiveMinimum.equals(other.exclusiveMinimum))) {
+ return false;
+ }
+ if (this.exclusiveMaximum != other.exclusiveMaximum && (this.exclusiveMaximum == null || !this.exclusiveMaximum.equals(other.exclusiveMaximum))) {
+ return false;
+ }
+ if (this.required != other.required && (this.required == null || !this.required.equals(other.required))) {
+ return false;
+ }
+ if (this.secondaryParam != other.secondaryParam && (this.secondaryParam == null || !this.secondaryParam.equals(other.secondaryParam))) {
+ return false;
+ }
+ if (this.isPrimitiveType != other.isPrimitiveType && (this.isPrimitiveType == null || !this.isPrimitiveType.equals(other.isPrimitiveType))) {
+ return false;
+ }
+ if (this.isContainer != other.isContainer && (this.isContainer == null || !this.isContainer.equals(other.isContainer))) {
+ return false;
+ }
+ if (this.isNotContainer != other.isNotContainer && (this.isNotContainer == null || !this.isNotContainer.equals(other.isNotContainer))) {
+ return false;
+ }
+ if (this.isEnum != other.isEnum) {
+ return false;
+ }
+ 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))) {
+ return false;
+ }
+ if (this.vendorExtensions != other.vendorExtensions && (this.vendorExtensions == null || !this.vendorExtensions.equals(other.vendorExtensions))) {
+ return false;
+ }
+ return true;
+ }
+}
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
new file mode 100644
index 00000000000..e20735b1418
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java
@@ -0,0 +1,25 @@
+package io.swagger.codegen;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+public class CodegenResponse {
+ public final List headers = new ArrayList();
+ public String code, message;
+ public Boolean hasMore;
+ public List> examples;
+ public String dataType, baseType, containerType;
+ public Boolean isDefault;
+ public Boolean simpleType;
+ public Boolean primitiveType;
+ public Boolean isMapContainer;
+ public Boolean isListContainer;
+ public Boolean isBinary = Boolean.FALSE;
+ public Object schema;
+ public String jsonSchema;
+
+ public boolean isWildcard() {
+ return "0".equals(code) || "default".equals(code);
+ }
+}
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
new file mode 100644
index 00000000000..10118206383
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java
@@ -0,0 +1,16 @@
+package io.swagger.codegen;
+
+import java.util.List;
+import java.util.Map;
+
+public class CodegenSecurity {
+ public String name;
+ public String type;
+ public Boolean hasMore, isBasic, isOAuth, isApiKey;
+ // ApiKey specific
+ public String keyParamName;
+ public Boolean isKeyInQuery, isKeyInHeader;
+ // Oauth specific
+ public String flow, authorizationUrl, tokenUrl;
+ public List> scopes;
+}
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
new file mode 100644
index 00000000000..8d65290e8f8
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenType.java
@@ -0,0 +1,36 @@
+package io.swagger.codegen;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public enum CodegenType {
+ CLIENT, SERVER, DOCUMENTATION, OTHER;
+
+ private static Map names = new HashMap();
+
+ @JsonCreator
+ public static CodegenType forValue(String value) {
+ return names.get(value.toLowerCase());
+ }
+
+ @JsonValue
+ public String toValue() {
+ for (Map.Entry entry : names.entrySet()) {
+ if (entry.getValue() == this) {
+ return entry.getKey();
+ }
+ }
+
+ return null; // or fail
+ }
+
+ static {
+ names.put("client", CLIENT);
+ names.put("server", SERVER);
+ 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
new file mode 100644
index 00000000000..dd1faa82ed4
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java
@@ -0,0 +1,2210 @@
+package io.swagger.codegen;
+
+import com.google.common.base.Function;
+import com.google.common.collect.Lists;
+
+import io.swagger.codegen.examples.ExampleGenerator;
+import io.swagger.models.ArrayModel;
+import io.swagger.models.ComposedModel;
+import io.swagger.models.Model;
+import io.swagger.models.ModelImpl;
+import io.swagger.models.Operation;
+import io.swagger.models.RefModel;
+import io.swagger.models.Response;
+import io.swagger.models.Swagger;
+import io.swagger.models.auth.ApiKeyAuthDefinition;
+import io.swagger.models.auth.BasicAuthDefinition;
+import io.swagger.models.auth.In;
+import io.swagger.models.auth.OAuth2Definition;
+import io.swagger.models.auth.SecuritySchemeDefinition;
+import io.swagger.models.parameters.BodyParameter;
+import io.swagger.models.parameters.CookieParameter;
+import io.swagger.models.parameters.FormParameter;
+import io.swagger.models.parameters.HeaderParameter;
+import io.swagger.models.parameters.Parameter;
+import io.swagger.models.parameters.PathParameter;
+import io.swagger.models.parameters.QueryParameter;
+import io.swagger.models.parameters.SerializableParameter;
+import io.swagger.models.properties.*;
+import io.swagger.models.properties.PropertyBuilder.PropertyId;
+import io.swagger.util.Json;
+
+import org.apache.commons.lang.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+
+public class DefaultCodegen {
+ protected static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class);
+
+ protected String outputFolder = "";
+ protected Set defaultIncludes = new HashSet();
+ protected Map typeMapping = new HashMap();
+ protected Map instantiationTypes = new HashMap();
+ protected Set reservedWords = new HashSet();
+ protected Set languageSpecificPrimitives = new HashSet();
+ protected Map importMapping = new HashMap();
+ protected String modelPackage = "", apiPackage = "", fileSuffix;
+ protected String testPackage = "";
+ protected Map apiTemplateFiles = new HashMap();
+ protected Map modelTemplateFiles = new HashMap();
+ protected Map apiTestTemplateFiles = new HashMap();
+ protected Map modelTestTemplateFiles = new HashMap();
+ protected String templateDir;
+ protected String embeddedTemplateDir;
+ protected Map additionalProperties = new HashMap();
+ protected List supportingFiles = new ArrayList();
+ protected List cliOptions = new ArrayList();
+ protected boolean skipOverwrite;
+ protected boolean supportsInheritance;
+ protected Map supportedLibraries = new LinkedHashMap();
+ protected String library;
+ protected Boolean sortParamsByRequiredFlag = true;
+ protected Boolean ensureUniqueParams = true;
+
+ public List cliOptions() {
+ return cliOptions;
+ }
+
+ public void processOpts() {
+ if (additionalProperties.containsKey(CodegenConstants.TEMPLATE_DIR)) {
+ this.setTemplateDir((String) additionalProperties.get(CodegenConstants.TEMPLATE_DIR));
+ }
+
+ if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) {
+ this.setModelPackage((String) additionalProperties.get(CodegenConstants.MODEL_PACKAGE));
+ }
+
+ if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) {
+ this.setApiPackage((String) additionalProperties.get(CodegenConstants.API_PACKAGE));
+ }
+
+ if (additionalProperties.containsKey(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) {
+ 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()));
+ }
+ }
+
+ // override with any special post-processing
+ @SuppressWarnings("static-method")
+ public Map postProcessModels(Map objs) {
+ return objs;
+ }
+
+ // override with any special post-processing
+ @SuppressWarnings("static-method")
+ public Map postProcessOperations(Map objs) {
+ return objs;
+ }
+
+ // override with any special post-processing
+ @SuppressWarnings("static-method")
+ public Map postProcessSupportingFileData(Map objs) {
+ return objs;
+ }
+
+ // override to post-process any model properties
+ @SuppressWarnings("unused")
+ public void postProcessModelProperty(CodegenModel model, CodegenProperty property){
+ }
+
+ // override to post-process any parameters
+ @SuppressWarnings("unused")
+ public void postProcessParameter(CodegenParameter parameter){
+ }
+
+ //override with any special handling of the entire swagger spec
+ @SuppressWarnings("unused")
+ public void preprocessSwagger(Swagger swagger) {
+ }
+
+ // override with any special handling of the entire swagger spec
+ @SuppressWarnings("unused")
+ public void processSwagger(Swagger swagger) {
+ }
+
+ // override with any special text escaping logic
+ @SuppressWarnings("static-method")
+ public String escapeText(String input) {
+ if (input != null) {
+ input = input.trim(); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
+ String output = input.replaceAll("\n", "\\\\n");
+ output = output.replace("\r", "\\r");
+ output = output.replace("\"", "\\\"");
+ return output;
+ }
+ return input;
+ }
+
+ public Set defaultIncludes() {
+ return defaultIncludes;
+ }
+
+ public Map typeMapping() {
+ return typeMapping;
+ }
+
+ public Map instantiationTypes() {
+ return instantiationTypes;
+ }
+
+ public Set reservedWords() {
+ return reservedWords;
+ }
+
+ public Set languageSpecificPrimitives() {
+ return languageSpecificPrimitives;
+ }
+
+ public Map importMapping() {
+ return importMapping;
+ }
+
+ public String testPackage() {
+ return testPackage;
+ }
+
+ public String modelPackage() {
+ return modelPackage;
+ }
+
+ public String apiPackage() {
+ return apiPackage;
+ }
+
+ public String fileSuffix() {
+ return fileSuffix;
+ }
+
+ public String templateDir() {
+ return templateDir;
+ }
+
+ public String embeddedTemplateDir() {
+ if (embeddedTemplateDir != null) {
+ return embeddedTemplateDir;
+ } else {
+ return templateDir;
+ }
+ }
+
+ public Map apiTestTemplateFiles() {
+ return apiTestTemplateFiles;
+ }
+
+ public Map modelTestTemplateFiles() {
+ return modelTestTemplateFiles;
+ }
+
+ public Map apiTemplateFiles() {
+ return apiTemplateFiles;
+ }
+
+ public Map modelTemplateFiles() {
+ return modelTemplateFiles;
+ }
+
+ public String apiFileFolder() {
+ return outputFolder + "/" + apiPackage().replace('.', '/');
+ }
+
+ public String modelFileFolder() {
+ return outputFolder + "/" + modelPackage().replace('.', '/');
+ }
+
+ public String apiTestFileFolder() {
+ return outputFolder + "/" + testPackage().replace('.', '/');
+ }
+
+ public String modelTestFileFolder() {
+ return outputFolder + "/" + testPackage().replace('.', '/');
+ }
+
+ public Map additionalProperties() {
+ return additionalProperties;
+ }
+
+ public List supportingFiles() {
+ return supportingFiles;
+ }
+
+ public String outputFolder() {
+ return outputFolder;
+ }
+
+ public void setOutputDir(String dir) {
+ this.outputFolder = dir;
+ }
+
+ public String getOutputDir() {
+ return outputFolder();
+ }
+
+ public void setTemplateDir(String templateDir) {
+ this.templateDir = templateDir;
+ }
+
+ public void setModelPackage(String modelPackage) {
+ this.modelPackage = modelPackage;
+ }
+
+ public void setApiPackage(String apiPackage) {
+ this.apiPackage = apiPackage;
+ }
+
+ public void setSortParamsByRequiredFlag(Boolean sortParamsByRequiredFlag) {
+ this.sortParamsByRequiredFlag = sortParamsByRequiredFlag;
+ }
+
+ public void setEnsureUniqueParams(Boolean ensureUniqueParams) {
+ this.ensureUniqueParams = ensureUniqueParams;
+ }
+
+ /**
+ * Return the file name of the Api Test
+ *
+ * @param name the file name of the Api
+ * @return the file name of the Api
+ */
+ public String toApiFilename(String name) {
+ return toApiName(name);
+ }
+
+ /**
+ * Return the file name of the Api Test
+ *
+ * @param name the file name of the Api
+ * @return the file name of the Api
+ */
+ public String toApiTestFilename(String name) {
+ return toApiName(name) + "Test";
+ }
+
+ /**
+ * Return the variable name in the Api
+ *
+ * @param name the varible name of the Api
+ * @return the snake-cased variable name
+ */
+ public String toApiVarName(String name) {
+ return snakeCase(name);
+ }
+
+ /**
+ * Return the capitalized file name of the model test
+ *
+ * @param name the model name
+ * @return the file name of the model
+ */
+ public String toModelFilename(String name) {
+ return initialCaps(name);
+ }
+
+ /**
+ * Return the capitalized file name of the model test
+ *
+ * @param name the model name
+ * @return the file name of the model
+ */
+ public String toModelTestFilename(String name) {
+ return initialCaps(name) + "Test";
+ }
+
+ /**
+ * Return the operation ID (method name)
+ *
+ * @param operationId operation ID
+ * @return the sanitized method name
+ */
+ @SuppressWarnings("static-method")
+ 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");
+ }
+
+ return operationId;
+ }
+
+ /**
+ * 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
+ */
+ public String toVarName(String name) {
+ if (reservedWords.contains(name)) {
+ return escapeReservedWord(name);
+ } else {
+ return name;
+ }
+ }
+
+ /**
+ * 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'.
+ if (reservedWords.contains(name)) {
+ return escapeReservedWord(name);
+ }
+ return name;
+ }
+
+ /**
+ * Return the Enum name (e.g. StatusEnum given 'status')
+ *
+ * @param property Codegen property object
+ * @return the Enum name
+ */
+ @SuppressWarnings("static-method")
+ public String toEnumName(CodegenProperty property) {
+ return StringUtils.capitalize(property.name) + "Enum";
+ }
+
+ /**
+ * Return the escaped name of the reserved word
+ *
+ * @param name the name to be escaped
+ * @return the escaped reserved word
+ *
+ * throws Runtime exception as reserved word is not allowed (default behavior)
+ */
+ @SuppressWarnings("static-method")
+ public String escapeReservedWord(String name) {
+ throw new RuntimeException("reserved word " + name + " not allowed");
+ }
+
+ /**
+ * Return the fully-qualified "Model" name for import
+ *
+ * @param name the name of the "Model"
+ * @return the fully-qualified "Model" name for import
+ */
+ public String toModelImport(String name) {
+ if ("".equals(modelPackage())) {
+ return name;
+ } else {
+ return modelPackage() + "." + name;
+ }
+ }
+
+ /**
+ * Return the fully-qualified "Api" name for import
+ *
+ * @param name the name of the "Api"
+ * @return the fully-qualified "Api" name for import
+ */
+ public String toApiImport(String name) {
+ return apiPackage() + "." + 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.
+ *
+ *
+ * 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")
+ );
+
+ typeMapping = new HashMap();
+ typeMapping.put("array", "List");
+ typeMapping.put("map", "Map");
+ typeMapping.put("List", "List");
+ typeMapping.put("boolean", "Boolean");
+ typeMapping.put("string", "String");
+ typeMapping.put("int", "Integer");
+ typeMapping.put("float", "Float");
+ typeMapping.put("number", "BigDecimal");
+ typeMapping.put("DateTime", "Date");
+ typeMapping.put("long", "Long");
+ typeMapping.put("short", "Short");
+ typeMapping.put("char", "String");
+ typeMapping.put("double", "Double");
+ typeMapping.put("object", "Object");
+ typeMapping.put("integer", "Integer");
+ typeMapping.put("ByteArray", "byte[]");
+ typeMapping.put("binary", "byte[]");
+
+
+ instantiationTypes = new HashMap();
+
+ reservedWords = new HashSet();
+
+ importMapping = new HashMap();
+ importMapping.put("BigDecimal", "java.math.BigDecimal");
+ importMapping.put("UUID", "java.util.UUID");
+ importMapping.put("File", "java.io.File");
+ importMapping.put("Date", "java.util.Date");
+ importMapping.put("Timestamp", "java.sql.Timestamp");
+ importMapping.put("Map", "java.util.Map");
+ importMapping.put("HashMap", "java.util.HashMap");
+ importMapping.put("Array", "java.util.List");
+ importMapping.put("ArrayList", "java.util.ArrayList");
+ importMapping.put("List", "java.util.*");
+ importMapping.put("Set", "java.util.*");
+ importMapping.put("DateTime", "org.joda.time.*");
+ importMapping.put("LocalDateTime", "org.joda.time.*");
+ importMapping.put("LocalDate", "org.joda.time.*");
+ importMapping.put("LocalTime", "org.joda.time.*");
+
+ 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()));
+ }
+
+ /**
+ * Return the example path
+ *
+ * @param path the path of the operation
+ * @param operation Swagger operation object
+ * @return string presentation of the example path
+ */
+ @SuppressWarnings("static-method")
+ public String generateExamplePath(String path, Operation operation) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(path);
+
+ if (operation.getParameters() != null) {
+ int count = 0;
+
+ for (Parameter param : operation.getParameters()) {
+ if (param instanceof QueryParameter) {
+ StringBuilder paramPart = new StringBuilder();
+ QueryParameter qp = (QueryParameter) param;
+
+ if (count == 0) {
+ paramPart.append("?");
+ } else {
+ paramPart.append(",");
+ }
+ count += 1;
+ if (!param.getRequired()) {
+ paramPart.append("[");
+ }
+ paramPart.append(param.getName()).append("=");
+ paramPart.append("{");
+ if (qp.getCollectionFormat() != null) {
+ paramPart.append(param.getName() + "1");
+ if ("csv".equals(qp.getCollectionFormat())) {
+ paramPart.append(",");
+ } else if ("pipes".equals(qp.getCollectionFormat())) {
+ paramPart.append("|");
+ } else if ("tsv".equals(qp.getCollectionFormat())) {
+ paramPart.append("\t");
+ } else if ("multi".equals(qp.getCollectionFormat())) {
+ paramPart.append("&").append(param.getName()).append("=");
+ paramPart.append(param.getName() + "2");
+ }
+ } else {
+ paramPart.append(param.getName());
+ }
+ paramPart.append("}");
+ if (!param.getRequired()) {
+ paramPart.append("]");
+ }
+ sb.append(paramPart.toString());
+ }
+ }
+ }
+
+ return sb.toString();
+ }
+
+ /**
+ * Return the instantiation type of the property, especially for map and array
+ *
+ * @param p Swagger property object
+ * @return string presentation of the instantiation type of the property
+ */
+ public String toInstantiationType(Property p) {
+ if (p instanceof MapProperty) {
+ MapProperty ap = (MapProperty) 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);
+ }
+ String inner = getSwaggerType(additionalProperties2);
+ return instantiationTypes.get("map") + "";
+ } else if (p instanceof ArrayProperty) {
+ ArrayProperty ap = (ArrayProperty) p;
+ String inner = getSwaggerType(ap.getItems());
+ return instantiationTypes.get("array") + "<" + inner + ">";
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Return the example value of the property
+ *
+ * @param p Swagger property object
+ * @return string presentation of the example value of the property
+ */
+ @SuppressWarnings("static-method")
+ public String toExampleValue(Property p) {
+ if (p instanceof StringProperty) {
+ return "null";
+ } else if (p instanceof BooleanProperty) {
+ return "null";
+ } 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.getExample() != null) {
+ return dp.getExample().toString();
+ }
+ return "null";
+ } else if (p instanceof FloatProperty) {
+ FloatProperty dp = (FloatProperty) p;
+ if (dp.getExample() != null) {
+ return dp.getExample().toString();
+ }
+ return "null";
+ } else if (p instanceof IntegerProperty) {
+ IntegerProperty dp = (IntegerProperty) p;
+ if (dp.getExample() != null) {
+ return dp.getExample().toString();
+ }
+ return "null";
+ } else if (p instanceof LongProperty) {
+ LongProperty dp = (LongProperty) p;
+ if (dp.getExample() != null) {
+ return dp.getExample().toString();
+ }
+ return "null";
+ } else {
+ return "null";
+ }
+ }
+
+ /**
+ * Return the default value of the property
+ *
+ * @param p Swagger property object
+ * @return string presentation of the default value of the property
+ */
+ @SuppressWarnings("static-method")
+ public String toDefaultValue(Property p) {
+ if (p instanceof StringProperty) {
+ return "null";
+ } else if (p instanceof BooleanProperty) {
+ return "null";
+ } 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 "null";
+ } else if (p instanceof FloatProperty) {
+ FloatProperty dp = (FloatProperty) p;
+ if (dp.getDefault() != null) {
+ return dp.getDefault().toString();
+ }
+ return "null";
+ } else if (p instanceof IntegerProperty) {
+ IntegerProperty dp = (IntegerProperty) p;
+ if (dp.getDefault() != null) {
+ return dp.getDefault().toString();
+ }
+ return "null";
+ } else if (p instanceof LongProperty) {
+ LongProperty dp = (LongProperty) p;
+ if (dp.getDefault() != null) {
+ return dp.getDefault().toString();
+ }
+ return "null";
+ } else {
+ return "null";
+ }
+ }
+
+ /**
+ * 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
+ * @return string presentation of the default value of the property
+ */
+ @SuppressWarnings("static-method")
+ public String toDefaultValueWithParam(String name, Property p) {
+ return " = data." + name + ";";
+ }
+
+ /**
+ * returns the swagger type for the property
+ * @param p Swagger property object
+ * @return string presentation of the type
+ **/
+ @SuppressWarnings("static-method")
+ public String getSwaggerType(Property p) {
+ String datatype = null;
+ if (p instanceof StringProperty && "number".equals(p.getFormat())) {
+ datatype = "BigDecimal";
+ } else if (p instanceof StringProperty) {
+ datatype = "string";
+ } else if (p instanceof ByteArrayProperty) {
+ datatype = "ByteArray";
+ } else if (p instanceof BinaryProperty) {
+ datatype = "binary";
+ } else if (p instanceof BooleanProperty) {
+ datatype = "boolean";
+ } else if (p instanceof DateProperty) {
+ datatype = "date";
+ } else if (p instanceof DateTimeProperty) {
+ datatype = "DateTime";
+ } else if (p instanceof DoubleProperty) {
+ datatype = "double";
+ } else if (p instanceof FloatProperty) {
+ datatype = "float";
+ } else if (p instanceof IntegerProperty) {
+ datatype = "integer";
+ } else if (p instanceof LongProperty) {
+ datatype = "long";
+ } else if (p instanceof MapProperty) {
+ datatype = "map";
+ } else if (p instanceof DecimalProperty) {
+ datatype = "number";
+ } else if ( p instanceof UUIDProperty) {
+ datatype = "UUID";
+ } else if (p instanceof RefProperty) {
+ try {
+ RefProperty r = (RefProperty) p;
+ datatype = r.get$ref();
+ if (datatype.indexOf("#/definitions/") == 0) {
+ datatype = datatype.substring("#/definitions/".length());
+ }
+ } catch (Exception e) {
+ LOGGER.warn("Error obtaining the datatype from RefProperty:" + p + ". Datatype default to Object");
+ datatype = "Object";
+ LOGGER.error(e.getMessage(), e);
+ }
+ } else {
+ if (p != null) {
+ datatype = p.getType();
+ }
+ }
+ return datatype;
+ }
+
+ /**
+ * Return the snake-case of the string
+ *
+ * @param name string to be snake-cased
+ * @return snake-cased string
+ */
+ @SuppressWarnings("static-method")
+ public String snakeCase(String name) {
+ return (name.length() > 0) ? (Character.toLowerCase(name.charAt(0)) + name.substring(1)) : "";
+ }
+
+ /**
+ * Capitalize the string
+ *
+ * @param name string to be capitalized
+ * @return capitalized string
+ */
+ @SuppressWarnings("static-method")
+ public String initialCaps(String name) {
+ return StringUtils.capitalize(name);
+ }
+
+ /**
+ * Output the type declaration of a given name
+ *
+ * @param name name
+ * @return a string presentation of the type
+ */
+ @SuppressWarnings("static-method")
+ public String getTypeDeclaration(String name) {
+ return name;
+ }
+
+ /**
+ * Output the type declaration of the property
+ *
+ * @param p Swagger Property object
+ * @return a string presentation of the property type
+ */
+ public String getTypeDeclaration(Property p) {
+ String swaggerType = getSwaggerType(p);
+ if (typeMapping.containsKey(swaggerType)) {
+ return typeMapping.get(swaggerType);
+ }
+ return swaggerType;
+ }
+
+ /**
+ * 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"
+ */
+ public String toApiName(String name) {
+ if (name.length() == 0) {
+ return "DefaultApi";
+ }
+ return initialCaps(name) + "Api";
+ }
+
+ /**
+ * Output the proper model name (capitalized)
+ *
+ * @param name the name of the model
+ * @return capitalized model name
+ */
+ public String toModelName(String name) {
+ return initialCaps(name);
+ }
+
+ /**
+ * Convert Swagger Model object to Codegen Model object without providing all model definitions
+ *
+ * @param name the name of the model
+ * @param model Swagger Model object
+ * @return Codegen Model object
+ */
+ public CodegenModel fromModel(String name, Model model) {
+ return fromModel(name, model, null);
+ }
+
+ /**
+ * Convert Swagger Model object to Codegen Model object
+ *
+ * @param name the name of the model
+ * @param model Swagger Model object
+ * @param allDefinitions a map of all Swagger models from the spec
+ * @return Codegen Model object
+ */
+ public CodegenModel fromModel(String name, Model model, Map allDefinitions) {
+ CodegenModel m = CodegenModelFactory.newInstance(CodegenModelType.MODEL);
+ if (reservedWords.contains(name)) {
+ m.name = escapeReservedWord(name);
+ } else {
+ m.name = name;
+ }
+ m.description = escapeText(model.getDescription());
+ m.unescapedDescription = model.getDescription();
+ m.classname = toModelName(name);
+ m.classVarName = toVarName(name);
+ m.modelJson = Json.pretty(model);
+ m.externalDocs = model.getExternalDocs();
+ m.vendorExtensions = model.getVendorExtensions();
+
+
+ if (model instanceof ArrayModel) {
+ ArrayModel am = (ArrayModel) model;
+ ArrayProperty arrayProperty = new ArrayProperty(am.getItems());
+ m.hasEnums = false; // Otherwise there will be a NullPointerException in JavaClientCodegen.fromModel
+ addParentContainer(m, name, arrayProperty);
+ } else if (model instanceof RefModel) {
+ // TODO
+ } else if (model instanceof ComposedModel) {
+ final ComposedModel composed = (ComposedModel) model;
+ Map properties = new HashMap();
+ List required = new ArrayList();
+ // parent model
+ final RefModel parent = (RefModel) composed.getParent();
+ if (parent != null) {
+ final String parentRef = parent.getSimpleRef();
+ m.parentSchema = parentRef;
+ m.parent = toModelName(parent.getSimpleRef());
+ addImport(m, m.parent);
+ if (!supportsInheritance && allDefinitions != null) {
+ final Model parentModel = allDefinitions.get(m.parentSchema);
+ if (parentModel instanceof ModelImpl) {
+ final ModelImpl _parent = (ModelImpl) parentModel;
+ if (_parent.getProperties() != null) {
+ properties.putAll(_parent.getProperties());
+ }
+ if (_parent.getRequired() != null) {
+ required.addAll(_parent.getRequired());
+ }
+ }
+ }
+ }
+ // interfaces (intermediate models)
+ if (allDefinitions != null && composed.getInterfaces() != null) {
+ for (RefModel _interface : composed.getInterfaces()) {
+ final String interfaceRef = toModelName(_interface.getSimpleRef());
+ final Model interfaceModel = allDefinitions.get(interfaceRef);
+ if (interfaceModel instanceof ModelImpl) {
+ final ModelImpl _interfaceModel = (ModelImpl) interfaceModel;
+ if (_interfaceModel.getProperties() != null) {
+ properties.putAll(_interfaceModel.getProperties());
+ }
+ if (_interfaceModel.getRequired() != null) {
+ required.addAll(_interfaceModel.getRequired());
+ }
+ }
+ }
+ }
+ // child model (properties owned by the model itself)
+ Model child = composed.getChild();
+ if (child != null && child instanceof RefModel && allDefinitions != null) {
+ final String childRef = ((RefModel) child).getSimpleRef();
+ child = allDefinitions.get(childRef);
+ }
+ if (child != null && child instanceof ModelImpl) {
+ final ModelImpl _child = (ModelImpl) child;
+ if (_child.getProperties() != null) {
+ properties.putAll(_child.getProperties());
+ }
+ if (_child.getRequired() != null) {
+ required.addAll(_child.getRequired());
+ }
+ }
+ addVars(m, properties, required);
+ } else {
+ ModelImpl impl = (ModelImpl) model;
+ if(impl.getEnum() != null && impl.getEnum().size() > 0) {
+ m.isEnum = true;
+ m.allowableValues = impl.getEnum();
+ Property p = PropertyBuilder.build(impl.getType(), impl.getFormat(), null);
+ m.dataType = getSwaggerType(p);
+ }
+ if (impl.getAdditionalProperties() != null) {
+ MapProperty mapProperty = new MapProperty(impl.getAdditionalProperties());
+ addParentContainer(m, name, mapProperty);
+ }
+ addVars(m, impl.getProperties(), impl.getRequired());
+ }
+
+ if(m.vars != null) {
+ for(CodegenProperty prop : m.vars) {
+ postProcessModelProperty(m, prop);
+ }
+ }
+ return m;
+ }
+
+ /**
+ * Camelize the method name of the getter and setter
+ *
+ * @param name string to be camelized
+ * @return Camelized string
+ */
+ public String getterAndSetterCapitalize(String name) {
+ if (name == null || name.length() == 0) {
+ return name;
+ }
+
+ return camelize(toVarName(name));
+
+ }
+
+ /**
+ * Convert Swagger Property object to Codegen Property object
+ *
+ * @param name name of the property
+ * @param p Swagger property object
+ * @return Codegen Property object
+ */
+ public CodegenProperty fromProperty(String name, Property p) {
+ if (p == null) {
+ LOGGER.error("unexpected missing property for name " + name);
+ return null;
+ }
+
+ CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY);
+
+ property.name = toVarName(name);
+ property.baseName = name;
+ property.description = escapeText(p.getDescription());
+ property.unescapedDescription = p.getDescription();
+ property.getter = "get" + getterAndSetterCapitalize(name);
+ property.setter = "set" + getterAndSetterCapitalize(name);
+ property.example = toExampleValue(p);
+ property.defaultValue = toDefaultValue(p);
+ property.defaultValueWithParam = toDefaultValueWithParam(name, p);
+ property.jsonSchema = Json.pretty(p);
+ property.isReadOnly = p.getReadOnly();
+ property.vendorExtensions = p.getVendorExtensions();
+
+ String type = getSwaggerType(p);
+ if (p instanceof AbstractNumericProperty) {
+ AbstractNumericProperty np = (AbstractNumericProperty) p;
+ property.minimum = np.getMinimum();
+ property.maximum = np.getMaximum();
+ property.exclusiveMinimum = np.getExclusiveMinimum();
+ property.exclusiveMaximum = np.getExclusiveMaximum();
+
+ // legacy support
+ Map allowableValues = new HashMap();
+ if (np.getMinimum() != null) {
+ allowableValues.put("min", np.getMinimum());
+ }
+ if (np.getMaximum() != null) {
+ allowableValues.put("max", np.getMaximum());
+ }
+ if(allowableValues.size() > 0) {
+ property.allowableValues = allowableValues;
+ }
+ }
+
+ if (p instanceof StringProperty) {
+ StringProperty sp = (StringProperty) p;
+ property.maxLength = sp.getMaxLength();
+ property.minLength = sp.getMinLength();
+ property.pattern = sp.getPattern();
+ if (sp.getEnum() != null) {
+ List _enum = sp.getEnum();
+ property._enum = _enum;
+ property.isEnum = true;
+
+ // legacy support
+ Map allowableValues = new HashMap();
+ allowableValues.put("values", _enum);
+ property.allowableValues = allowableValues;
+ }
+ }
+
+ if (p instanceof IntegerProperty) {
+ IntegerProperty sp = (IntegerProperty) p;
+ if (sp.getEnum() != null) {
+ List _enum = sp.getEnum();
+ property._enum = new ArrayList