diff --git a/.travis.yml b/.travis.yml index 73c80821ba56..73dc7fdd26df 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ sudo: false language: java -script: mvn verify +script: mvn verify -Psamples jdk: - oraclejdk7 diff --git a/README.md b/README.md index 703adaa70890..b43351aa6197 100644 --- a/README.md +++ b/README.md @@ -29,11 +29,12 @@ Build a nodejs server stub: ## Compatibility The Swagger Specification has undergone 3 revisions since initial creation in 2010. The swagger-codegen project has the following compatibilies with the swagger specification: -Swagger Codegen Version | Release Date | Swagger Spec compatibility | Notes ------------------------ | ------------ | -------------------------- | ----- -2.1.0 | 2015-06-09 | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen) -2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17) -1.0.4 | 2012-04-12 | 1.0, 1.1 | [tag v1.0.4](https://github.com/swagger-api/swagger-codegen/tree/swagger-codegen_2.9.1-1.1) +Swagger Codegen Version | Release Date | Swagger Spec compatibility | Notes +-------------------------- | ------------ | -------------------------- | ----- +2.1.4-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen) +2.1.3 (**current stable**) | 2015-08-24 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.3](https://github.com/swagger-api/swagger-codegen/tree/v2.1.3) +2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17) +1.0.4 | 2012-04-12 | 1.0, 1.1 | [tag v1.0.4](https://github.com/swagger-api/swagger-codegen/tree/swagger-codegen_2.9.1-1.1) ### Prerequisites @@ -128,7 +129,7 @@ OPTIONS -s , --skip-overwrite specifies if the existing files should be overwritten during the generation - ``` +``` You can then compile and run the client, as well as unit tests against it: @@ -184,12 +185,16 @@ There are different aspects of customizing the code generator beyond just creati ``` $ ls -1 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ +AbstractTypeScriptClientCodegen.java AkkaScalaClientCodegen.java AndroidClientCodegen.java AsyncScalaClientCodegen.java CSharpClientCodegen.java +CodeGenStatus.java +CsharpDotNet2ClientCodegen.java FlashClientCodegen.java JavaClientCodegen.java +JavaInflectorServerCodegen.java JaxRSServerCodegen.java NodeJSServerCodegen.java ObjcClientCodegen.java @@ -202,6 +207,8 @@ RetrofitClientCodegen.java RubyClientCodegen.java ScalaClientCodegen.java ScalatraServerCodegen.java +SilexServerCodegen.java +SinatraServerCodegen.java SpringMVCServerCodegen.java StaticDocCodegen.java StaticHtmlGenerator.java @@ -209,6 +216,8 @@ SwaggerGenerator.java SwaggerYamlGenerator.java SwiftCodegen.java TizenClientCodegen.java +TypeScriptAngularClientCodegen.java +TypeScriptNodeClientCodegen.java ``` Each of these files creates reasonable defaults so you can get running quickly. But if you want to configure package names, prefixes, model folders, etc. you can use a json config file to pass the values. @@ -250,6 +259,11 @@ CONFIG OPTIONS sourceFolder source folder for generated code + + library + library template (sub-template) to use: + - HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2 + jersey2 - HTTP client: Jersey client 2.6 ``` Your config file for java can look like diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index 7a47662a7c7c..23c2935ed2ae 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -24,6 +24,7 @@ cd $APP_DIR ./bin/dynamic-html.sh ./bin/html-petstore.sh ./bin/java-petstore.sh +./bin/java-petstore-jersey2.sh ./bin/jaxrs-petstore-server.sh ./bin/nodejs-petstore-server.sh ./bin/objc-petstore.sh diff --git a/bin/java-petstore-jersey2.json b/bin/java-petstore-jersey2.json new file mode 100644 index 000000000000..af343e1d6b88 --- /dev/null +++ b/bin/java-petstore-jersey2.json @@ -0,0 +1,4 @@ +{ + "library": "jersey2", + "artifactId": "swagger-petstore-jersey2" +} \ No newline at end of file diff --git a/bin/java-petstore-jersey2.sh b/bin/java-petstore-jersey2.sh new file mode 100755 index 000000000000..cb51c1e1a8d4 --- /dev/null +++ b/bin/java-petstore-jersey2.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -c bin/java-petstore-jersey2.json -o samples/client/petstore/java/jersey2" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore.sh b/bin/java-petstore.sh index 3beff2f07cec..f842d9ca3b0e 100755 --- a/bin/java-petstore.sh +++ b/bin/java-petstore.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -o samples/client/petstore/java" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -o samples/client/petstore/java/default" java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen-cli/pom.xml b/modules/swagger-codegen-cli/pom.xml index 6a6d05270df4..5193e39531a6 100644 --- a/modules/swagger-codegen-cli/pom.xml +++ b/modules/swagger-codegen-cli/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.1.3-SNAPSHOT + 2.1.4-SNAPSHOT ../.. 4.0.0 @@ -70,33 +70,34 @@ swagger-codegen ${project.version} - io.airlift airline 0.7 - com.googlecode.lambdaj lambdaj 2.3.3 - org.slf4j slf4j-simple ${slf4j-version} - - junit - junit - ${junit-version} + org.testng + testng + ${testng-version} + test + + + org.jmockit + jmockit + ${jmockit-version} test - \ No newline at end of file diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java index 6b34a4bf56df..f7a128613b94 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java @@ -4,10 +4,7 @@ import io.airlift.airline.Command; import io.airlift.airline.Option; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; - -import java.util.ServiceLoader; - -import static java.util.ServiceLoader.load; +import io.swagger.codegen.CodegenConfigLoader; @Command(name = "config-help", description = "Config help for chosen lang") public class ConfigHelp implements Runnable { @@ -16,36 +13,14 @@ public class ConfigHelp implements Runnable { description = "language to get config help for") private String lang; - /** - * 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 - */ - private static CodegenConfig forName(String name) { - ServiceLoader loader = load(CodegenConfig.class); - for (CodegenConfig config : loader) { - if (config.getName().equals(name)) { - return config; - } - } - - // 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), e); - } - } - @Override public void run() { System.out.println(); - CodegenConfig config = forName(lang); + 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.getDescription()); + System.out.println("\t " + langCliOption.getDescription().replaceAll("\n", "\n\t ")); System.out.println(); } } diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java index 035fa1a21d35..d6790a6aa8ff 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java @@ -8,16 +8,21 @@ import io.swagger.codegen.CliOption; import io.swagger.codegen.ClientOptInput; import io.swagger.codegen.ClientOpts; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConfigLoader; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.DefaultGenerator; +import io.swagger.codegen.cmd.utils.OptionUtils; import io.swagger.models.Swagger; import io.swagger.parser.SwaggerParser; +import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; -import java.util.ServiceLoader; +import java.util.List; +import java.util.Map; +import java.util.Set; -import static java.util.ServiceLoader.load; import static org.apache.commons.lang3.StringUtils.isNotEmpty; /** @@ -31,8 +36,6 @@ public class Generate implements Runnable { public static final Logger LOG = LoggerFactory.getLogger(Generate.class); - public static final String TEMPLATE_DIR_PARAM = "templateDir"; - @Option(name = {"-v", "--verbose"}, description = "verbose mode") private boolean verbose; @@ -70,27 +73,42 @@ public class Generate implements Runnable { "overwritten during the generation.") private boolean skipOverwrite; - /** - * 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 - */ - private static CodegenConfig forName(String name) { - ServiceLoader loader = load(CodegenConfig.class); - for (CodegenConfig config : loader) { - if (config.getName().equals(name)) { - return config; - } - } + @Option(name = {"--api-package"}, title = "api package", description = CodegenConstants.API_PACKAGE_DESC) + private String apiPackage; - // 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), e); - } - } + @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; @Override public void run() { @@ -98,48 +116,92 @@ public class Generate implements Runnable { setSystemProperties(); - ClientOptInput input = new ClientOptInput(); + CodegenConfig config = CodegenConfigLoader.forName(lang); - if (isNotEmpty(auth)) { - input.setAuth(auth); - } - - CodegenConfig config = forName(lang); config.setOutputDir(new File(output).getAbsolutePath()); + config.setSkipOverwrite(skipOverwrite); - if (null != templateDir) { - config.additionalProperties().put(TEMPLATE_DIR_PARAM, new File(templateDir).getAbsolutePath()); + putKeyValuePairsInMap(config.instantiationTypes(), instantiationTypes); + putKeyValuePairsInMap(config.typeMapping(), typeMappings); + putKeyValuePairsInMap(config.additionalProperties(), additionalProperties); + putKeyValuePairsInMap(config.importMapping(), importMappings); + + addValuesToSet(config.languageSpecificPrimitives(), languageSpecificPrimitives); + + checkAndSetAdditionalProperty(config, apiPackage, CodegenConstants.API_PACKAGE); + checkAndSetAdditionalProperty(config, modelPackage, CodegenConstants.MODEL_PACKAGE); + + if(isNotEmpty(templateDir)) { + config.additionalProperties().put(CodegenConstants.TEMPLATE_DIR, new File(templateDir).getAbsolutePath()); } + checkAndSetAdditionalProperty(config, invokerPackage, CodegenConstants.INVOKER_PACKAGE); + checkAndSetAdditionalProperty(config, groupId, CodegenConstants.GROUP_ID); + checkAndSetAdditionalProperty(config, artifactId, CodegenConstants.ARTIFACT_ID); + checkAndSetAdditionalProperty(config, artifactVersion, CodegenConstants.ARTIFACT_VERSION); + if (null != configFile) { Config genConfig = ConfigParser.read(configFile); if (null != genConfig) { for (CliOption langCliOption : config.cliOptions()) { - if (genConfig.hasOption(langCliOption.getOpt())) { - config.additionalProperties().put(langCliOption.getOpt(), genConfig.getOption(langCliOption.getOpt())); + String opt = langCliOption.getOpt(); + if (genConfig.hasOption(opt)) { + config.additionalProperties().put(opt, genConfig.getOption(opt)); + // the "library" config option is for library template (sub-template) + if ("library".equals(opt)) { + config.setLibrary(genConfig.getOption(opt)); + } } } } } - config.setSkipOverwrite(skipOverwrite); - input.setConfig(config); + ClientOptInput input = new ClientOptInput().config(config); + + if (isNotEmpty(auth)) { + input.setAuth(auth); + } Swagger swagger = new SwaggerParser().read(spec, input.getAuthorizationValues(), true); new DefaultGenerator().opts(input.opts(new ClientOpts()).swagger(swagger)).generate(); } - private void setSystemProperties() { - if (systemProperties != null && systemProperties.length() > 0) { - for (String property : systemProperties.split(",")) { - int ix = property.indexOf('='); - if (ix > 0 && ix < property.length() - 1) { - System.setProperty(property.substring(0, ix), property.substring(ix + 1)); - } - } + private void addValuesToSet(Set set, String csvProperty) { + final List values = OptionUtils.splitCommaSeparatedList(csvProperty); + + for (String value : values) { + set.add(value); } } + private void checkAndSetAdditionalProperty(CodegenConfig config, String property, String propertyKey) { + checkAndSetAdditionalProperty(config, property, property, propertyKey); + } + + private void checkAndSetAdditionalProperty(CodegenConfig config, String property, String valueToSet, String propertyKey) { + if(isNotEmpty(property)) { + config.additionalProperties().put(propertyKey, valueToSet); + } + } + + private void setSystemProperties() { + + final List> systemPropertyPairs = OptionUtils.parseCommaSeparatedTuples(systemProperties); + + for (Pair pair : systemPropertyPairs) { + System.setProperty(pair.getLeft(), pair.getRight()); + } + } + + private void putKeyValuePairsInMap(Map map, String commaSeparatedKVPairs) { + final List> pairs = OptionUtils.parseCommaSeparatedTuples(commaSeparatedKVPairs); + + for (Pair pair : pairs) { + map.put(pair.getLeft(), pair.getRight()); + } + } + + /** * If true parameter, adds system properties which enables debug mode in generator * diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/utils/OptionUtils.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/utils/OptionUtils.java new file mode 100644 index 000000000000..34d567274125 --- /dev/null +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/utils/OptionUtils.java @@ -0,0 +1,43 @@ +package io.swagger.codegen.cmd.utils; + +import org.apache.commons.lang3.tuple.Pair; + +import java.util.ArrayList; +import java.util.List; + +import static org.apache.commons.lang3.StringUtils.isNotEmpty; + +public class OptionUtils { + + public static List> parseCommaSeparatedTuples(String input) { + + List> results = new ArrayList>(); + + final List tuples = splitCommaSeparatedList(input); + + for (String tuple : tuples) { + int ix = tuple.indexOf('='); + if (ix > 0 && ix < tuple.length() - 1) { + final Pair pair = Pair.of(tuple.substring(0, ix), tuple.substring(ix + 1)); + results.add(pair); + } + } + + return results; + } + + public static List splitCommaSeparatedList(String input) { + + List results = new ArrayList(); + + if(input != null && !input.isEmpty()) { + for (String value : input.split(",")) { + if(isNotEmpty(value)) + results.add(value); + } + } + + return results; + } + +} 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 000000000000..94a397df700d --- /dev/null +++ b/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/GenerateTest.java @@ -0,0 +1,352 @@ +package io.swagger.codegen.cmd; + +import config.Config; +import config.ConfigParser; +import io.swagger.codegen.ClientOptInput; +import io.swagger.codegen.ClientOpts; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.DefaultGenerator; +import io.swagger.codegen.SwaggerCodegen; +import io.swagger.codegen.CodegenConfigLoader; +import io.swagger.codegen.languages.JavaClientCodegen; +import io.swagger.models.Swagger; +import io.swagger.models.auth.AuthorizationValue; +import io.swagger.parser.SwaggerParser; +import mockit.Expectations; +import mockit.FullVerifications; +import mockit.Injectable; +import mockit.Mocked; +import mockit.StrictExpectations; +import org.apache.commons.lang3.ArrayUtils; +import org.testng.annotations.Test; + +import java.io.File; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; + +public class GenerateTest { + + @Mocked + SwaggerParser parser; + + @Injectable + Swagger swagger; + + @Mocked + DefaultGenerator defaultGenerator; + + @Mocked + CodegenConfigLoader codegenConfigLoader; + + @Mocked + ClientOptInput clientOptInput; + + @Injectable + List authorizationValues; + + @Test + public void testVerbose_ShortArg() throws Exception { + doVerboseTest("-v"); + } + + @Test + public void testVerbose_LongArg() throws Exception { + doVerboseTest("--verbose"); + } + + @Test + public void testRequiredArgs_ShortArgs() throws Exception { + doRequiredArgsTest("-l", "-o", "-i"); + } + + @Test + public void testRequiredArgs_LongArgs() throws Exception { + doRequiredArgsTest("--lang", "--output", "--input-spec"); + } + + @Test + public void testTemplateDir() throws Exception { + final String absolutePath = new File("src").getAbsolutePath(); + + doSingleAdditionalPropertyTest("--template-dir", CodegenConstants.TEMPLATE_DIR, "src", absolutePath); + doSingleAdditionalPropertyTest("--template-dir", CodegenConstants.TEMPLATE_DIR, absolutePath, absolutePath); + doSingleAdditionalPropertyTest("-t", CodegenConstants.TEMPLATE_DIR, "src", absolutePath); + doSingleAdditionalPropertyTest("-t", CodegenConstants.TEMPLATE_DIR, absolutePath, absolutePath); + } + + @Test + public void testAuth() throws Exception { + + final String auth = "hello:world"; + + new StrictExpectations() {{ + clientOptInput.setAuth(auth); + times = 1; + }}; + + setupAndRunGenericTest("-a", auth); + + new StrictExpectations() {{ + clientOptInput.setAuth(auth); + times = 1; + }}; + + setupAndRunGenericTest("--auth", auth); + } + + @Test + public void testSystemProperties() throws Exception { + + new StrictExpectations(System.class) {{ + System.setProperty("hello", "world"); + times = 1; + System.setProperty("foo", "bar"); + times = 1; + }}; + + setupAndRunGenericTest("-D", "hello=world,foo=bar"); + } + + @Test + public void testConfig(@Mocked final ConfigParser parser) throws Exception { + + final String configFilePath = "config.json"; + final String invokerPackage = "com.foo.bar.invoker"; + final String groupId = "com.foo.bar"; + Map configMap = new HashMap(); + configMap.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + configMap.put(CodegenConstants.GROUP_ID, groupId); + final Config config = new Config(configMap); + + final String[] configArgs = {"-c", "--config"}; + + for (String configArg : configArgs) { + new StrictExpectations() {{ + parser.read(configFilePath); + times = 1; + result = config; + + }}; + + final CodegenConfig codegenConfig = setupAndRunGenericTest(configArg, configFilePath); + + assertValueInMap(codegenConfig.additionalProperties(), CodegenConstants.INVOKER_PACKAGE, invokerPackage); + assertValueInMap(codegenConfig.additionalProperties(), CodegenConstants.GROUP_ID, groupId); + } + } + + @Test + public void testSkipOverwrite() throws Exception { + + CodegenConfig codegenConfig1 = setupAndRunGenericTest(); + assertFalse(codegenConfig1.isSkipOverwrite()); + + CodegenConfig codegenConfig2 = setupAndRunGenericTest("-s"); + assertTrue(codegenConfig2.isSkipOverwrite()); + + CodegenConfig codegenConfig3 = setupAndRunGenericTest("--skip-overwrite"); + assertTrue(codegenConfig3.isSkipOverwrite()); + } + + @Test + public void testApiPackage() throws Exception { + doSingleAdditionalPropertyTest("--api-package", CodegenConstants.API_PACKAGE, "io.foo.bar.api"); + } + + @Test + public void testModelPackage() throws Exception { + doSingleAdditionalPropertyTest("--model-package", CodegenConstants.MODEL_PACKAGE, "io.foo.bar.models"); + } + + @Test + public void testInstantiationTypes() throws Exception { + + final CodegenConfig codegenConfig = setupAndRunGenericTest("--instantiation-types", "foo=bar,hello=world"); + + assertValueInMap(codegenConfig.instantiationTypes(), "foo", "bar"); + assertValueInMap(codegenConfig.instantiationTypes(), "hello", "world"); + } + + @Test + public void testTypeMappings() throws Exception { + final CodegenConfig codegenConfig = setupAndRunGenericTest("--type-mappings", "foo=bar,hello=world"); + + assertValueInMap(codegenConfig.typeMapping(), "foo", "bar"); + assertValueInMap(codegenConfig.typeMapping(), "hello", "world"); + } + + @Test + public void testAdditionalProperties() throws Exception { + final CodegenConfig codegenConfig = setupAndRunGenericTest("--additional-properties", "foo=bar,hello=world"); + + assertValueInMap(codegenConfig.additionalProperties(), "foo", "bar"); + assertValueInMap(codegenConfig.additionalProperties(), "hello", "world"); + } + + @Test + public void testLanguageSpecificPrimitives() throws Exception { + final CodegenConfig codegenConfig = setupAndRunGenericTest("--language-specific-primitives", "foo,bar,hello,world"); + + final Set languageSpecificPrimitives = codegenConfig.languageSpecificPrimitives(); + + assertTrue(languageSpecificPrimitives.contains("foo")); + assertTrue(languageSpecificPrimitives.contains("bar")); + assertTrue(languageSpecificPrimitives.contains("hello")); + assertTrue(languageSpecificPrimitives.contains("world")); + } + + @Test + public void testImportMappings() throws Exception { + final CodegenConfig codegenConfig = setupAndRunGenericTest("--import-mappings", "foo=bar,hello=world"); + + assertValueInMap(codegenConfig.importMapping(), "foo", "bar"); + assertValueInMap(codegenConfig.importMapping(), "hello", "world"); + } + + @Test + public void testInvokerPackage() throws Exception { + doSingleAdditionalPropertyTest("--invoker-package", CodegenConstants.INVOKER_PACKAGE, "io.foo.bar.invoker"); + } + + @Test + public void testGroupId() throws Exception { + doSingleAdditionalPropertyTest("--group-id", CodegenConstants.GROUP_ID, "io.foo.bar"); + } + + @Test + public void testArtifactId() throws Exception { + doSingleAdditionalPropertyTest("--artifact-id", CodegenConstants.ARTIFACT_ID, "awesome-api"); + } + + @Test + public void testArtifactVersion() throws Exception { + doSingleAdditionalPropertyTest("--artifact-version", CodegenConstants.ARTIFACT_VERSION, "1.2.3"); + } + + private void doVerboseTest(String verboseFlag) { + new StrictExpectations(System.class) {{ + System.setProperty("debugSwagger", ""); + times = 1; + System.setProperty("debugModels", ""); + times = 1; + System.setProperty("debugOperations", ""); + times = 1; + System.setProperty("debugSupportingFiles", ""); + times = 1; + }}; + + setupAndRunGenericTest(verboseFlag); + } + + private void doRequiredArgsTest(String langFlag, String outputDirFlag, String inputSpecFlag) { + final String spec = "swagger.yaml"; + final String lang = "java"; + final String outputDir = "src/main/java"; + + final String[] args = {"generate", langFlag, lang, outputDirFlag, outputDir, inputSpecFlag, spec}; + + final CodegenConfig config = new JavaClientCodegen(); + + setupStandardExpectations(spec, lang, config); + + SwaggerCodegen.main(args); + + new FullVerifications() {{ + }}; + + assertEquals(config.getOutputDir(), new File(outputDir).getAbsolutePath()); + } + + private void doSingleAdditionalPropertyTest(String cliArg, String additionalPropertyKey, String expectedValue) { + doSingleAdditionalPropertyTest(cliArg, additionalPropertyKey, expectedValue, expectedValue); + } + + private void doSingleAdditionalPropertyTest(String cliArg, String additionalPropertyKey, String cliValue, String additionalPropertyValue) { + + final CodegenConfig config = setupAndRunGenericTest(cliArg, cliValue); + + assertValueInMap(config.additionalProperties(), additionalPropertyKey, additionalPropertyValue); + } + + private CodegenConfig setupAndRunGenericTest(String... additionalParameters) { + + final String spec = "swagger.yaml"; + final String lang = "java"; + + final String[] commonArgs = {"generate", "-l", lang, "-o", "path/to/some/directory", "-i", spec}; + + String[] argsToUse = ArrayUtils.addAll(commonArgs, additionalParameters); + + final CodegenConfig config = new JavaClientCodegen(); + + setupStandardExpectations(spec, lang, config); + + SwaggerCodegen.main(argsToUse); + + new FullVerifications() {{ + }}; + + return config; + } + + private void assertValueInMap(Map map, String propertyKey, String expectedPropertyValue) { + assertTrue(map.containsKey(propertyKey)); + assertEquals(map.get(propertyKey), expectedPropertyValue); + } + + private void setupStandardExpectations(final String spec, final String languageName, final CodegenConfig config) { + + new Expectations() {{ + CodegenConfigLoader.forName(languageName); + times = 1; + result = config; + + new ClientOptInput(); + times = 1; + result = clientOptInput; + + clientOptInput.config(config); + times = 1; + result = clientOptInput; + + new SwaggerParser(); + times = 1; + result = parser; + + clientOptInput.getAuthorizationValues(); + times = 1; + result = authorizationValues; + + parser.read(spec, authorizationValues, true); + times = 1; + result = swagger; + + new DefaultGenerator(); + times = 1; + result = defaultGenerator; + + clientOptInput.opts((ClientOpts) any); + times = 1; + result = clientOptInput; + + clientOptInput.swagger(swagger); + times = 1; + result = clientOptInput; + + defaultGenerator.opts(clientOptInput); + times = 1; + result = defaultGenerator; + + defaultGenerator.generate(); + times = 1; + }}; + } + +} 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 000000000000..a7dc4d7f1cd4 --- /dev/null +++ b/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/utils/OptionUtilsTest.java @@ -0,0 +1,52 @@ +package io.swagger.codegen.cmd.utils; + +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; + +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 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 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 index a7eaf852a223..372b2c90adf6 100644 --- a/modules/swagger-codegen-maven-plugin/README.md +++ b/modules/swagger-codegen-maven-plugin/README.md @@ -20,6 +20,9 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase) src/main/resources/api.yaml java + + src/gen/java/main + @@ -32,10 +35,21 @@ Followed by: mvn clean compile ``` -### Configuration parameters +### General Configuration parameters - `inputSpec` - swagger 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) + +### Java-specific parameters (under configOptions) + +- `sourceFolder` - the folder to use for generated sources under the output folder +- `groupId` - groupId in generated pom.xml +- `artifactId` - artifactId in generated pom.xml +- `artifactVersion` - artifact version in generated pom.xml diff --git a/modules/swagger-codegen-maven-plugin/pom.xml b/modules/swagger-codegen-maven-plugin/pom.xml index 7ad4496872ce..4d7107dba7e1 100644 --- a/modules/swagger-codegen-maven-plugin/pom.xml +++ b/modules/swagger-codegen-maven-plugin/pom.xml @@ -6,7 +6,7 @@ io.swagger swagger-codegen-project - 2.1.3-SNAPSHOT + 2.1.4-SNAPSHOT ../.. swagger-codegen-maven-plugin @@ -17,7 +17,7 @@ UTF-8 - + org.apache.maven maven-core 3.2.5 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 index aa137cbf6c39..f3678e783e09 100644 --- 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 @@ -7,10 +7,10 @@ package io.swagger.codegen.plugin; */ 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"; private AdditionalParams() { - } - - } diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java index 812be6981d4f..7500fcfeb398 100644 --- a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java +++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java @@ -20,6 +20,7 @@ import io.swagger.codegen.CliOption; import io.swagger.codegen.ClientOptInput; import io.swagger.codegen.ClientOpts; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConfigLoader; import io.swagger.codegen.DefaultGenerator; import io.swagger.models.Swagger; import io.swagger.parser.SwaggerParser; @@ -35,8 +36,12 @@ import config.Config; import config.ConfigParser; import java.io.File; +import java.util.Map; import java.util.ServiceLoader; +import static io.swagger.codegen.plugin.AdditionalParams.API_PACKAGE_PARAM; +import static io.swagger.codegen.plugin.AdditionalParams.INVOKER_PACKAGE_PARAM; +import static io.swagger.codegen.plugin.AdditionalParams.MODEL_PACKAGE_PARAM; import static io.swagger.codegen.plugin.AdditionalParams.TEMPLATE_DIR_PARAM; /** @@ -44,7 +49,6 @@ import static io.swagger.codegen.plugin.AdditionalParams.TEMPLATE_DIR_PARAM; */ @Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES) public class CodeGenMojo extends AbstractMojo { - /** * Location of the output directory. */ @@ -65,6 +69,24 @@ public class CodeGenMojo extends AbstractMojo { @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. */ @@ -72,11 +94,16 @@ public class CodeGenMojo extends AbstractMojo { private String language; /** - * Path to json configuration file. + * Path to separate json configuration file. */ @Parameter(name = "configurationFile", required = false) private String configurationFile; + /** + * 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 @@ -95,13 +122,31 @@ public class CodeGenMojo extends AbstractMojo { public void execute() throws MojoExecutionException { Swagger swagger = new SwaggerParser().read(inputSpec); - CodegenConfig config = forName(language); + CodegenConfig config = CodegenConfigLoader.forName(language); config.setOutputDir(output.getAbsolutePath()); 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 (null != configurationFile) { Config genConfig = ConfigParser.read(configurationFile); if (null != genConfig) { @@ -123,20 +168,4 @@ public class CodeGenMojo extends AbstractMojo { project.addCompileSourceRoot(output.toString()); } } - - private CodegenConfig forName(String name) { - ServiceLoader loader = ServiceLoader.load(CodegenConfig.class); - for (CodegenConfig config : loader) { - if (config.getName().equals(name)) { - return config; - } - } - - // 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), e); - } - } } diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index 762aa3a72f29..b6caa0a684ae 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.1.3-SNAPSHOT + 2.1.4-SNAPSHOT ../.. 4.0.0 @@ -334,6 +334,18 @@ ${scala-version} test + + org.testng + testng + ${testng-version} + test + + + org.reflections + reflections + ${reflections-version} + test + diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java index ac3771536252..2c90f4255ece 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java @@ -60,6 +60,27 @@ public abstract class AbstractGenerator { 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 (templateExists(libTemplateFile)) { + return libTemplateFile; + } + } + return config.templateDir() + File.separator + templateFile; + } + + public boolean templateExists(String name) { + return this.getClass().getClassLoader().getResource(getCPResourcePath(name)) != null; + } + public String getCPResourcePath(String name) { if (!"/".equals(File.separator)) { return name.replaceAll(Pattern.quote(File.separator), "/"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java index da026c7f0400..56c4c66835a2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java @@ -10,7 +10,7 @@ import java.util.ArrayList; import java.util.List; public class ClientOptInput { - protected CodegenConfig config; + private CodegenConfig config; private ClientOpts opts; private Swagger swagger; private List auths; @@ -25,6 +25,11 @@ public class ClientOptInput { return this; } + public ClientOptInput config(CodegenConfig codegenConfig) { + this.setConfig(codegenConfig); + return this; + } + public String getAuth() { if (auths != null) { StringBuilder b = new StringBuilder(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java index c99e04e54949..d4c0707f1a73 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java @@ -85,7 +85,7 @@ public class Codegen extends DefaultGenerator { swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true); } if (cmd.hasOption("t")) { - clientOpts.getProperties().put("templateDir", String.valueOf(cmd.getOptionValue("t"))); + clientOpts.getProperties().put(CodegenConstants.TEMPLATE_DIR, String.valueOf(cmd.getOptionValue("t"))); } } catch (Exception e) { usage(options); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java index 4ef8bb23e664..1b0e349dacaf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -83,6 +83,8 @@ public interface CodegenConfig { Map modelTemplateFiles(); + Set languageSpecificPrimitives(); + void processSwagger(Swagger swagger); String toApiFilename(String name); @@ -108,4 +110,13 @@ public interface CodegenConfig { 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 000000000000..45a57e7bb3a3 --- /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 000000000000..c4bdad9c6eab --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -0,0 +1,36 @@ +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 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"; +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index b795f8e38e25..4f30cc01ccba 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -30,6 +30,23 @@ public class CodegenOperation { public List> examples; public ExternalDocs externalDocs; + private boolean nonempty(List params) + { + return params != null && params.size() > 0; + } + public boolean getHasBodyParam() { + return nonempty(bodyParams); + } + public boolean getHasQueryParams() { + return nonempty(bodyParams); + } + public boolean getHasHeaderParams() { + return nonempty(bodyParams); + } + public boolean getHasPathParams() { + return nonempty(bodyParams); + } + // legacy support public String nickname; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java index c5aeaab124cc..4447915de4da 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java @@ -7,7 +7,7 @@ import java.util.List; public class CodegenParameter { public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam, - isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer, secondaryParam; + isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer, secondaryParam, isBinary; public String baseName, paramName, dataType, collectionFormat, description, baseType, defaultValue; public String jsonSchema; public boolean isEnum; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java index 7872da2c707f..076d6cbfbdbe 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java @@ -34,4 +34,107 @@ public class CodegenProperty { public boolean isEnum; public List _enum; public Map allowableValues; + public CodegenProperty items; + + @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; + } + 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 index 6d90152f5149..1929bcf52dc3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java @@ -15,6 +15,7 @@ public class CodegenResponse { public Boolean primitiveType; public Boolean isMapContainer; public Boolean isListContainer; + public Boolean isBinary; public Object schema; public String jsonSchema; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index bf58bd1cc361..687e37a35221 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -27,6 +27,7 @@ import io.swagger.models.parameters.SerializableParameter; import io.swagger.models.properties.AbstractNumericProperty; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.BooleanProperty; +import io.swagger.models.properties.ByteArrayProperty; import io.swagger.models.properties.DateProperty; import io.swagger.models.properties.DateTimeProperty; import io.swagger.models.properties.DecimalProperty; @@ -55,6 +56,7 @@ 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; @@ -81,22 +83,24 @@ public class DefaultCodegen { protected List cliOptions = new ArrayList(); protected boolean skipOverwrite; protected boolean supportsInheritance = false; + protected Map supportedLibraries = new LinkedHashMap(); + protected String library = null; public List cliOptions() { return cliOptions; } public void processOpts() { - if (additionalProperties.containsKey("templateDir")) { - this.setTemplateDir((String) additionalProperties.get("templateDir")); + if (additionalProperties.containsKey(CodegenConstants.TEMPLATE_DIR)) { + this.setTemplateDir((String) additionalProperties.get(CodegenConstants.TEMPLATE_DIR)); } - if (additionalProperties.containsKey("modelPackage")) { - this.setModelPackage((String) additionalProperties.get("modelPackage")); + if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { + this.setModelPackage((String) additionalProperties.get(CodegenConstants.MODEL_PACKAGE)); } - if (additionalProperties.containsKey("apiPackage")) { - this.setApiPackage((String) additionalProperties.get("apiPackage")); + if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { + this.setApiPackage((String) additionalProperties.get(CodegenConstants.API_PACKAGE)); } } @@ -122,6 +126,7 @@ public class DefaultCodegen { // override with any special text escaping logic public String escapeText(String input) { if (input != null) { + input = input.trim(); String output = input.replaceAll("\n", "\\\\n"); output = output.replace("\"", "\\\""); return output; @@ -308,6 +313,8 @@ public class DefaultCodegen { typeMapping.put("double", "Double"); typeMapping.put("object", "Object"); typeMapping.put("integer", "Integer"); + typeMapping.put("ByteArray", "byte[]"); + instantiationTypes = new HashMap(); @@ -330,8 +337,8 @@ public class DefaultCodegen { importMapping.put("LocalDate", "org.joda.time.*"); importMapping.put("LocalTime", "org.joda.time.*"); - cliOptions.add(new CliOption("modelPackage", "package for generated models")); - cliOptions.add(new CliOption("apiPackage", "package for generated api classes")); + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); } @@ -388,7 +395,13 @@ public class DefaultCodegen { public String toInstantiationType(Property p) { if (p instanceof MapProperty) { MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); + 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; @@ -444,6 +457,8 @@ public class DefaultCodegen { String datatype = null; if (p instanceof StringProperty) { datatype = "string"; + } else if (p instanceof ByteArrayProperty) { + datatype = "ByteArray"; } else if (p instanceof BooleanProperty) { datatype = "boolean"; } else if (p instanceof DateProperty) { @@ -526,6 +541,7 @@ public class DefaultCodegen { if (model instanceof ArrayModel) { ArrayModel am = (ArrayModel) model; ArrayProperty arrayProperty = new ArrayProperty(am.getItems()); + m.hasEnums = false; // Otherwise there will be a NullPointerException in JavaClientCodegen.fromModel addParentContainer(m, name, arrayProperty); } else if (model instanceof RefModel) { // TODO @@ -636,7 +652,9 @@ public class DefaultCodegen { if (np.getMaximum() != null) { allowableValues.put("max", np.getMaximum()); } - property.allowableValues = allowableValues; + if(allowableValues.size() > 0) { + property.allowableValues = allowableValues; + } } if (p instanceof StringProperty) { @@ -667,22 +685,28 @@ public class DefaultCodegen { property.baseType = getSwaggerType(p); - if (p instanceof ArrayProperty) { - property.isContainer = true; - property.containerType = "array"; - ArrayProperty ap = (ArrayProperty) p; - CodegenProperty cp = fromProperty("inner", ap.getItems()); - if (cp == null) { - LOGGER.warn("skipping invalid property " + Json.pretty(p)); - } else { - property.baseType = getSwaggerType(p); - if (!languageSpecificPrimitives.contains(cp.baseType)) { - property.complexType = cp.baseType; - } else { - property.isPrimitiveType = true; - } - } - } else if (p instanceof MapProperty) { + if (p instanceof ArrayProperty) { + property.isContainer = true; + property.containerType = "array"; + ArrayProperty ap = (ArrayProperty) p; + CodegenProperty cp = fromProperty(property.name, ap.getItems()); + if (cp == null) { + LOGGER.warn("skipping invalid property " + Json.pretty(p)); + } else { + property.baseType = getSwaggerType(p); + if (!languageSpecificPrimitives.contains(cp.baseType)) { + property.complexType = cp.baseType; + } else { + property.isPrimitiveType = true; + } + property.items = cp; + if (property.items.isEnum) { + property.datatypeWithEnum = property.datatypeWithEnum.replace(property.items.baseType, + property.items.datatypeWithEnum); + property.defaultValue = property.defaultValue.replace(property.items.baseType, property.items.datatypeWithEnum); + } + } + } else if (p instanceof MapProperty) { property.isContainer = true; property.containerType = "map"; MapProperty ap = (MapProperty) p; @@ -752,7 +776,7 @@ public class DefaultCodegen { } } operationId = builder.toString(); - LOGGER.warn("generated operationId " + operationId); + LOGGER.info("generated operationId " + operationId + "\tfor Path: " + httpMethod + " " + path); } operationId = removeNonNameElementToCamelCase(operationId); op.path = path; @@ -963,6 +987,7 @@ public class DefaultCodegen { } } r.dataType = cm.datatype; + r.isBinary = cm.datatype.equals("byte[]"); if (cm.isContainer != null) { r.simpleType = false; r.containerType = cm.containerType; @@ -991,6 +1016,10 @@ public class DefaultCodegen { } p.jsonSchema = Json.pretty(param); + if (System.getProperty("debugParser") != null) { + LOGGER.info("working on Parameter " + param); + } + // move the defaultValue for headers, forms and params if (param instanceof QueryParameter) { p.defaultValue = ((QueryParameter) param).getDefaultValue(); @@ -1004,7 +1033,11 @@ public class DefaultCodegen { SerializableParameter qp = (SerializableParameter) param; Property property = null; String collectionFormat = null; - if ("array".equals(qp.getType())) { + String type = qp.getType(); + if (null == type) { + LOGGER.warn("Type is NULL for Serializable Parameter: " + param); + } + if ("array".equals(type)) { Property inner = qp.getItems(); if (inner == null) { LOGGER.warn("warning! No inner type supplied for array parameter \"" + qp.getName() + "\", using String"); @@ -1016,7 +1049,7 @@ public class DefaultCodegen { p.baseType = pr.datatype; p.isContainer = true; imports.add(pr.baseType); - } else if ("object".equals(qp.getType())) { + } else if ("object".equals(type)) { Property inner = qp.getItems(); if (inner == null) { LOGGER.warn("warning! No inner type supplied for map parameter \"" + qp.getName() + "\", using String"); @@ -1029,12 +1062,13 @@ public class DefaultCodegen { imports.add(pr.baseType); } else { Map args = new HashMap(); + String format = qp.getFormat(); args.put(PropertyId.ENUM, qp.getEnum()); - property = PropertyBuilder.build(qp.getType(), qp.getFormat(), args); + property = PropertyBuilder.build(type, format, args); } if (property == null) { - LOGGER.warn("warning! Property type \"" + qp.getType() + "\" not found for parameter \"" + param.getName() + "\", using String"); - property = new StringProperty().description("//TODO automatically added by swagger-codegen. Type was " + qp.getType() + " but not supported"); + LOGGER.warn("warning! Property type \"" + type + "\" not found for parameter \"" + param.getName() + "\", using String"); + property = new StringProperty().description("//TODO automatically added by swagger-codegen. Type was " + type + " but not supported"); } property.setRequired(param.getRequired()); CodegenProperty model = fromProperty(qp.getName(), property); @@ -1049,6 +1083,10 @@ public class DefaultCodegen { imports.add(model.complexType); } } else { + if (!(param instanceof BodyParameter)) { + LOGGER.error("Cannot use Parameter " + param + " as Body Parameter"); + } + BodyParameter bp = (BodyParameter) param; Model model = bp.getSchema(); @@ -1059,12 +1097,17 @@ public class DefaultCodegen { p.dataType = getTypeDeclaration(cm.classname); imports.add(p.dataType); } else { - // TODO: missing format, so this will not always work - Property prop = PropertyBuilder.build(impl.getType(), null, null); + Property prop = PropertyBuilder.build(impl.getType(), impl.getFormat(), null); prop.setRequired(bp.getRequired()); CodegenProperty cp = fromProperty("property", prop); if (cp != null) { p.dataType = cp.datatype; + if (p.dataType.equals("byte[]")) { + p.isBinary = true; + } + else { + p.isBinary = false; + } } } } else if (model instanceof ArrayModel) { @@ -1287,7 +1330,7 @@ public class DefaultCodegen { m.emptyVars = true; } } - + /** * Remove characters not suitable for variable or method name from the input and camelize it @@ -1308,7 +1351,7 @@ public class DefaultCodegen { name = name.substring(0, 1).toLowerCase() + name.substring(1); } return name; - } + } public static String camelize(String word) { return camelize(word, false); @@ -1387,4 +1430,71 @@ public class DefaultCodegen { public void setSkipOverwrite(boolean skipOverwrite) { this.skipOverwrite = skipOverwrite; } + + /** + * All library templates supported. + * (key: library name, value: library description) + */ + public Map supportedLibraries() { + return supportedLibraries; + } + + public void setLibrary(String library) { + if (library != null && !supportedLibraries.containsKey(library)) + throw new RuntimeException("unknown library: " + library); + this.library = library; + } + + /** + * Library template (sub-template). + */ + public String getLibrary() { + return library; + } + + protected CliOption buildLibraryCliOption(Map supportedLibraries) { + StringBuilder sb = new StringBuilder("library template (sub-template) to use:"); + for (String lib : supportedLibraries.keySet()) { + sb.append("\n").append(lib).append(" - ").append(supportedLibraries.get(lib)); + } + return new CliOption("library", sb.toString()); + } + + /** + * sanitize name (parameter, property, method, etc) + * + * @param name string to be sanitize + * @return sanitized string + */ + public String sanitizeName(String name) { + // NOTE: performance wise, we should have written with 2 replaceAll to replace desired + // character with _ or empty character. Below aims to spell out different cases we've + // encountered so far and hopefully make it easier for others to add more special + // cases in the future. + + // input[] => input + name = name.replaceAll("\\[\\]", ""); + + // input[a][b] => input_a_b + name = name.replaceAll("\\[", "_"); + name = name.replaceAll("\\]", ""); + + // input(a)(b) => input_a_b + name = name.replaceAll("\\(", "_"); + name = name.replaceAll("\\)", ""); + + // input.name => input_name + name = name.replaceAll("\\.", "_"); + + // input-name => input_name + name = name.replaceAll("-", "_"); + + // input name and age => input_name_and_age + name = name.replaceAll(" ", "_"); + + // remove everything else other than word, number and _ + // $php_variable => php_variable + return name.replaceAll("[^a-zA-Z0-9_]", ""); + + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 5e4566ab3748..e5a49f4eba46 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -1,8 +1,11 @@ package io.swagger.codegen; +import static org.apache.commons.lang3.StringUtils.capitalize; +import static org.apache.commons.lang3.StringUtils.isNotEmpty; + import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; - +import io.swagger.codegen.languages.CodeGenStatus; import io.swagger.models.ComposedModel; import io.swagger.models.Contact; import io.swagger.models.Info; @@ -15,8 +18,10 @@ import io.swagger.models.auth.OAuth2Definition; import io.swagger.models.auth.SecuritySchemeDefinition; import io.swagger.models.parameters.Parameter; import io.swagger.util.Json; - import org.apache.commons.io.IOUtils; +import org.joda.time.DateTime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; @@ -35,14 +40,16 @@ import java.util.List; import java.util.Map; import java.util.Set; -import static org.apache.commons.lang3.StringUtils.capitalize; -import static org.apache.commons.lang3.StringUtils.isNotEmpty; - public class DefaultGenerator extends AbstractGenerator implements Generator { + Logger LOGGER = LoggerFactory.getLogger(DefaultGenerator.class); + protected CodegenConfig config; protected ClientOptInput opts = null; protected Swagger swagger = null; + public CodeGenStatus status = CodeGenStatus.UNRUN; + + @Override public Generator opts(ClientOptInput opts) { this.opts = opts; @@ -53,6 +60,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { return this; } + @Override public List generate() { if (swagger == null || config == null) { throw new RuntimeException("missing swagger input or config!"); @@ -63,6 +71,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { List files = new ArrayList(); try { config.processOpts(); + + config.additionalProperties().put("generatedDate", DateTime.now().toString()); + config.additionalProperties().put("generatorClass", config.getClass().toString()); + if (swagger.getInfo() != null) { Info info = swagger.getInfo(); if (info.getTitle() != null) { @@ -140,9 +152,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { if (!config.shouldOverwrite(filename)) { continue; } - String template = readTemplate(config.templateDir() + File.separator + templateName); + String templateFile = getFullTemplateFile(config, templateName); + String template = readTemplate(templateFile); Template tmpl = Mustache.compiler() .withLoader(new Mustache.TemplateLoader() { + @Override public Reader getTemplate(String name) { return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); } @@ -188,13 +202,15 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { for (String templateName : config.apiTemplateFiles().keySet()) { String filename = config.apiFilename(templateName, tag); - if (!config.shouldOverwrite(filename)) { + if (!config.shouldOverwrite(filename) && new File(filename).exists()) { continue; } - String template = readTemplate(config.templateDir() + File.separator + templateName); + String templateFile = getFullTemplateFile(config, templateName); + String template = readTemplate(templateFile); Template tmpl = Mustache.compiler() .withLoader(new Mustache.TemplateLoader() { + @Override public Reader getTemplate(String name) { return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); } @@ -263,10 +279,13 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { continue; } - if (support.templateFile.endsWith("mustache")) { - String template = readTemplate(config.templateDir() + File.separator + support.templateFile); + String templateFile = getFullTemplateFile(config, support.templateFile); + + if (templateFile.endsWith("mustache")) { + String template = readTemplate(templateFile); Template tmpl = Mustache.compiler() .withLoader(new Mustache.TemplateLoader() { + @Override public Reader getTemplate(String name) { return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); } @@ -280,12 +299,12 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { InputStream in = null; try { - in = new FileInputStream(config.templateDir() + File.separator + support.templateFile); + in = new FileInputStream(templateFile); } catch (Exception e) { // continue } if (in == null) { - in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(config.templateDir() + File.separator + support.templateFile)); + in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(templateFile)); } File outputFile = new File(outputFilename); OutputStream out = new FileOutputStream(outputFile, false); @@ -294,7 +313,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { IOUtils.copy(in, out); } else { if (in == null) { - System.out.println("can't open " + config.templateDir() + File.separator + support.templateFile + " for input"); + System.out.println("can't open " + templateFile + " for input"); } if (out == null) { System.out.println("can't open " + outputFile + " for output"); @@ -306,8 +325,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } config.processSwagger(swagger); + + status = CodeGenStatus.SUCCESSFUL; } catch (Exception e) { - e.printStackTrace(); + status = CodeGenStatus.FAILED; } return files; } @@ -404,6 +425,9 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { public void processOperation(String resourcePath, String httpMethod, Operation operation, Map> operations, Path path) { if (operation != null) { + if (System.getProperty("debugOperations") != null) { + LOGGER.debug("processOperation: resourcePath= " + resourcePath + "\t;" + httpMethod + " " + operation + "\n"); + } List tags = operation.getTags(); if (tags == null) { tags = new ArrayList(); @@ -433,44 +457,54 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } for (String tag : tags) { - CodegenOperation co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions()); - co.tags = new ArrayList(); - co.tags.add(sanitizeTag(tag)); - config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations); + CodegenOperation co = null; + try { + co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions()); + co.tags = new ArrayList(); + co.tags.add(sanitizeTag(tag)); + config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations); - List>> securities = operation.getSecurity(); - if (securities == null) { - continue; - } - Map authMethods = new HashMap(); - for (Map> security : securities) { - if (security.size() != 1) { - //Not sure what to do + List>> securities = operation.getSecurity(); + if (securities == null) { continue; } - String securityName = security.keySet().iterator().next(); - SecuritySchemeDefinition securityDefinition = fromSecurity(securityName); - if (securityDefinition != null) { - if(securityDefinition instanceof OAuth2Definition) { - OAuth2Definition oauth2Definition = (OAuth2Definition) securityDefinition; - OAuth2Definition oauth2Operation = new OAuth2Definition(); - oauth2Operation.setType(oauth2Definition.getType()); - oauth2Operation.setAuthorizationUrl(oauth2Definition.getAuthorizationUrl()); - oauth2Operation.setFlow(oauth2Definition.getFlow()); - oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl()); - for (String scope : security.values().iterator().next()) { - if (oauth2Definition.getScopes().containsKey(scope)) { - oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope)); - } - } - authMethods.put(securityName, oauth2Operation); - } else { - authMethods.put(securityName, securityDefinition); - } + Map authMethods = new HashMap(); + for (Map> security : securities) { + if (security.size() != 1) { + //Not sure what to do + continue; + } + String securityName = security.keySet().iterator().next(); + SecuritySchemeDefinition securityDefinition = fromSecurity(securityName); + if (securityDefinition != null) { + if(securityDefinition instanceof OAuth2Definition) { + OAuth2Definition oauth2Definition = (OAuth2Definition) securityDefinition; + OAuth2Definition oauth2Operation = new OAuth2Definition(); + oauth2Operation.setType(oauth2Definition.getType()); + oauth2Operation.setAuthorizationUrl(oauth2Definition.getAuthorizationUrl()); + oauth2Operation.setFlow(oauth2Definition.getFlow()); + oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl()); + for (String scope : security.values().iterator().next()) { + if (oauth2Definition.getScopes().containsKey(scope)) { + oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope)); + } + } + authMethods.put(securityName, oauth2Operation); + } else { + authMethods.put(securityName, securityDefinition); + } + } + } + if (!authMethods.isEmpty()) { + co.authMethods = config.fromSecurity(authMethods); } } - if (!authMethods.isEmpty()) { - co.authMethods = config.fromSecurity(authMethods); + catch (Exception ex) { + LOGGER.error("Error while trying to get Config from Operation for tag(" + tag + ")\n" // + + "\tResource: " + httpMethod + " " + resourcePath + "\n"// + + "\tOperation:" + operation + "\n" // + + "\tDefinitions: " + swagger.getDefinitions() + "\n"); + ex.printStackTrace(); } } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java index 73294268f39d..a6bfc7d5ddd6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java @@ -128,7 +128,7 @@ public class XmlExampleGenerator { ArrayProperty p = (ArrayProperty) property; Property inner = p.getItems(); boolean wrapped = false; - if (property.getXml() != null && property.getXml().getWrapped()) { + if (property.getXml() != null && property.getXml().getWrapped() != null && property.getXml().getWrapped()) { wrapped = true; } if (wrapped) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java index f9490e3d3dd7..c40eb6535430 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java @@ -4,6 +4,7 @@ import com.google.common.base.CaseFormat; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenResponse; @@ -80,10 +81,10 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon "trait", "try", "true", "type", "val", "var", "while", "with", "yield") ); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); additionalProperties.put("configKey", configKey); additionalProperties.put("configKeyPath", configKeyPath); additionalProperties.put("defaultTimeout", defaultTimeoutInMs); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index f570cc42e821..9c55053e59cd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -2,6 +2,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; @@ -58,11 +59,11 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi instantiationTypes.put("array", "ArrayList"); instantiationTypes.put("map", "HashMap"); - cliOptions.add(new CliOption("invokerPackage", "root package to use for the generated code")); - cliOptions.add(new CliOption("groupId", "groupId for use in the generated build.gradle and pom.xml")); - cliOptions.add(new CliOption("artifactId", "artifactId for use in the generated build.gradle and pom.xml")); - cliOptions.add(new CliOption("artifactVersion", "artifact version for use in the generated build.gradle and pom.xml")); - cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); + cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, "groupId for use in the generated build.gradle and pom.xml")); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, "artifactId for use in the generated build.gradle and pom.xml")); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "artifact version for use in the generated build.gradle and pom.xml")); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); cliOptions.add(new CliOption("useAndroidMavenGradlePlugin", "A flag to toggle android-maven gradle plugin. Default is true.")); } @@ -187,36 +188,36 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("invokerPackage")) { - this.setInvokerPackage((String) additionalProperties.get("invokerPackage")); + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); } else { //not set, use default to be passed to template - additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); } - if (additionalProperties.containsKey("groupId")) { - this.setGroupId((String) additionalProperties.get("groupId")); + if (additionalProperties.containsKey(CodegenConstants.GROUP_ID)) { + this.setGroupId((String) additionalProperties.get(CodegenConstants.GROUP_ID)); } else { //not set, use to be passed to template - additionalProperties.put("groupId", groupId); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); } - if (additionalProperties.containsKey("artifactId")) { - this.setArtifactId((String) additionalProperties.get("artifactId")); + if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_ID)) { + this.setArtifactId((String) additionalProperties.get(CodegenConstants.ARTIFACT_ID)); } else { //not set, use to be passed to template - additionalProperties.put("artifactId", artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); } - if (additionalProperties.containsKey("artifactVersion")) { - this.setArtifactVersion((String) additionalProperties.get("artifactVersion")); + if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) { + this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION)); } else { //not set, use to be passed to template - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); } - if (additionalProperties.containsKey("sourceFolder")) { - this.setSourceFolder((String) additionalProperties.get("sourceFolder")); + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { + this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } if (additionalProperties.containsKey("useAndroidMavenGradlePlugin")) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java index 53faf2f9e1fc..38e6328a8e55 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; @@ -52,10 +53,10 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo "trait", "try", "true", "type", "val", "var", "while", "with", "yield") ); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); additionalProperties.put("asyncHttpClient", asyncHttpClient); additionalProperties.put("authScheme", authScheme); additionalProperties.put("authPreemptive", authPreemptive); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index 1d7accd3b274..09ec05b078bf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -146,8 +146,8 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + // sanitize name + name = sanitizeName(name); // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) { @@ -249,7 +249,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); } - return camelize(operationId); + return camelize(sanitizeName(operationId)); } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CodeGenStatus.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CodeGenStatus.java new file mode 100644 index 000000000000..aa22958517fd --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CodeGenStatus.java @@ -0,0 +1,5 @@ +package io.swagger.codegen.languages; + +public enum CodeGenStatus { + UNRUN, SUCCESSFUL, FAILED +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java index ca0979fb694d..7c484c38a0b9 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java @@ -2,34 +2,27 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.AbstractNumericProperty; -import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.BooleanProperty; import io.swagger.models.properties.DateProperty; import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DecimalProperty; import io.swagger.models.properties.DoubleProperty; import io.swagger.models.properties.FloatProperty; import io.swagger.models.properties.IntegerProperty; import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; -import io.swagger.models.properties.PropertyBuilder; -import io.swagger.models.properties.RefProperty; import io.swagger.models.properties.StringProperty; +import org.apache.commons.lang.StringUtils; import java.io.File; import java.util.Arrays; -import java.util.HashSet; import java.util.HashMap; - -import org.apache.commons.lang.StringUtils; +import java.util.HashSet; public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig { protected String packageName = "io.swagger"; @@ -82,8 +75,8 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig cliOptions.clear(); cliOptions.add(new CliOption("packageName", "flash package name (convention: package.name), default: io.swagger")); cliOptions.add(new CliOption("packageVersion", "flash package version, default: 1.0.0")); - cliOptions.add(new CliOption("invokerPackage", "root package for generated code")); - cliOptions.add(new CliOption("sourceFolder", "source folder for generated code. e.g. src/main/flex")); + cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, "source folder for generated code. e.g. src/main/flex")); } @@ -91,15 +84,15 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("invokerPackage")) { - this.setInvokerPackage((String) additionalProperties.get("invokerPackage")); + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); } else { //not set, use default to be passed to template - additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); } - if (additionalProperties.containsKey("sourceFolder")) { - this.setSourceFolder((String) additionalProperties.get("sourceFolder")); + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { + this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } if (additionalProperties.containsKey("packageName")) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index 099a9cb9adde..326d98010d6e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -1,27 +1,43 @@ package io.swagger.codegen.languages; +import com.google.common.base.Strings; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; +import io.swagger.models.Model; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; import java.io.File; +import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { + private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class); + protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-java-client"; protected String artifactVersion = "1.0.0"; protected String sourceFolder = "src/main/java"; protected String localVariablePrefix = ""; + protected Boolean serializableModel = false; + public JavaClientCodegen() { super(); outputFolder = "generated-code/java"; @@ -51,27 +67,36 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { "Integer", "Long", "Float", - "Object") + "Object", + "byte[]") ); instantiationTypes.put("array", "ArrayList"); instantiationTypes.put("map", "HashMap"); - cliOptions.add(new CliOption("invokerPackage", "root package for generated code")); - cliOptions.add(new CliOption("groupId", "groupId in generated pom.xml")); - cliOptions.add(new CliOption("artifactId", "artifactId in generated pom.xml")); - cliOptions.add(new CliOption("artifactVersion", "artifact version in generated pom.xml")); - cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); - cliOptions.add(new CliOption("localVariablePrefix", "prefix for generated code members and local variables")); + cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); + cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC)); + + supportedLibraries.put("", "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); + supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); + cliOptions.add(buildLibraryCliOption(supportedLibraries)); } + @Override public CodegenType getTag() { return CodegenType.CLIENT; } + @Override public String getName() { return "java"; } + @Override public String getHelp() { return "Generates a Java client library."; } @@ -79,52 +104,62 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public void processOpts() { super.processOpts(); - - if (additionalProperties.containsKey("invokerPackage")) { - this.setInvokerPackage((String) additionalProperties.get("invokerPackage")); + + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); } else { //not set, use default to be passed to template - additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); } - if (additionalProperties.containsKey("groupId")) { - this.setGroupId((String) additionalProperties.get("groupId")); + if (additionalProperties.containsKey(CodegenConstants.GROUP_ID)) { + this.setGroupId((String) additionalProperties.get(CodegenConstants.GROUP_ID)); } else { //not set, use to be passed to template - additionalProperties.put("groupId", groupId); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); } - if (additionalProperties.containsKey("artifactId")) { - this.setArtifactId((String) additionalProperties.get("artifactId")); + if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_ID)) { + this.setArtifactId((String) additionalProperties.get(CodegenConstants.ARTIFACT_ID)); } else { //not set, use to be passed to template - additionalProperties.put("artifactId", artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); } - if (additionalProperties.containsKey("artifactVersion")) { - this.setArtifactVersion((String) additionalProperties.get("artifactVersion")); + if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) { + this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION)); } else { //not set, use to be passed to template - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); } - if (additionalProperties.containsKey("sourceFolder")) { - this.setSourceFolder((String) additionalProperties.get("sourceFolder")); + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { + this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } - if (additionalProperties.containsKey("localVariablePrefix")) { - this.setLocalVariablePrefix((String) additionalProperties.get("localVariablePrefix")); + if (additionalProperties.containsKey(CodegenConstants.LOCAL_VARIABLE_PREFIX)) { + this.setLocalVariablePrefix((String) additionalProperties.get(CodegenConstants.LOCAL_VARIABLE_PREFIX)); } + if (additionalProperties.containsKey(CodegenConstants.SERIALIZABLE_MODEL)) { + this.setSerializableModel(Boolean.valueOf((String)additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL).toString())); + } + + // need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string + additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel); + + this.sanitizeConfig(); + final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); - supportingFiles.add(new SupportingFile("JsonUtil.mustache", invokerFolder, "JsonUtil.java")); - supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); + supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); + supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); + supportingFiles.add(new SupportingFile("TypeRef.mustache", invokerFolder, "TypeRef.java")); final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator); supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); @@ -133,7 +168,26 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); } - + private void sanitizeConfig() { + // Sanitize any config options here. We also have to update the additionalProperties because + // the whole additionalProperties object is injected into the main object passed to the mustache layer + + this.setApiPackage(sanitizePackageName(apiPackage)); + if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { + this.additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); + } + + this.setModelPackage(sanitizePackageName(modelPackage)); + if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { + this.additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); + } + + this.setInvokerPackage(sanitizePackageName(invokerPackage)); + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + } + } + @Override public String escapeReservedWord(String name) { return "_" + name; @@ -144,14 +198,15 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); } + @Override public String modelFileFolder() { return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); } @Override public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + // sanitize name + name = sanitizeName(name); if("_".equals(name)) { name = "_u"; @@ -182,6 +237,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toModelName(String name) { + name = sanitizeName(name); + // model name cannot use reserved keyword, e.g. return if (reservedWords.contains(name)) { throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); @@ -232,11 +289,14 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { if (typeMapping.containsKey(swaggerType)) { type = typeMapping.get(swaggerType); if (languageSpecificPrimitives.contains(type)) { - return toModelName(type); + return type; } } else { type = swaggerType; } + if (null == type) { + LOGGER.error("No Type defined for Property " + p); + } return toModelName(type); } @@ -252,7 +312,85 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); } - return camelize(operationId, true); + return camelize(sanitizeName(operationId), true); + } + + @Override + public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); + + if (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) { + final Model parentModel = allDefinitions.get(toModelName(codegenModel.parent)); + final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); + codegenModel = this.reconcileInlineEnums(codegenModel, parentCodegenModel); + } + + return codegenModel; + } + + @Override + public Map postProcessModels(Map objs) { + List models = (List) objs.get("models"); + for (Object _mo : models) { + Map mo = (Map) _mo; + CodegenModel cm = (CodegenModel) mo.get("model"); + for (CodegenProperty var : cm.vars) { + Map allowableValues = var.allowableValues; + if (allowableValues == null) + continue; + List values = (List) allowableValues.get("values"); + // put "enumVars" map into `allowableValues", including `name` and `value` + if (values == null) + continue; + List> enumVars = new ArrayList>(); + for (String value : values) { + Map enumVar = new HashMap(); + enumVar.put("name", toVarName(value.toUpperCase())); + enumVar.put("value", value); + enumVars.add(enumVar); + } + allowableValues.put("enumVars", enumVars); + } + } + return objs; + } + + private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { + // This generator uses inline classes to define enums, which breaks when + // dealing with models that have subTypes. To clean this up, we will analyze + // the parent and child models, look for enums that match, and remove + // them from the child models and leave them in the parent. + // Because the child models extend the parents, the enums will be available via the parent. + + // Only bother with reconciliation if the parent model has enums. + if (parentCodegenModel.hasEnums) { + + // Get the properties for the parent and child models + final List parentModelCodegenProperties = parentCodegenModel.vars; + List codegenProperties = codegenModel.vars; + + // Iterate over all of the parent model properties + for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) { + // Look for enums + if (parentModelCodegenPropery.isEnum) { + // Now that we have found an enum in the parent class, + // and search the child class for the same enum. + Iterator iterator = codegenProperties.iterator(); + while (iterator.hasNext()) { + CodegenProperty codegenProperty = iterator.next(); + if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) { + // We found an enum in the child class that is + // a duplicate of the one in the parent, so remove it. + iterator.remove(); + } + } + } + } + + codegenModel.vars = codegenProperties; + } + + return codegenModel; } public void setInvokerPackage(String invokerPackage) { @@ -278,4 +416,23 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { public void setLocalVariablePrefix(String localVariablePrefix) { this.localVariablePrefix = localVariablePrefix; } + + + public Boolean getSerializableModel() { + return serializableModel; + } + + public void setSerializableModel(Boolean serializableModel) { + this.serializableModel = serializableModel; + } + + private String sanitizePackageName(String packageName) { + packageName = packageName.trim(); + packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_"); + if(Strings.isNullOrEmpty(packageName)) { + return "invalidPackageName"; + } + return packageName; + } + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java index 168e214aef15..56dbdd0e48b8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenType; import io.swagger.codegen.SupportingFile; @@ -38,10 +39,10 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen implements Cod apiPackage = System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.handler"); modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model"); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); additionalProperties.put("title", title); languageSpecificPrimitives = new HashSet( diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java index df3207975154..eb0f6be03e9d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java @@ -1,13 +1,12 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenResponse; import io.swagger.codegen.CodegenType; import io.swagger.codegen.SupportingFile; import io.swagger.models.Operation; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; import java.io.File; import java.util.ArrayList; @@ -38,10 +37,10 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf apiPackage = System.getProperty("swagger.codegen.jaxrs.apipackage", "io.swagger.api"); modelPackage = System.getProperty("swagger.codegen.jaxrs.modelpackage", "io.swagger.model"); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); additionalProperties.put("title", title); @@ -122,27 +121,35 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf if (operations != null) { List ops = (List) operations.get("operation"); for (CodegenOperation operation : ops) { + List responses = operation.responses; + if (responses != null) { + for (CodegenResponse resp : responses) { + if ("0".equals(resp.code)) { + resp.code = "200"; + } + } + } if (operation.returnType == null) { operation.returnType = "Void"; } else if (operation.returnType.startsWith("List")) { String rt = operation.returnType; int end = rt.lastIndexOf(">"); if (end > 0) { - operation.returnType = rt.substring("List<".length(), end); + operation.returnType = rt.substring("List<".length(), end).trim(); operation.returnContainer = "List"; } } else if (operation.returnType.startsWith("Map")) { String rt = operation.returnType; int end = rt.lastIndexOf(">"); if (end > 0) { - operation.returnType = rt.substring("Map<".length(), end); + operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim(); operation.returnContainer = "Map"; } } else if (operation.returnType.startsWith("Set")) { String rt = operation.returnType; int end = rt.lastIndexOf(">"); if (end > 0) { - operation.returnType = rt.substring("Set<".length(), end); + operation.returnType = rt.substring("Set<".length(), end).trim(); operation.returnContainer = "Set"; } } @@ -156,7 +163,7 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf if (name.length() == 0) { return "DefaultApi"; } - name = name.replaceAll("[^a-zA-Z0-9]+", "_"); + name = sanitizeName(name); return camelize(name) + "Api"; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java index 5d0a7034537f..10070ece5121 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java @@ -207,11 +207,14 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig } @SuppressWarnings("unchecked") - private Map getOperations(Map objs) { + private List> getOperations(Map objs) { + List> result = new ArrayList>(); Map apiInfo = (Map) objs.get("apiInfo"); List> apis = (List>) apiInfo.get("apis"); - Map api = apis.get(0); - return (Map) api.get("operations"); + for (Map api : apis) { + result.add((Map) api.get("operations")); + } + return result; } private List> sortOperationsByPath(List ops) { @@ -221,7 +224,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig opsByPath.put(op.path, op); } - List> opsByPathList = new ArrayList>(); + List> opsByPathList = new ArrayList>(); for (Entry> entry : opsByPath.asMap().entrySet()) { Map opsByPathEntry = new HashMap(); opsByPathList.add(opsByPathEntry); @@ -239,16 +242,13 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig @Override public Map postProcessSupportingFileData(Map objs) { - Map operations = getOperations(objs); - - if (operations != null) { + for (Map operations : getOperations(objs)) { @SuppressWarnings("unchecked") List ops = (List) operations.get("operation"); List> opsByPathList = sortOperationsByPath(ops); operations.put("operationsByPath", opsByPathList); } - return super.postProcessSupportingFileData(objs); } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index cb6ec79a9848..dfb4094f2b65 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -328,9 +328,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toVarName(String name) { - // replace non-word characters to `_` - // e.g. `created-at` to `created_at` - name = name.replaceAll("[^a-zA-Z0-9_]", "_"); + // sanitize name + name = sanitizeName(name); // if it's all upper case, do noting if (name.matches("^[A-Z_]$")) { @@ -371,7 +370,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); } - return camelize(operationId, true); + return camelize(sanitizeName(operationId), true); } public void setClassPrefix(String classPrefix) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index eaf758cf1c4b..ac2cddfefa98 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -2,6 +2,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; @@ -15,7 +16,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "Swagger\\Client"; @@ -24,6 +25,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String packagePath = "SwaggerClient-php"; protected String artifactVersion = "1.0.0"; protected String srcBasePath = "lib"; + protected String variableNamingConvention= "snake_case"; public PhpClientCodegen() { super(); @@ -61,6 +63,11 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { instantiationTypes.put("array", "array"); instantiationTypes.put("map", "map"); + + // provide primitives to mustache template + String primitives = "'" + StringUtils.join(languageSpecificPrimitives, "', '") + "'"; + additionalProperties.put("primitives", primitives); + // ref: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#data-types typeMapping = new HashMap(); typeMapping.put("integer", "int"); @@ -78,13 +85,14 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("list", "array"); typeMapping.put("object", "object"); typeMapping.put("DateTime", "\\DateTime"); - - cliOptions.add(new CliOption("invokerPackage", "The main namespace to use for all classes. e.g. Yay\\Pets")); + + cliOptions.add(new CliOption("variableNamingConvention", "naming convention of variable name, e.g. camelCase. Default: snake_case")); + cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, "The main namespace to use for all classes. e.g. Yay\\Pets")); cliOptions.add(new CliOption("packagePath", "The main package name for classes. e.g. GeneratedPetstore")); cliOptions.add(new CliOption("srcBasePath", "The directory under packagePath to serve as source root.")); cliOptions.add(new CliOption("composerVendorName", "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. yaypets")); cliOptions.add(new CliOption("composerProjectName", "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client")); - cliOptions.add(new CliOption("artifactVersion", "The version to use in the composer package version field. e.g. 1.2.3")); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "The version to use in the composer package version field. e.g. 1.2.3")); } public String getPackagePath() { @@ -148,22 +156,22 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("srcBasePath", srcBasePath); } - if (additionalProperties.containsKey("invokerPackage")) { - this.setInvokerPackage((String) additionalProperties.get("invokerPackage")); + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); } else { - additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); } - if (additionalProperties.containsKey("modelPackage")) { - this.setModelPackage((String) additionalProperties.get("modelPackage")); + if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { + this.setModelPackage((String) additionalProperties.get(CodegenConstants.MODEL_PACKAGE)); } else { - additionalProperties.put("modelPackage", modelPackage); + additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); } - if (additionalProperties.containsKey("apiPackage")) { - this.setApiPackage((String) additionalProperties.get("apiPackage")); + if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { + this.setApiPackage((String) additionalProperties.get(CodegenConstants.API_PACKAGE)); } else { - additionalProperties.put("apiPackage", apiPackage); + additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); } if (additionalProperties.containsKey("composerProjectName")) { @@ -178,10 +186,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("composerVendorName", composerVendorName); } - if (additionalProperties.containsKey("artifactVersion")) { - this.setArtifactVersion((String) additionalProperties.get("artifactVersion")); + if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) { + this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION)); } else { - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); } additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); @@ -274,6 +282,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { this.srcBasePath = srcBasePath; } + public void setParameterNamingConvention(String variableNamingConvention) { + this.variableNamingConvention = variableNamingConvention; + } + private void setComposerVendorName(String composerVendorName) { this.composerVendorName = composerVendorName; } @@ -284,9 +296,22 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toVarName(String name) { - // return the name in underscore style - // PhoneNumber => phone_number - name = underscore(name); + if (additionalProperties.containsKey("variableNamingConvention")) { + this.setParameterNamingConvention((String) additionalProperties.get("variableNamingConvention")); + } + + // sanitize name + name = sanitizeName(name); + + if ("camelCase".equals(variableNamingConvention)) { + // return the name in camelCase style + // phone_number => phoneNumber + name = camelize(name, true); + } else { // default to snake case + // return the name in underscore style + // PhoneNumber => phone_number + name = underscore(name); + } // parameter name starting with number won't compile // need to escape it by appending _ at the beginning @@ -320,4 +345,20 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { // should be the same as the model name return toModelName(name); } + + @Override + public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + + // method name cannot use reserved keyword, e.g. return + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } + + return camelize(sanitizeName(operationId), true); + } + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index e0e1bdc07f8d..8926a79343a5 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -61,7 +61,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig "return", "def", "for", "lambda", "try")); cliOptions.clear(); - cliOptions.add(new CliOption("packageName", "python package name (convension: under_score), default: swagger_client")); + cliOptions.add(new CliOption("packageName", "python package name (convention: snake_case), default: swagger_client")); cliOptions.add(new CliOption("packageVersion", "python package version, default: 1.0.0")); } @@ -119,7 +119,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String escapeReservedWord(String name) { - return name + "_"; + return "_" + name; } @Override @@ -167,8 +167,8 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + // sanitize name + name = sanitizeName(name); // if it's all uppper case, convert to lower case if (name.matches("^[A-Z_]*$")) { @@ -177,16 +177,16 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig // underscore the variable name // petId => pet_id - name = underscore(dropDots(name)); + name = underscore(name); + + // remove leading underscore + name = name.replaceAll("^_*", ""); // for reserved word or word starting with number, append _ if (reservedWords.contains(name) || name.matches("^\\d.*")) { name = escapeReservedWord(name); } - // remove leading underscore - name = name.replaceAll("^_*", ""); - return name; } @@ -258,7 +258,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); } - return underscore(operationId); + return underscore(sanitizeName(operationId)); } public void setPackageName(String packageName) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java index 66d3f19f948b..37c119edfb67 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; @@ -44,10 +45,10 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf "native", "super", "while") ); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("service.mustache", diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index 59b62b0be6ad..f608c4b8d0f3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -196,10 +196,8 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toVarName(String name) { - // remove trailing special characters, e.g. "post[created-at]!!" => "post[created-at" - name = name.replaceAll("\\W+\\z", ""); - // replace special characters with _, e.g. "post[created-at" => "post_created_at" - name = name.replaceAll("\\W+", "_"); + // sanitize name + name = sanitizeName(name); // if it's all uppper case, convert to lower case if (name.matches("^[A-Z_]*$")) { @@ -278,7 +276,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); } - return underscore(operationId); + return underscore(sanitizeName(operationId)); } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java index 5d8ae4b89b63..003be5ab950b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; @@ -54,10 +55,10 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig "trait", "try", "true", "type", "val", "var", "while", "with", "yield") ); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); additionalProperties.put("asyncHttpClient", asyncHttpClient); additionalProperties.put("authScheme", authScheme); additionalProperties.put("authPreemptive", authPreemptive); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java index d6b0f78253a9..9bab6a6cad03 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; @@ -73,10 +74,10 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf additionalProperties.put("infoEmail", "apiteam@swagger.io"); additionalProperties.put("licenseInfo", "All rights reserved"); additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java index 8bd4d627d567..e25aae159760 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; @@ -41,10 +42,10 @@ public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor") ); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); // ref: http://php.net/manual/en/language.types.intro.php languageSpecificPrimitives = new HashSet( diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java index 8ee34768b5ee..863a1aef2e70 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java @@ -34,12 +34,12 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen configPackage = "io.swagger.configuration"; - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); additionalProperties.put("title", title); - additionalProperties.put("apiPackage", apiPackage); + additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); additionalProperties.put("configPackage", configPackage); languageSpecificPrimitives = new HashSet( @@ -102,21 +102,6 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen } - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getTypeDeclaration(inner); - } - return super.getTypeDeclaration(p); - } - @Override public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { String basePath = resourcePath; @@ -158,27 +143,30 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen } } } + System.out.println(operation.operationId); + io.swagger.util.Json.prettyPrint(operation); + if (operation.returnType == null) { operation.returnType = "Void"; } else if (operation.returnType.startsWith("List")) { String rt = operation.returnType; int end = rt.lastIndexOf(">"); if (end > 0) { - operation.returnType = rt.substring("List<".length(), end); + operation.returnType = rt.substring("List<".length(), end).trim(); operation.returnContainer = "List"; } } else if (operation.returnType.startsWith("Map")) { String rt = operation.returnType; int end = rt.lastIndexOf(">"); if (end > 0) { - operation.returnType = rt.substring("Map<".length(), end); + operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim(); operation.returnContainer = "Map"; } } else if (operation.returnType.startsWith("Set")) { String rt = operation.returnType; int end = rt.lastIndexOf(">"); if (end > 0) { - operation.returnType = rt.substring("Set<".length(), end); + operation.returnType = rt.substring("Set<".length(), end).trim(); operation.returnContainer = "Set"; } } @@ -187,6 +175,15 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen return objs; } + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + name = sanitizeName(name); + return camelize(name) + "Api"; + } + public void setConfigPackage(String configPackage) { this.configPackage = configPackage; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java index bfee70f1732c..c0ccf2a0a6f4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; @@ -21,10 +22,10 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig { apiTemplateFiles.put("operation.mustache", ".html"); templateDir = "swagger-static"; - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("main.mustache", "", "main.js")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java index 8a3244b00972..29cb5d55eaa6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; @@ -37,10 +38,10 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig additionalProperties.put("infoEmail", "hello@helloreverb.com"); additionalProperties.put("licenseInfo", "All rights reserved"); additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); supportingFiles.add(new SupportingFile("index.mustache", "", "index.html")); reservedWords = new HashSet(); diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 79b445948162..5e18c854cba4 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -1,17 +1,14 @@ package {{invokerPackage}}; -import com.fasterxml.jackson.core.JsonGenerator.Feature; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.api.client.WebResource.Builder; + import com.sun.jersey.multipart.FormDataMultiPart; +import com.sun.jersey.multipart.file.FileDataBodyPart; import javax.ws.rs.core.Response.Status.Family; import javax.ws.rs.core.MediaType; @@ -29,7 +26,9 @@ import java.util.TimeZone; import java.net.URLEncoder; import java.io.IOException; +import java.io.File; import java.io.UnsupportedEncodingException; +import java.io.DataInputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; @@ -40,14 +39,19 @@ import {{invokerPackage}}.auth.HttpBasicAuth; import {{invokerPackage}}.auth.ApiKeyAuth; import {{invokerPackage}}.auth.OAuth; +{{>generatedAnnotation}} public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); private boolean debugging = false; private String basePath = "{{basePath}}"; + private JSON json = new JSON(); private Map authentications; + private int statusCode; + private Map> responseHeaders; + private DateFormat dateFormat; public ApiClient() { @@ -79,6 +83,20 @@ public class ApiClient { return this; } + /** + * Gets the status code of the previous request + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Gets the response headers of the previous request + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + /** * Get authentications (key: authentication name, value: authentication). */ @@ -337,68 +355,47 @@ public class ApiClient { } /** - * Deserialize the given JSON string to Java object. - * - * @param json The JSON string - * @param containerType The container type, one of "list", "array" or "" - * @param cls The type of the Java object - * @return The deserialized Java object + * Serialize the given Java object into string according the given + * Content-Type (only JSON is supported for now). */ - public Object deserialize(String json, String containerType, Class cls) throws ApiException { - if(null != containerType) { - containerType = containerType.toLowerCase(); - } - try{ - if("list".equals(containerType) || "array".equals(containerType)) { - JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls); - List response = (List) JsonUtil.getJsonMapper().readValue(json, typeInfo); - return response; - } - else if(String.class.equals(cls)) { - if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) - return json.substring(1, json.length() - 1); - else - return json; - } - else { - return JsonUtil.getJsonMapper().readValue(json, cls); - } - } - catch (IOException e) { - throw new ApiException(500, e.getMessage(), null, json); + public String serialize(Object obj, String contentType) throws ApiException { + if (contentType.startsWith("application/json")) { + return json.serialize(obj); + } else { + throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); } } /** - * Serialize the given Java object into JSON string. + * Deserialize response body to Java object according to the Content-Type. */ - public String serialize(Object obj) throws ApiException { - try { - if (obj != null) - return JsonUtil.getJsonMapper().writeValueAsString(obj); - else - return null; - } - catch (Exception e) { - throw new ApiException(500, e.getMessage()); + public T deserialize(ClientResponse response, TypeRef returnType) throws ApiException { + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = contentTypes.get(0); + if (contentType == null) + throw new ApiException(500, "missing Content-Type in response"); + + String body; + if (response.hasEntity()) + body = (String) response.getEntity(String.class); + else + body = ""; + + if (contentType.startsWith("application/json")) { + return json.deserialize(body, returnType); + } else { + throw new ApiException(500, "can not deserialize Content-Type: " + contentType); } } - /** - * Invoke API by sending HTTP request with the given options. - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param formParams The form parameters - * @param accept The request's Accept header - * @param contentType The request's Content-Type header - * @param authNames The authentications to apply - * @return The response body in type of string - */ - public String invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + + if (body != null && binaryBody != null){ + throw new ApiException(500, "either body or binaryBody must be null"); + } + updateParamsForAuth(authNames, queryParams, headerParams); Client client = getClient(); @@ -424,80 +421,166 @@ public class ApiClient { else builder = client.resource(basePath + path + querystring).accept(accept); - for(String key : headerParams.keySet()) { + for (String key : headerParams.keySet()) { builder = builder.header(key, headerParams.get(key)); } - for(String key : defaultHeaderMap.keySet()) { - if(!headerParams.containsKey(key)) { + for (String key : defaultHeaderMap.keySet()) { + if (!headerParams.containsKey(key)) { builder = builder.header(key, defaultHeaderMap.get(key)); } } + String encodedFormParams = null; + if (contentType.startsWith("multipart/form-data")) { + FormDataMultiPart mp = new FormDataMultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + mp.field(param.getKey(), file.getName()); + mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE)); + } else { + mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); + } + } + body = mp; + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + encodedFormParams = this.getXWWWFormUrlencodedParams(formParams); + } + ClientResponse response = null; - if("GET".equals(method)) { + if ("GET".equals(method)) { response = (ClientResponse) builder.get(ClientResponse.class); - } - else if ("POST".equals(method)) { - if (contentType.startsWith("application/x-www-form-urlencoded")) { - String encodedFormParams = this - .getXWWWFormUrlencodedParams(formParams); - response = builder.type(contentType).post(ClientResponse.class, - encodedFormParams); + } else if ("POST".equals(method)) { + if (encodedFormParams != null) { + response = builder.type(contentType).post(ClientResponse.class, encodedFormParams); } else if (body == null) { - response = builder.post(ClientResponse.class, null); - } else if(body instanceof FormDataMultiPart) { + if(binaryBody == null) + response = builder.post(ClientResponse.class, null); + else + response = builder.type(contentType).post(ClientResponse.class, binaryBody); + } else if (body instanceof FormDataMultiPart) { response = builder.type(contentType).post(ClientResponse.class, body); - } - else - response = builder.type(contentType).post(ClientResponse.class, serialize(body)); - } - else if ("PUT".equals(method)) { - if ("application/x-www-form-urlencoded".equals(contentType)) { - String encodedFormParams = this - .getXWWWFormUrlencodedParams(formParams); - response = builder.type(contentType).put(ClientResponse.class, - encodedFormParams); - } else if(body == null) { - response = builder.put(ClientResponse.class, serialize(body)); } else { - response = builder.type(contentType).put(ClientResponse.class, serialize(body)); + response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType)); } - } - else if ("DELETE".equals(method)) { - if ("application/x-www-form-urlencoded".equals(contentType)) { - String encodedFormParams = this - .getXWWWFormUrlencodedParams(formParams); - response = builder.type(contentType).delete(ClientResponse.class, - encodedFormParams); + } else if ("PUT".equals(method)) { + if (encodedFormParams != null) { + response = builder.type(contentType).put(ClientResponse.class, encodedFormParams); } else if(body == null) { - response = builder.delete(ClientResponse.class); + if(binaryBody == null) + response = builder.put(ClientResponse.class, null); + else + response = builder.type(contentType).put(ClientResponse.class, binaryBody); } else { - response = builder.type(contentType).delete(ClientResponse.class, serialize(body)); + response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType)); } - } - else { + } else if ("DELETE".equals(method)) { + if (encodedFormParams != null) { + response = builder.type(contentType).delete(ClientResponse.class, encodedFormParams); + } else if(body == null) { + if(binaryBody == null) + response = builder.delete(ClientResponse.class); + else + response = builder.type(contentType).delete(ClientResponse.class, binaryBody); + } else { + response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType)); + } + } else { throw new ApiException(500, "unknown method type " + method); } + return response; + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" + * @param queryParams The query parameters + * @param body The request body object - if it is not binary, otherwise null + * @param binaryBody The request body object - if it is binary, otherwise null + * @param headerParams The header parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @return The response body in type of string + */ + public T invokeAPI(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { + + ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames); + + statusCode = response.getStatusInfo().getStatusCode(); + responseHeaders = response.getHeaders(); + + if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { + return null; + } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { + if (returnType == null) + return null; + else + return deserialize(response, returnType); + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { + try { + respBody = String.valueOf(response.getEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + throw new ApiException( + response.getStatusInfo().getStatusCode(), + message, + response.getHeaders(), + respBody); + } + } + /** + * Invoke API by sending HTTP request with the given options - return binary result + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" + * @param queryParams The query parameters + * @param body The request body object - if it is not binary, otherwise null + * @param binaryBody The request body object - if it is binary, otherwise null + * @param headerParams The header parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @return The response body in type of string + */ + public byte[] invokeBinaryAPI(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[]authNames) throws ApiException { + + ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames); if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { return null; } else if(response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { if(response.hasEntity()) { - return (String) response.getEntity(String.class); + DataInputStream stream = new DataInputStream(response.getEntityInputStream()); + byte[] data = new byte[response.getLength()]; + try { + stream.readFully(data); + } catch (IOException ex) { + throw new ApiException(500, "Error obtaining binary response data"); + } + return data; } else { - return ""; + return new byte[0]; } } else { String message = "error"; - String respBody = null; if(response.hasEntity()) { try{ - respBody = String.valueOf(response.getEntity(String.class)); - message = respBody; + message = String.valueOf(response.getEntity(String.class)); } catch (RuntimeException e) { // e.printStackTrace(); @@ -505,9 +588,7 @@ public class ApiClient { } throw new ApiException( response.getStatusInfo().getStatusCode(), - message, - response.getHeaders(), - respBody); + message); } } @@ -527,15 +608,14 @@ public class ApiClient { /** * Encode the given form parameters as request body. */ - private String getXWWWFormUrlencodedParams(Map formParams) { + private String getXWWWFormUrlencodedParams(Map formParams) { StringBuilder formParamBuilder = new StringBuilder(); - for (Entry param : formParams.entrySet()) { - String keyStr = parameterToString(param.getKey()); + for (Entry param : formParams.entrySet()) { + String keyStr = param.getKey(); String valueStr = parameterToString(param.getValue()); - try { - formParamBuilder.append(URLEncoder.encode(keyStr, "utf8")) + formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8")) .append("=") .append(URLEncoder.encode(valueStr, "utf8")); formParamBuilder.append("&"); @@ -543,11 +623,12 @@ public class ApiClient { // move on to next } } + String encodedFormParams = formParamBuilder.toString(); if (encodedFormParams.endsWith("&")) { - encodedFormParams = encodedFormParams.substring(0, - encodedFormParams.length() - 1); + encodedFormParams = encodedFormParams.substring(0, encodedFormParams.length() - 1); } + return encodedFormParams; } diff --git a/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache index e936b423a91c..4629c4e17be4 100644 --- a/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache @@ -1,5 +1,6 @@ package {{invokerPackage}}; +{{>generatedAnnotation}} public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/modules/swagger-codegen/src/main/resources/Java/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/JSON.mustache new file mode 100644 index 000000000000..7689856f5de5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/JSON.mustache @@ -0,0 +1,54 @@ +package {{invokerPackage}}; + +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; + +import java.io.IOException; + +{{>generatedAnnotation}} +public class JSON { + private ObjectMapper mapper; + + public JSON() { + mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.registerModule(new JodaModule()); + } + + /** + * Serialize the given Java object into JSON string. + */ + public String serialize(Object obj) throws ApiException { + try { + if (obj != null) + return mapper.writeValueAsString(obj); + else + return null; + } catch (Exception e) { + throw new ApiException(400, e.getMessage()); + } + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, TypeRef returnType) throws ApiException { + JavaType javaType = mapper.constructType(returnType.getType()); + try { + return mapper.readValue(body, javaType); + } catch (IOException e) { + if (returnType.getType().equals(String.class)) + return (T) body; + else + throw new ApiException(500, e.getMessage(), null, body); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache b/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache deleted file mode 100644 index 29d5f55eceea..000000000000 --- a/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache +++ /dev/null @@ -1,23 +0,0 @@ -package {{invokerPackage}}; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.core.JsonGenerator.Feature; - -import com.fasterxml.jackson.datatype.joda.*; - -public class JsonUtil { - public static ObjectMapper mapper; - - static { - mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.registerModule(new JodaModule()); - } - - public static ObjectMapper getJsonMapper() { - return mapper; - } -} diff --git a/modules/swagger-codegen/src/main/resources/Java/Pair.mustache b/modules/swagger-codegen/src/main/resources/Java/Pair.mustache index 9805c74903b2..e2a47317afe4 100644 --- a/modules/swagger-codegen/src/main/resources/Java/Pair.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/Pair.mustache @@ -1,5 +1,6 @@ package {{invokerPackage}}; +{{>generatedAnnotation}} public class Pair { private String name = ""; private String value = ""; diff --git a/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache b/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache index 035d6739dce2..073966b0c217 100644 --- a/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache @@ -1,5 +1,6 @@ package {{invokerPackage}}; +{{>generatedAnnotation}} public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/modules/swagger-codegen/src/main/resources/Java/TypeRef.mustache b/modules/swagger-codegen/src/main/resources/Java/TypeRef.mustache new file mode 100644 index 000000000000..9e9ba5f88956 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/TypeRef.mustache @@ -0,0 +1,26 @@ +package {{invokerPackage}}; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +{{>generatedAnnotation}} +public class TypeRef { + private final Type type; + + public TypeRef() { + this.type = getGenericType(getClass()); + } + + private static Type getGenericType(Class klass) { + Type superclass = klass.getGenericSuperclass(); + if (superclass instanceof Class) { + throw new RuntimeException("No type parameter provided"); + } + ParameterizedType parameterized = (ParameterizedType) superclass; + return parameterized.getActualTypeArguments()[0]; + } + + public Type getType() { + return type; + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index c48c0503f5c5..8ffc355072a5 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -4,6 +4,7 @@ import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiClient; import {{invokerPackage}}.Configuration; import {{invokerPackage}}.Pair; +import {{invokerPackage}}.TypeRef; import {{modelPackage}}.*; @@ -12,15 +13,11 @@ import java.util.*; {{#imports}}import {{import}}; {{/imports}} -import com.sun.jersey.multipart.FormDataMultiPart; -import com.sun.jersey.multipart.file.FileDataBodyPart; - -import javax.ws.rs.core.MediaType; - import java.io.File; import java.util.Map; import java.util.HashMap; +{{>generatedAnnotation}} {{#operations}} public class {{classname}} { private ApiClient {{localVariablePrefix}}apiClient; @@ -49,22 +46,22 @@ public class {{classname}} { {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{^isBinary}}{{paramName}}{{/isBinary}}{{#isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + byte[] {{localVariablePrefix}}postBinaryBody = {{#bodyParam}}{{#isBinary}}{{paramName}}{{/isBinary}}{{^isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == null) { - throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"); - } - {{/required}}{{/allParams}} - + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"); + } + {{/required}}{{/allParams}} // create path and map variables - String {{localVariablePrefix}}path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} + String {{localVariablePrefix}}path = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}} .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params List {{localVariablePrefix}}queryParams = new ArrayList(); Map {{localVariablePrefix}}headerParams = new HashMap(); - Map {{localVariablePrefix}}formParams = new HashMap(); + Map {{localVariablePrefix}}formParams = new HashMap(); {{#queryParams}} {{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); @@ -74,6 +71,10 @@ public class {{classname}} { {{localVariablePrefix}}headerParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}})); {{/headerParams}} + {{#formParams}}if ({{paramName}} != null) + {{localVariablePrefix}}formParams.put("{{baseName}}", {{paramName}}); + {{/formParams}} + final String[] {{localVariablePrefix}}accepts = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }; @@ -84,42 +85,27 @@ public class {{classname}} { }; final String {{localVariablePrefix}}contentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}contentTypes); - if({{localVariablePrefix}}contentType.startsWith("multipart/form-data")) { - boolean {{localVariablePrefix}}hasFields = false; - FormDataMultiPart {{localVariablePrefix}}mp = new FormDataMultiPart(); - {{#formParams}}{{#notFile}} - if ({{paramName}} != null) { - {{localVariablePrefix}}hasFields = true; - {{localVariablePrefix}}mp.field("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}), MediaType.MULTIPART_FORM_DATA_TYPE); - } - {{/notFile}}{{#isFile}} - if ({{paramName}} != null) { - {{localVariablePrefix}}hasFields = true; - {{localVariablePrefix}}mp.field("{{baseName}}", {{paramName}}.getName()); - {{localVariablePrefix}}mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE)); - } - {{/isFile}}{{/formParams}} - if({{localVariablePrefix}}hasFields) - {{localVariablePrefix}}postBody = {{localVariablePrefix}}mp; - } - else { - {{#formParams}}{{#notFile}}if ({{paramName}} != null) - {{localVariablePrefix}}formParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/notFile}} - {{/formParams}} - } + String[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + {{#responses}} + {{#isDefault}} - try { - String[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; - String {{localVariablePrefix}}response = {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames); - if({{localVariablePrefix}}response != null){ - return {{#returnType}}({{{returnType}}}) {{localVariablePrefix}}apiClient.deserialize({{localVariablePrefix}}response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}}; - } - else { - return {{#returnType}}null{{/returnType}}; - } - } catch (ApiException ex) { - throw ex; - } + {{#isBinary}} + byte[] {{localVariablePrefix}}response = null; + {{localVariablePrefix}}response = {{localVariablePrefix}}apiClient.invokeBinaryAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams,{{localVariablePrefix}} postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames); + return {{localVariablePrefix}}response; + {{/isBinary}} + + {{^isBinary}} + {{#returnType}} + TypeRef {{localVariablePrefix}}returnType = new TypeRef<{{{returnType}}}>() {}; + return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, {{localVariablePrefix}}returnType); + {{/returnType}}{{^returnType}} + {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, null); + {{/returnType}} + {{/isBinary}} + + {{/isDefault}} + {{/responses}} } {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache index 9afe96c6ffb4..bb3b53b0aeb2 100644 --- a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache @@ -3,6 +3,7 @@ package {{invokerPackage}}; import java.util.Map; import java.util.List; +{{>generatedAnnotation}} public class ApiException extends Exception { private int code = 0; private String message = null; diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache index a1824b551ca9..04be4812292c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache @@ -5,6 +5,7 @@ import {{invokerPackage}}.Pair; import java.util.Map; import java.util.List; +{{>generatedAnnotation}} public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache index 265c74cb76f9..037ef58ab90e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache @@ -5,6 +5,7 @@ import {{invokerPackage}}.Pair; import java.util.Map; import java.util.List; +{{>generatedAnnotation}} public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List queryParams, Map headerParams); diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache index 032ea57d4e89..63813e2504e1 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache @@ -8,6 +8,7 @@ import java.util.List; import java.io.UnsupportedEncodingException; import javax.xml.bind.DatatypeConverter; +{{>generatedAnnotation}} public class HttpBasicAuth implements Authentication { private String username; private String password; diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache index 66cf2ac8f0f8..a1f1b6a827c2 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache @@ -5,6 +5,7 @@ import {{invokerPackage}}.Pair; import java.util.Map; import java.util.List; +{{>generatedAnnotation}} public class OAuth implements Authentication { @Override public void applyToParams(List queryParams, Map headerParams) { diff --git a/modules/swagger-codegen/src/main/resources/Java/enumClass.mustache b/modules/swagger-codegen/src/main/resources/Java/enumClass.mustache new file mode 100644 index 000000000000..68fc07aae7d7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/enumClass.mustache @@ -0,0 +1,14 @@ +public enum {{datatypeWithEnum}} { + {{#allowableValues}}{{#enumVars}}{{name}}("{{value}}"){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + + private String value; + + {{datatypeWithEnum}}(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/Java/generatedAnnotation.mustache new file mode 100644 index 000000000000..49110fc1ad93 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/generatedAnnotation.mustache @@ -0,0 +1 @@ +@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache new file mode 100644 index 000000000000..fb5f6b0d1075 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -0,0 +1,534 @@ +package {{invokerPackage}}; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Form; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.filter.LoggingFilter; +import org.glassfish.jersey.media.multipart.FormDataBodyPart; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Date; +import java.util.TimeZone; + +import java.net.URLEncoder; + +import java.io.IOException; +import java.io.File; +import java.io.UnsupportedEncodingException; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.text.ParseException; + +import {{invokerPackage}}.auth.Authentication; +import {{invokerPackage}}.auth.HttpBasicAuth; +import {{invokerPackage}}.auth.ApiKeyAuth; +import {{invokerPackage}}.auth.OAuth; + +{{>generatedAnnotation}} +public class ApiClient { + private Map hostMap = new HashMap(); + private Map defaultHeaderMap = new HashMap(); + private boolean debugging = false; + private String basePath = "{{basePath}}"; + private JSON json = new JSON(); + + private Map authentications; + + private DateFormat dateFormat; + + public ApiClient() { + // Use ISO 8601 format for date and datetime. + // See https://en.wikipedia.org/wiki/ISO_8601 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + // Set default User-Agent. + setUserAgent("Java-Swagger"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap();{{#authMethods}}{{#isBasic}} + authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} + authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} + authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + return this; + } + + /** + * Get the date format used to parse/format date parameters. + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + */ + public ApiClient getDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + return this; + } + + /** + * Parse the given string into Date object. + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given parameter object into string. + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection)param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /* + Format to {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) return null; + if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) return "application/json"; + if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + */ + public Entity serialize(Object obj, String contentType) throws ApiException { + if (contentType.startsWith("application/json")) { + return Entity.json(json.serialize(obj)); + } else { + throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); + } + } + + /** + * Deserialize response body to Java object according to the Content-Type. + */ + public T deserialize(Response response, TypeRef returnType) throws ApiException { + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = String.valueOf(contentTypes.get(0)); + if (contentType == null) + throw new ApiException(500, "missing Content-Type in response"); + + String body; + if (response.hasEntity()) + body = (String) response.readEntity(String.class); + else + body = ""; + + if (contentType.startsWith("application/json")) { + return json.deserialize(body, returnType); + } else { + throw new ApiException(500, "can not deserialize Content-Type: " + contentType); + } + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @return The response body in type of string + */ + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final ClientConfig clientConfig = new ClientConfig(); + clientConfig.register(MultiPartFeature.class); + if (debugging) { + clientConfig.register(LoggingFilter.class); + } + Client client = ClientBuilder.newClient(clientConfig); + + WebTarget target = client.target(this.basePath).path(path); + + if (queryParams != null) { + for (Pair queryParam : queryParams) { + if (queryParam.getValue() != null) { + target = target.queryParam(queryParam.getName(), queryParam.getValue()); + } + } + } + + Invocation.Builder invocationBuilder = target.request(contentType).accept(accept); + + for (String key : headerParams.keySet()) { + String value = headerParams.get(key); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + + for (String key : defaultHeaderMap.keySet()) { + if (!headerParams.containsKey(key)) { + String value = defaultHeaderMap.get(key); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + } + + Entity formEntity = null; + + if (contentType.startsWith("multipart/form-data")) { + MultiPart multipart = new MultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + + FormDataMultiPart mp = new FormDataMultiPart(); + mp.bodyPart(new FormDataBodyPart(param.getKey(), file.getName())); + multipart.bodyPart(mp, MediaType.MULTIPART_FORM_DATA_TYPE); + + multipart.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + } else { + FormDataMultiPart mp = new FormDataMultiPart(); + mp.bodyPart(new FormDataBodyPart(param.getKey(), parameterToString(param.getValue()))); + multipart.bodyPart(mp, MediaType.MULTIPART_FORM_DATA_TYPE); + } + } + formEntity = Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA_TYPE); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + Form form = new Form(); + for (Entry param: formParams.entrySet()) { + form.param(param.getKey(), parameterToString(param.getValue())); + } + formEntity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); + } + + Response response = null; + + if ("GET".equals(method)) { + response = invocationBuilder.get(); + } else if ("POST".equals(method)) { + if (formEntity != null) { + response = invocationBuilder.post(formEntity); + } else if (body == null) { + response = invocationBuilder.post(null); + } else { + response = invocationBuilder.post(serialize(body, contentType)); + } + } else if ("PUT".equals(method)) { + if (formEntity != null) { + response = invocationBuilder.put(formEntity); + } else if (body == null) { + response = invocationBuilder.put(null); + } else { + response = invocationBuilder.put(serialize(body, contentType)); + } + } else if ("DELETE".equals(method)) { + response = invocationBuilder.delete(); + } else { + throw new ApiException(500, "unknown method type " + method); + } + + if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { + return null; + } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { + if (returnType == null) + return null; + else + return deserialize(response, returnType); + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { + try { + respBody = String.valueOf(response.readEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + Map> responseHeaders = new HashMap>(); + for (String key: response.getHeaders().keySet()) { + List values = response.getHeaders().get(key); + List headers = new ArrayList(); + for (Object o : values) { + headers.add(String.valueOf(o)); + } + responseHeaders.put(key, headers); + } + throw new ApiException( + response.getStatus(), + message, + responseHeaders, + respBody); + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ + private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache new file mode 100644 index 000000000000..e2d0f73d408e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache @@ -0,0 +1,171 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + org.glassfish.jersey.core + jersey-client + ${jersey-version} + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey-version} + + + + + 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} + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 2.6 + 2.4.2 + 2.3 + 1.0.0 + 4.8.1 + + diff --git a/modules/swagger-codegen/src/main/resources/Java/model.mustache b/modules/swagger-codegen/src/main/resources/Java/model.mustache index 0e12f514c488..bfb65a3d4195 100644 --- a/modules/swagger-codegen/src/main/resources/Java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/model.mustache @@ -3,6 +3,9 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} +{{#serializableModel}} +import java.io.Serializable;{{/serializableModel}} + import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; {{#models}} @@ -12,13 +15,14 @@ import com.fasterxml.jackson.annotation.JsonProperty; * {{description}} **/{{/description}} @ApiModel(description = "{{{description}}}") -public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { +{{>generatedAnnotation}} +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { {{#vars}}{{#isEnum}} - public enum {{datatypeWithEnum}} { - {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} - }; - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} - private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} + +{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} + +{{>enumClass}}{{/items}}{{/items.isEnum}} + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} {{#vars}} /**{{#description}} diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index 592edeec0518..315ea9e5b924 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -112,6 +112,8 @@ swagger-annotations ${swagger-annotations-version} + + com.sun.jersey jersey-client @@ -122,6 +124,8 @@ jersey-multipart ${jersey-version} + + com.fasterxml.jackson.core jackson-core @@ -141,7 +145,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda 2.1.5 - + joda-time joda-time diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache index 5f5b5b1df9a4..74e688ee23e0 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache @@ -13,14 +13,22 @@ import {{modelPackage}}.*; {{#imports}}import {{import}}; {{/imports}} +{{>generatedAnnotation}} {{#operations}} public class {{classname}} { + /** + * Uncomment and implement as you see fit. These operations will map + * Direclty to operation calls from the routing logic. Because the inflector + * Code allows you to implement logic incrementally, they are disabled. + **/ {{#operation}} - public ResponseContext {{nickname}}(RequestContext request {{#allParams}},{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{/allParams}}) - { + /* + public ResponseContext {{nickname}}(RequestContext request {{#allParams}}, {{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{/allParams}}) { return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); } + */ + {{/operation}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/generatedAnnotation.mustache new file mode 100644 index 000000000000..49110fc1ad93 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/generatedAnnotation.mustache @@ -0,0 +1 @@ +@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/model.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/model.mustache index 300d5e61dd9d..db2480a85403 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/model.mustache @@ -12,6 +12,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * {{description}} **/{{/description}} @ApiModel(description = "{{{description}}}") +{{>generatedAnnotation}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}}{{#isEnum}} public enum {{datatypeWithEnum}} { diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache index 09477f950523..20d5aaf30c64 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache @@ -74,99 +74,17 @@ - - - com.fasterxml.jackson.core - jackson-core - ${jackson-version} - - - com.fasterxml.jackson.core - jackson-annotations - 2.4.0 - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-version} - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson-version} - - - - org.glassfish.jersey.containers - jersey-container-servlet-core - ${jersey2-version} - - - org.glassfish.jersey.media - jersey-media-multipart - ${jersey2-version} - - - org.glassfish.jersey.core - jersey-client - ${jersey2-version} - - - javax.servlet - servlet-api - ${servlet-api-version} - provided - - - - ch.qos.logback - logback-classic - ${logback-version} - - - ch.qos.logback - logback-core - ${logback-version} - - - org.slf4j - slf4j-ext - ${slf4j-version} - - - org.slf4j - slf4j-api - ${slf4j-version} - - - - - commons-lang - commons-lang - ${commons-lang-version} - - - + io.swagger swagger-inflector 1.0.0-SNAPSHOT - 1.0.0 - 1.5.0 - 1.0.8 - 2.4.2 - 2.2 - 1.2 + 1.5.3 9.2.9.v20150224 - 2.6 - 2.5 - 2.4 - 2.4 - 1.1 1.0.1 4.8.2 1.6.3 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiException.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiException.mustache index ffab3b1088e7..11b4036b8326 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiException.mustache @@ -1,5 +1,6 @@ package {{apiPackage}}; +{{>generatedAnnotation}} public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache index 68675432c648..a1e5a678fe17 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache @@ -5,8 +5,8 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; +{{>generatedAnnotation}} public class ApiOriginFilter implements javax.servlet.Filter { - @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) response; @@ -16,11 +16,7 @@ public class ApiOriginFilter implements javax.servlet.Filter { chain.doFilter(request, response); } - @Override - public void destroy() { - } + public void destroy() {} - @Override - public void init(FilterConfig filterConfig) throws ServletException { - } + public void init(FilterConfig filterConfig) throws ServletException {} } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache index 94711b26efb2..2b9a2b1f8c5b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache @@ -3,6 +3,7 @@ package {{apiPackage}}; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement +{{>generatedAnnotation}} public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/NotFoundException.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/NotFoundException.mustache index 8ab2c99e4f84..1bd5e207d7be 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/NotFoundException.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/NotFoundException.mustache @@ -1,5 +1,6 @@ package {{apiPackage}}; +{{>generatedAnnotation}} public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index 3216b60d5168..a2213ea60860 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -26,6 +26,7 @@ import javax.ws.rs.*; {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} @io.swagger.annotations.Api(value = "/{{baseName}}", description = "the {{baseName}} API") +{{>generatedAnnotation}} {{#operations}} public class {{classname}} { @@ -38,7 +39,7 @@ public class {{classname}} { {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} @io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) @io.swagger.annotations.ApiResponses(value = { {{#responses}} - @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}}, + @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}){{#hasMore}}, {{/hasMore}}{{/responses}} }) public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache index 43e7cd8685ce..a731da6c11cc 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache @@ -18,6 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; +{{>generatedAnnotation}} {{#operations}} public abstract class {{classname}}Service { {{#operation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache index a434311d285a..1bb63bc07751 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache @@ -3,6 +3,7 @@ package {{package}}.factories; import {{package}}.{{classname}}Service; import {{package}}.impl.{{classname}}ServiceImpl; +{{>generatedAnnotation}} public class {{classname}}ServiceFactory { private final static {{classname}}Service service = new {{classname}}ServiceImpl(); diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache index d49fa4952a2c..0acd755745ef 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache @@ -18,6 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; +{{>generatedAnnotation}} {{#operations}} public class {{classname}}ServiceImpl extends {{classname}}Service { {{#operation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache index ba842165f3d3..1bae4717f4dc 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache @@ -1,2 +1,2 @@ -{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "{{{description}}}") @FormDataParam("file") InputStream inputStream, - @ApiParam(value = "file detail") @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @FormDataParam("file") InputStream inputStream, + @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/generatedAnnotation.mustache new file mode 100644 index 000000000000..49110fc1ad93 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/generatedAnnotation.mustache @@ -0,0 +1 @@ +@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache index 300d5e61dd9d..db2480a85403 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache @@ -12,6 +12,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * {{description}} **/{{/description}} @ApiModel(description = "{{{description}}}") +{{>generatedAnnotation}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}}{{#isEnum}} public enum {{datatypeWithEnum}} { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache index 708ca6cac4d0..ba58d23ca7f0 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache @@ -119,13 +119,12 @@ jersey-server ${jersey-version} - - org.scalatest - scalatest_2.9.1 - ${scala-test-version} - test + javax.servlet + servlet-api + ${servlet-api-version} + junit junit @@ -133,9 +132,30 @@ test - javax.servlet - servlet-api - ${servlet-api-version} + com.sun.jersey + jersey-client + ${jersey-version} + test + + + org.testng + testng + 6.8.8 + test + + + junit + junit + + + snakeyaml + org.yaml + + + bsh + org.beanshell + + @@ -148,11 +168,10 @@ - 1.5.0 + 1.5.3 9.2.9.v20150224 - 1.13 + 1.18.1 1.6.3 - 1.6.1 4.8.1 2.5 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/returnTypes.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/returnTypes.mustache new file mode 100644 index 000000000000..c8f7a56938aa --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/returnTypes.mustache @@ -0,0 +1 @@ +{{#returnContainer}}{{#isMapContainer}}Map{{/isMapContainer}}{{#isListContainer}}List<{{{returnType}}}>{{/isListContainer}}{{/returnContainer}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache index d6a24b69311b..695d1c5525b6 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache @@ -30,6 +30,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/{{baseName}}", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/{{baseName}}", description = "the {{baseName}} API") +{{>generatedAnnotation}} {{#operations}} public class {{classname}} { {{#operation}} @@ -41,11 +42,11 @@ public class {{classname}} { {{#hasProduces}}produces = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}} {{#hasConsumes}}consumes = { {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}} method = RequestMethod.{{httpMethod}}) - public ResponseEntity<{{returnType}}> {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + public ResponseEntity<{{>returnTypes}}> {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws NotFoundException { // do some magic! - return new ResponseEntity<{{returnType}}>(HttpStatus.OK); + return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK); } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiException.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiException.mustache index ffab3b1088e7..11b4036b8326 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiException.mustache @@ -1,5 +1,6 @@ package {{apiPackage}}; +{{>generatedAnnotation}} public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiOriginFilter.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiOriginFilter.mustache index 68675432c648..5db3301b3d93 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiOriginFilter.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiOriginFilter.mustache @@ -5,6 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; +{{>generatedAnnotation}} public class ApiOriginFilter implements javax.servlet.Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiResponseMessage.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiResponseMessage.mustache index 94711b26efb2..2b9a2b1f8c5b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiResponseMessage.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiResponseMessage.mustache @@ -3,6 +3,7 @@ package {{apiPackage}}; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement +{{>generatedAnnotation}} public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/generatedAnnotation.mustache new file mode 100644 index 000000000000..49110fc1ad93 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/generatedAnnotation.mustache @@ -0,0 +1 @@ +@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache index 300d5e61dd9d..db2480a85403 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache @@ -12,6 +12,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * {{description}} **/{{/description}} @ApiModel(description = "{{{description}}}") +{{>generatedAnnotation}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}}{{#isEnum}} public enum {{datatypeWithEnum}} { diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/notFoundException.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/notFoundException.mustache index 8ab2c99e4f84..1bd5e207d7be 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/notFoundException.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/notFoundException.mustache @@ -1,5 +1,6 @@ package {{apiPackage}}; +{{>generatedAnnotation}} public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache index 9896c3ac6d83..ffbb0e435161 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache @@ -150,7 +150,7 @@ - 1.5.0 + 1.5.3 9.2.9.v20150224 1.13 1.6.3 diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/returnTypes.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/returnTypes.mustache new file mode 100644 index 000000000000..c8f7a56938aa --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/returnTypes.mustache @@ -0,0 +1 @@ +{{#returnContainer}}{{#isMapContainer}}Map{{/isMapContainer}}{{#isListContainer}}List<{{{returnType}}}>{{/isListContainer}}{{/returnContainer}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerConfig.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerConfig.mustache index b33ee7fc994a..4a6e6879df32 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerConfig.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerConfig.mustache @@ -18,6 +18,7 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2; @EnableSwagger2 //Loads the spring beans required by the framework @PropertySource("classpath:swagger.properties") @Import(SwaggerUiConfiguration.class) +{{>generatedAnnotation}} public class SwaggerConfig { @Bean ApiInfo apiInfo() { diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerUiConfiguration.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerUiConfiguration.mustache index 652dc3103582..0b515fe2cc8c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerUiConfiguration.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerUiConfiguration.mustache @@ -8,6 +8,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration @EnableWebMvc +{{>generatedAnnotation}} public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter { private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" }; diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webApplication.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webApplication.mustache index 6910ad11b765..426f831582eb 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webApplication.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webApplication.mustache @@ -2,6 +2,7 @@ package {{configPackage}}; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; +{{>generatedAnnotation}} public class WebApplication extends AbstractAnnotationConfigDispatcherServletInitializer { @Override diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webMvcConfiguration.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webMvcConfiguration.mustache index 03904e51e794..d60c126316e0 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webMvcConfiguration.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webMvcConfiguration.mustache @@ -3,6 +3,7 @@ package {{configPackage}}; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; +{{>generatedAnnotation}} public class WebMvcConfiguration extends WebMvcConfigurationSupport { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache index eb24f77c0720..b9fd8603baaa 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache @@ -217,7 +217,7 @@ 2.3.9 1.2 2.2 - 1.5.0 + 1.5.3 1.0.0 4.8.1 diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index c93537a740dc..3399d84297da 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -49,6 +49,16 @@ namespace {{packageName}}.Client { get { return _defaultHeaderMap; } } + + /// + /// Gets the status code of the previous request + /// + public int StatusCode { get; private set; } + + /// + /// Gets the response headers of the previous request + /// + public Dictionary ResponseHeaders { get; private set; } // Creates and sets up a RestRequest prior to a call. private RestRequest PrepareRequest( @@ -110,7 +120,10 @@ namespace {{packageName}}.Client { var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - return (Object)RestClient.Execute(request); + var response = RestClient.Execute(request); + StatusCode = (int) response.StatusCode; + ResponseHeaders = response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()); + return (Object) response; } /// @@ -133,7 +146,10 @@ namespace {{packageName}}.Client { var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - return (Object) await RestClient.ExecuteTaskAsync(request); + var response = await RestClient.ExecuteTaskAsync(request); + StatusCode = (int)response.StatusCode; + ResponseHeaders = response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()); + return (Object)response; } /// @@ -154,7 +170,7 @@ namespace {{packageName}}.Client /// Escaped string. public string EscapeString(string str) { - return RestSharp.Contrib.HttpUtility.UrlEncode(str); + return RestSharp.Extensions.StringExtensions.UrlEncode(str); } /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/compile.mustache b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache index ed4481bb4bbe..e35879e0efa1 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/compile.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache @@ -1,3 +1,3 @@ SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319 -%CSCPATH%\csc /reference:bin/Newtonsoft.Json.dll;bin/RestSharp.dll /target:library /out:bin/{{invokerPackage}}.dll /recurse:src\*.cs /doc:bin/{{invokerPackage}}.xml +%CSCPATH%\csc /reference:bin/Newtonsoft.Json.dll;bin/RestSharp.dll /target:library /out:bin/{{packageName}}.dll /recurse:src\*.cs /doc:bin/{{packageName}}.xml diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index ce881084bc2f..584db3b7a855 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -1,52 +1,158 @@ - + + + - - API Reference + {{{appName}}} + +

{{{appName}}}

-
{{{appDescription}}} for {{partner}}
+
{{{appDescription}}}
{{#infoUrl}}
More information: {{{infoUrl}}}
{{/infoUrl}} {{#infoEmail}}
Contact Info: {{{infoEmail}}}
{{/infoEmail}} {{#version}}
Version: {{{version}}}
{{/version}}
{{{licenseInfo}}}
{{{licenseUrl}}}

Access

-
Customize this message as you see fit!
-

Methods

+ {{access}} + +

Methods

+ [ Jump to Models ] + + {{! for the tables of content, I cheat and don't use CSS styles.... }} +

Table of Contents

+
{{access}}
+ {{#apiInfo}} +
    + {{#apis}} + {{#operations}} + {{#operation}} +
  1. {{httpMethod}} {{path}}
  2. + {{/operation}} + {{/operations}} + {{/apis}} +
+ {{/apiInfo}} + {{#apiInfo}} {{#apis}} - {{#operations}}{{#operation}} -
-
{{httpMethod}}: {{path}}
-
{{#tags}}{{this}}{{/tags}}
-
{{nickname}} {{summary}}
+ {{#operations}} + {{#operation}} +
+
+ Up +
{{httpMethod}} {{path}}
+
{{summary}} ({{nickname}})
+ {{! notes is operation.description. So why rename it and make it super confusing???? }}
{{notes}}
-

Parameters

+ {{#hasPathParams}} +

Path parameters

- {{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>headerParam}}{{>formParam}} - {{/allParams}} + {{#pathParams}}{{>pathParam}}{{/pathParams}}
+ {{/hasPathParams}} + + {{#hasConsumes}} +

Consumes

+ This API call consumes the following media types via the Content-Type request header: +
    + {{#consumes}} +
  • {{mediaType}}
  • + {{/consumes}} +
+ {{/hasConsumes}} + + {{#hasBodyParam}} +

Request body

+
+ {{#bodyParams}}{{>bodyParam}}{{/bodyParams}} +
+ {{/hasBodyParam}} + + {{#hasHeaderParam}} +

Request headers

+
+ {{#headerParam}}{{>headerParam}}{{/headerParam}} +
+ {{/hasHeaderParam}} + + {{#hasQueryParams}} +

Query parameters

+
+ {{#queryParams}}{{>queryParam}}{{/queryParams}} +
+ {{/hasQueryParams}} + + + + {{#hasExamples}} + {{#examples}} +

Example data

+
Content-Type: {{{contentType}}}
+
{{{example}}}
+ {{/examples}} + {{/hasExamples}} + + {{#hasProduces}} +

Produces

+ This API call produces the following media types according to the Accept request header; + the media type will be conveyed by the Content-Type response header. +
    + {{#produces}} +
  • {{mediaType}}
  • + {{/produces}} +
+ {{/hasProduces}} + +

Responses

+ {{#responses}} +

{{code}}

+ {{message}} {{#examples}}

Example data

Content-Type: {{{contentType}}}
{{example}}
{{/examples}} + {{/responses}}
-
- {{/operation}}{{/operations}} - {{/apis}}{{/apiInfo}} +
+ {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + + +

Models

+ [ Jump to Methods ] + +

Table of Contents

+
    + {{#models}} + {{#model}} +
  1. {{classname}}
  2. + {{/model}} + {{/models}} +
-

Models

{{#models}} {{#model}}
-

{{classname}}

+

{{classname}} Up

{{#vars}}
{{name}} {{#isNotRequired}}(optional){{/isNotRequired}}
{{datatype}} {{description}}
{{/vars}} @@ -54,8 +160,5 @@
{{/model}} {{/models}} - \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache index 14ab06a7f7e5..d69f0e7b1617 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache @@ -57,6 +57,10 @@ pre { margin-bottom: 2px; } +.http-method { + text-transform: uppercase; +} + pre.get { background-color: #0f6ab4; } @@ -96,6 +100,10 @@ code { background-color: #0f6ab4; } +.up { + float:right; +} + .parameter { width: 500px; } diff --git a/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache b/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache index 59940f08b157..3b975e53b807 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache @@ -14,7 +14,7 @@ {{#operations}} {{#operationsByPath}} "{{{path}}}": { - {{#operation}} + {{#operation}} "{{httpMethod}}": { "summary": "{{summary}}", "description":"{{notes}}", @@ -34,7 +34,6 @@ {{/operation}} } {{#hasMore}},{{/hasMore}} {{/operationsByPath}} - {{#hasMore}},{{/hasMore}} {{/operations}} {{/apis}} {{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index a7d290022f6d..b7643de6ddd6 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -467,6 +467,7 @@ static void (^reachabilityChangeBlock)(int); -(NSNumber*) requestWithCompletionBlock: (NSString*) path method: (NSString*) method + pathParams: (NSDictionary *) pathParams queryParams: (NSDictionary*) queryParams formParams: (NSDictionary *) formParams files: (NSDictionary *) files @@ -499,12 +500,25 @@ static void (^reachabilityChangeBlock)(int); self.responseSerializer = [AFHTTPResponseSerializer serializer]; } + // sanitize parameters + pathParams = [self sanitizeForSerialization:pathParams]; + queryParams = [self sanitizeForSerialization:queryParams]; + headerParams = [self sanitizeForSerialization:headerParams]; + formParams = [self sanitizeForSerialization:formParams]; + body = [self sanitizeForSerialization:body]; + // auth setting [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; + NSMutableString *resourcePath = [NSMutableString stringWithString:path]; + [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", key, @"}"]] + withString:[SWGApiClient escape:obj]]; + }]; + NSMutableURLRequest * request = nil; - NSString* pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; + NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams]; if ([pathWithQueryParams hasPrefix:@"/"]) { pathWithQueryParams = [pathWithQueryParams substringFromIndex:1]; } @@ -540,20 +554,21 @@ static void (^reachabilityChangeBlock)(int); } } + // request cache BOOL hasHeaderParams = false; if(headerParams != nil && [headerParams count] > 0) { hasHeaderParams = true; } if(offlineState) { - NSLog(@"%@ cache forced", path); + NSLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; } else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - NSLog(@"%@ cache enabled", path); + NSLog(@"%@ cache enabled", resourcePath); [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; } else { - NSLog(@"%@ cache disabled", path); + NSLog(@"%@ cache disabled", resourcePath); [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } @@ -671,4 +686,44 @@ static void (^reachabilityChangeBlock)(int); *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } +- (id) sanitizeForSerialization:(id) object { + if (object == nil) { + return nil; + } + else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[SWGQueryParamCollection class]]) { + return object; + } + else if ([object isKindOfClass:[NSDate class]]) { + return [object ISO8601String]; + } + else if ([object isKindOfClass:[NSArray class]]) { + NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[object count]]; + [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + if (obj) { + [sanitizedObjs addObject:[self sanitizeForSerialization:obj]]; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[NSDictionary class]]) { + NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[object count]]; + [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + if (obj) { + [sanitizedObjs setValue:[self sanitizeForSerialization:obj] forKey:key]; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[SWGObject class]]) { + return [object toDictionary]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] + userInfo:nil]; + @throw e; + } +} + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index 46d424d735f0..eba627058795 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -168,6 +168,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; * * @param path Request url. * @param method Request method. + * @param pathParams Request path parameters. * @param queryParams Request query parameters. * @param body Request body. * @param headerParams Request header parameters. @@ -180,6 +181,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ -(NSNumber*) requestWithCompletionBlock:(NSString*) path method:(NSString*) method + pathParams:(NSDictionary *) pathParams queryParams:(NSDictionary*) queryParams formParams:(NSDictionary *) formParams files:(NSDictionary *) files @@ -191,4 +193,11 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; responseType:(NSString *) responseType completionBlock:(void (^)(id, NSError *))completionBlock; +/** + * Sanitize object for request + * + * @param object The query/path/header/form/body param to be sanitized. + */ +- (id) sanitizeForSerialization:(id) object; + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index 198c5a89fdf3..534c887fe7b1 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -88,8 +88,11 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - - {{#pathParams}}[resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"{{baseName}}", @"}"]] withString: [{{classPrefix}}ApiClient escape:{{paramName}}]]; + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + {{#pathParams}}if ({{paramName}} != nil) { + pathParams[@"{{baseName}}"] = {{paramName}}; + } {{/pathParams}} NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -132,26 +135,12 @@ NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; {{#bodyParam}} bodyParam = {{paramName}}; - - if(bodyParam != nil && [bodyParam isKindOfClass:[NSArray class]]){ - NSMutableArray *objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)bodyParam) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[({{classPrefix}}Object*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyParam = objs; - } - else if([bodyParam respondsToSelector:@selector(toDictionary)]) { - bodyParam = [({{classPrefix}}Object*)bodyParam toDictionary]; - } {{/bodyParam}}{{^bodyParam}} {{#formParams}} {{#notFile}} - formParams[@"{{paramName}}"] = {{paramName}}; + if ({{paramName}}) { + formParams[@"{{baseName}}"] = {{paramName}}; + } {{/notFile}}{{#isFile}} files[@"{{paramName}}"] = {{paramName}}; {{/isFile}} @@ -167,6 +156,7 @@ {{/requiredParamCount}} return [self.apiClient requestWithCompletionBlock: resourcePath method: @"{{httpMethod}}" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 1d63440b66fd..45b56aa9b97c 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -191,9 +191,9 @@ class ObjectSerializer $values[] = $this->deserialize($value, $subClass); } $deserialized = $values; - } elseif ($class === 'DateTime') { + } elseif ($class === '\DateTime') { $deserialized = new \DateTime($data); - } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { + } elseif (in_array($class, array({{&primitives}}))) { settype($data, $class); $deserialized = $data; } elseif ($class === '\SplFileObject') { diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 3620e9fb9eee..b076fa5d3ea3 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -34,6 +34,7 @@ class {{classname}}(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. + Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): @@ -42,7 +43,7 @@ class {{classname}}(object): self.api_client = api_client else: if not config.api_client: - config.api_client = ApiClient('{{basePath}}') + config.api_client = ApiClient() self.api_client = config.api_client {{#operation}} @@ -51,7 +52,7 @@ class {{classname}}(object): {{{summary}}} {{{notes}}} - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index ca9a3c051042..1becd5547dd5 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -14,11 +14,13 @@ Copyright 2015 SmartBear Software 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. + + ref: https://github.com/swagger-api/swagger-codegen """ from __future__ import absolute_import from . import models -from .rest import RESTClient +from .rest import RESTClientObject from .rest import ApiException import os @@ -56,7 +58,7 @@ class ApiClient(object): templates. NOTE: This class is auto generated by the swagger code generator program. - https://github.com/swagger-api/swagger-codegen + Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. :param host: The base path for the server to call. @@ -69,13 +71,14 @@ class ApiClient(object): """ Constructor of the class. """ + self.rest_client = RESTClientObject() self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value self.host = host self.cookie = cookie # Set default User-Agent. - self.user_agent = 'Python-Swagger' + self.user_agent = 'Python-Swagger/{{packageVersion}}' @property def user_agent(self): @@ -202,11 +205,9 @@ class ApiClient(object): # and attributes which value is not None. # Convert attribute name to json key in # model definition for request. - obj_dict = {obj.attribute_map[key[1:]]: val - for key, val in iteritems(obj.__dict__) - if key != 'swagger_types' - and key != 'attribute_map' - and val is not None} + obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) + for attr, _ in iteritems(obj.swagger_types) + if getattr(obj, attr) is not None} return {key: self.sanitize_for_serialization(val) for key, val in iteritems(obj_dict)} @@ -282,7 +283,8 @@ class ApiClient(object): body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None): """ - Makes the HTTP request and return the deserialized data. + Makes the HTTP request (synchronous) and return the deserialized data. + To make an async request, define a function for callback. :param resource_path: Path to method endpoint. :param method: Method to call. @@ -329,32 +331,35 @@ class ApiClient(object): Makes the HTTP request using RESTClient. """ if method == "GET": - return RESTClient.GET(url, - query_params=query_params, - headers=headers) + return self.rest_client.GET(url, + query_params=query_params, + headers=headers) elif method == "HEAD": - return RESTClient.HEAD(url, - query_params=query_params, - headers=headers) + return self.rest_client.HEAD(url, + query_params=query_params, + headers=headers) elif method == "POST": - return RESTClient.POST(url, - headers=headers, - post_params=post_params, - body=body) + return self.rest_client.POST(url, + query_params=query_params, + headers=headers, + post_params=post_params, + body=body) elif method == "PUT": - return RESTClient.PUT(url, - headers=headers, - post_params=post_params, - body=body) + return self.rest_client.PUT(url, + query_params=query_params, + headers=headers, + post_params=post_params, + body=body) elif method == "PATCH": - return RESTClient.PATCH(url, - headers=headers, - post_params=post_params, - body=body) + return self.rest_client.PATCH(url, + query_params=query_params, + headers=headers, + post_params=post_params, + body=body) elif method == "DELETE": - return RESTClient.DELETE(url, - query_params=query_params, - headers=headers) + return self.rest_client.DELETE(url, + query_params=query_params, + headers=headers) else: raise ValueError( "http method must be `GET`, `HEAD`," @@ -449,9 +454,8 @@ class ApiClient(object): def __deserialize_file(self, response): """ - Saves response body into a file in (the defined) temporary folder, - using the filename from the `Content-Disposition` header if provided, - otherwise a random filename. + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. :param response: RESTResponse. :return: file path. diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index 62633cdc4a10..07625c67e484 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -14,6 +14,8 @@ Copyright 2015 SmartBear Software 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. + + ref: https://github.com/swagger-api/swagger-codegen """ from __future__ import absolute_import @@ -23,9 +25,9 @@ import urllib3 try: import httplib except ImportError: - # python3 + # for python3 import http.client as httplib - + import sys import logging @@ -44,7 +46,7 @@ def singleton(cls, *args, **kw): class Configuration(object): """ NOTE: This class is auto generated by the swagger code generator program. - https://github.com/swagger-api/swagger-codegen + Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. """ @@ -56,7 +58,7 @@ class Configuration(object): self.host = "{{basePath}}" # Default api client self.api_client = None - # Temp file folder for download + # Temp file folder for downloading files self.temp_folder_path = None # Authentication Settings @@ -77,6 +79,12 @@ class Configuration(object): self.__debug = False self.init_logger() + # SSL/TLS verification + # Set this to false to skip verifying SSL certificate when calling API from https server. + self.verify_ssl = True + # Set this to customize the certificate file to verify the peer. + self.ssl_ca_cert = None + def init_logger(self): """ Initializes logger settings. @@ -139,7 +147,7 @@ class Configuration(object): def get_basic_auth_token(self): """ - Gets basic auth header string. + Gets HTTP basic authentication header (string). :return: The token for basic HTTP authentication. """ diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index c810655e3822..81e0b05849ab 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -14,6 +14,8 @@ Copyright 2015 SmartBear Software 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. + + Ref: https://github.com/swagger-api/swagger-codegen """ {{#models}} @@ -29,7 +31,7 @@ class {{classname}}(object): """ def __init__(self): """ - Swagger model + {{classname}} - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. @@ -82,28 +84,27 @@ class {{classname}}(object): {{/vars}} def to_dict(self): """ - Return model properties dict + Returns the model properties as a dict """ result = {} - for name, prop in iteritems(self.__dict__): - if name == "attribute_map" or name == "swagger_types": - continue - if isinstance(prop, list): - result[name[1:]] = list(map( + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - prop + value )) - elif hasattr(prop, "to_dict"): - result[name[1:]] = prop.to_dict() + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() else: - result[name[1:]] = prop + result[attr] = value return result def to_str(self): """ - Return model properties str + Returns the string representation of the model """ return pformat(self.to_dict()) diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 8a8e55eb3d12..1481cbff3d52 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -18,6 +18,7 @@ Copyright 2015 SmartBear Software Credit: this file (rest.py) is modified based on rest.py in Dropbox Python SDK: https://www.dropbox.com/developers/core/sdks/python """ +from __future__ import absolute_import import sys import io @@ -29,6 +30,8 @@ import logging # python 2 and python 3 compatibility library from six import iteritems +from .configuration import Configuration + try: import urllib3 except ImportError: @@ -69,31 +72,24 @@ class RESTResponse(io.IOBase): class RESTClientObject(object): def __init__(self, pools_size=4): - # http pool manager - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size - ) + if Configuration().verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + if Configuration().ssl_ca_cert: + ca_certs = Configuration().ssl_ca_cert + else: + # if not set certificate file, use Mozilla's root certificates. + ca_certs = certifi.where() # https pool manager - # certificates validated using Mozilla’s root certificates - self.ssl_pool_manager = urllib3.PoolManager( + self.pool_manager = urllib3.PoolManager( num_pools=pools_size, - cert_reqs=ssl.CERT_REQUIRED, - ca_certs=certifi.where() + cert_reqs=cert_reqs, + ca_certs=ca_certs ) - def agent(self, url): - """ - Use `urllib3.util.parse_url` for backward compatibility. - Return proper pool manager for the http/https schemes. - """ - url = urllib3.util.parse_url(url) - scheme = url.scheme - if scheme == 'https': - return self.ssl_pool_manager - else: - return self.pool_manager - def request(self, method, url, query_params=None, headers=None, body=None, post_params=None): """ @@ -120,32 +116,37 @@ class RESTClientObject(object): if 'Content-Type' not in headers: headers['Content-Type'] = 'application/json' - # For `POST`, `PUT`, `PATCH` - if method in ['POST', 'PUT', 'PATCH']: - if query_params: - url += '?' + urlencode(query_params) - if headers['Content-Type'] == 'application/json': - r = self.agent(url).request(method, url, - body=json.dumps(body), - headers=headers) - if headers['Content-Type'] == 'application/x-www-form-urlencoded': - r = self.agent(url).request(method, url, - fields=post_params, - encode_multipart=False, - headers=headers) - if headers['Content-Type'] == 'multipart/form-data': - # must del headers['Content-Type'], or the correct Content-Type - # which generated by urllib3 will be overwritten. - del headers['Content-Type'] - r = self.agent(url).request(method, url, - fields=post_params, - encode_multipart=True, - headers=headers) - # For `GET`, `HEAD`, `DELETE` - else: - r = self.agent(url).request(method, url, - fields=query_params, - headers=headers) + try: + # For `POST`, `PUT`, `PATCH` + if method in ['POST', 'PUT', 'PATCH']: + if query_params: + url += '?' + urlencode(query_params) + if headers['Content-Type'] == 'application/json': + r = self.pool_manager.request(method, url, + body=json.dumps(body), + headers=headers) + if headers['Content-Type'] == 'application/x-www-form-urlencoded': + r = self.pool_manager.request(method, url, + fields=post_params, + encode_multipart=False, + headers=headers) + if headers['Content-Type'] == 'multipart/form-data': + # must del headers['Content-Type'], or the correct Content-Type + # which generated by urllib3 will be overwritten. + del headers['Content-Type'] + r = self.pool_manager.request(method, url, + fields=post_params, + encode_multipart=True, + headers=headers) + # For `GET`, `HEAD`, `DELETE` + else: + r = self.pool_manager.request(method, url, + fields=query_params, + headers=headers) + except urllib3.exceptions.SSLError as e: + msg = "{0}\n{1}".format(type(e).__name__, str(e)) + raise ApiException(status=0, reason=msg) + r = RESTResponse(r) # In the python 3, the response.data is bytes. @@ -176,21 +177,24 @@ class RESTClientObject(object): headers=headers, query_params=query_params) - def POST(self, url, headers=None, post_params=None, body=None): + def POST(self, url, headers=None, query_params=None, post_params=None, body=None): return self.request("POST", url, headers=headers, + query_params=query_params, post_params=post_params, body=body) - def PUT(self, url, headers=None, post_params=None, body=None): + def PUT(self, url, headers=None, query_params=None, post_params=None, body=None): return self.request("PUT", url, headers=headers, + query_params=query_params, post_params=post_params, body=body) - def PATCH(self, url, headers=None, post_params=None, body=None): + def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None): return self.request("PATCH", url, headers=headers, + query_params=query_params, post_params=post_params, body=body) @@ -224,58 +228,20 @@ class ApiException(Exception): return error_message -class RESTClient(object): - """ - A class with all class methods to perform JSON requests. - """ - IMPL = RESTClientObject() - @classmethod - def request(cls, *n, **kw): - """ - Perform a REST request and parse the response. - """ - return cls.IMPL.request(*n, **kw) - @classmethod - def GET(cls, *n, **kw): - """ - Perform a GET request using `RESTClient.request()`. - """ - return cls.IMPL.GET(*n, **kw) - @classmethod - def HEAD(cls, *n, **kw): - """ - Perform a HEAD request using `RESTClient.request()`. - """ - return cls.IMPL.GET(*n, **kw) - @classmethod - def POST(cls, *n, **kw): - """ - Perform a POST request using `RESTClient.request()` - """ - return cls.IMPL.POST(*n, **kw) - @classmethod - def PUT(cls, *n, **kw): - """ - Perform a PUT request using `RESTClient.request()` - """ - return cls.IMPL.PUT(*n, **kw) - @classmethod - def PATCH(cls, *n, **kw): - """ - Perform a PATCH request using `RESTClient.request()` - """ - return cls.IMPL.PATCH(*n, **kw) - @classmethod - def DELETE(cls, *n, **kw): - """ - Perform a DELETE request using `RESTClient.request()` - """ - return cls.IMPL.DELETE(*n, **kw) + + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/python/setup.mustache b/modules/swagger-codegen/src/main/resources/python/setup.mustache index a939ce019587..08e110e35cce 100644 --- a/modules/swagger-codegen/src/main/resources/python/setup.mustache +++ b/modules/swagger-codegen/src/main/resources/python/setup.mustache @@ -8,13 +8,11 @@ VERSION = "{{packageVersion}}" {{#apiInfo}}{{#apis}}{{^hasMore}} -# To install the library, open a Terminal shell, then run this -# file by typing: +# To install the library, run the following # # python setup.py install # -# You need to have the setuptools module installed. -# Try reading the setuptools documentation: +# prerequisite: setuptools # http://pypi.python.org/pypi/setuptools REQUIRES = ["urllib3 >= 1.10", "six >= 1.9", "certifi", "python-dateutil"] diff --git a/modules/swagger-codegen/src/main/resources/scala/pom.mustache b/modules/swagger-codegen/src/main/resources/scala/pom.mustache index c6fe4a1f3561..5fc849ea87df 100644 --- a/modules/swagger-codegen/src/main/resources/scala/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/pom.mustache @@ -210,7 +210,7 @@ 1.2 2.2 1.19 - 1.5.0 + 1.5.3 1.0.5 1.0.0 2.4.2 diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenConfigLoaderTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenConfigLoaderTest.java new file mode 100644 index 000000000000..b91e506a4f96 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenConfigLoaderTest.java @@ -0,0 +1,57 @@ +package io.swagger.codegen; + +import org.reflections.Reflections; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import static org.testng.Assert.assertEquals; + +public class CodegenConfigLoaderTest { + + @DataProvider(name = "codegenConfig") + public Object[][] createCodegenConfigDataSet() throws Exception { + + Reflections reflections = new Reflections("io.swagger.codegen.languages"); + final Set> subTypesOf = reflections.getSubTypesOf(DefaultCodegen.class); + + List codegenConfigList = new ArrayList(); + + for (Class aClass : subTypesOf) { + if (!Modifier.isAbstract(aClass.getModifiers())) { + final DefaultCodegen defaultCodegen = aClass.newInstance(); + codegenConfigList.add((CodegenConfig) defaultCodegen); + } + } + + Object[][] result = new Object[codegenConfigList.size()][1]; + + for (int i = 0; i < codegenConfigList.size(); i++) { + result[i]= new Object[]{codegenConfigList.get(i)}; + } + + return result; + } + + @Test(dataProvider = "codegenConfig") + public void testLoadByName(CodegenConfig codegenConfig) throws Exception { + final CodegenConfig loadedConfig = CodegenConfigLoader.forName(codegenConfig.getName()); + + assertEquals(loadedConfig.getClass(), codegenConfig.getClass()); + assertEquals(loadedConfig.getName(), codegenConfig.getName()); + } + + @Test(dataProvider = "codegenConfig") + public void testLoadByFullQualifiedName(CodegenConfig codegenConfig) throws Exception { + final CodegenConfig loadedConfig = CodegenConfigLoader.forName(codegenConfig.getClass().getName()); + + assertEquals(loadedConfig.getClass(), codegenConfig.getClass()); + assertEquals(loadedConfig.getName(), codegenConfig.getName()); + + + } +} diff --git a/modules/swagger-codegen-cli/src/test/java/io.swagger.codegen/GenerateTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java similarity index 51% rename from modules/swagger-codegen-cli/src/test/java/io.swagger.codegen/GenerateTest.java rename to modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java index bd2a342e3e20..5da6a01763c5 100644 --- a/modules/swagger-codegen-cli/src/test/java/io.swagger.codegen/GenerateTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java @@ -1,15 +1,13 @@ package io.swagger.codegen; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import io.swagger.codegen.languages.JavaClientCodegen; +import io.swagger.models.Swagger; +import io.swagger.parser.SwaggerParser; import org.apache.commons.io.FileUtils; -import org.junit.Rule; -import org.junit.Test; import org.junit.rules.TemporaryFolder; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.fail; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; import java.io.BufferedWriter; import java.io.File; @@ -20,34 +18,53 @@ import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.Arrays; -public class GenerateTest { +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.fail; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; + +/** + * Tests for DefaultGenerator logic + */ +public class DefaultGeneratorTest { private static final String TEST_SKIP_OVERWRITE = "testSkipOverwrite"; private static final String POM_FILE = "pom.xml"; private static final String MODEL_ORDER_FILE = "/src/main/java/io/swagger/client/model/Order.java"; - @Rule public TemporaryFolder folder = new TemporaryFolder(); + @BeforeMethod + public void setUp() throws Exception { + folder.create(); + } + + @AfterMethod + public void tearDown() throws Exception { + folder.delete(); + } + @Test - public void testSkipOverwrite() throws IOException { + public void testSkipOverwrite() throws Exception { final File output = folder.getRoot(); - String[] args = {"generate", "-i", "src/test/resources/petstore.json", "-l", "java", "-o", output.getAbsolutePath()}; - String[] argsWithSparam = Arrays.copyOf(args, args.length + 1); - argsWithSparam[args.length] = "-s"; + final Swagger swagger = new SwaggerParser().read("src/test/resources/petstore.json"); + CodegenConfig codegenConfig = new JavaClientCodegen(); + codegenConfig.setOutputDir(output.getAbsolutePath()); - //generate content first time without -s flag, so all generated files should be recorded - SwaggerCodegen.main(args); + ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); + + //generate content first time without skipOverwrite flag, so all generated files should be recorded + new DefaultGenerator().opts(clientOptInput).generate(); final File order = new File(output, MODEL_ORDER_FILE); assertTrue(order.exists()); //change content of one file changeContent(order); - //generate content second time without -s flag, so changed file should be rewritten - SwaggerCodegen.main(args); - //order = new File(output, MODEL_ORDER_FILE); + //generate content second time without skipOverwrite flag, so changed file should be rewritten + new DefaultGenerator().opts(clientOptInput).generate(); + assertTrue(!TEST_SKIP_OVERWRITE.equals(FileUtils.readFileToString(order, StandardCharsets.UTF_8))); //change content again @@ -58,9 +75,10 @@ public class GenerateTest { fail(); } - //generate content third time with -s flag, so changed file should not be rewritten + //generate content third time with skipOverwrite flag, so changed file should not be rewritten //and deleted file should be recorded - SwaggerCodegen.main(argsWithSparam); + codegenConfig.setSkipOverwrite(true); + new DefaultGenerator().opts(clientOptInput).generate(); assertEquals(FileUtils.readFileToString(order, StandardCharsets.UTF_8), TEST_SKIP_OVERWRITE); assertTrue(pom.exists()); } @@ -70,4 +88,5 @@ public class GenerateTest { out.write(TEST_SKIP_OVERWRITE); out.close(); } + } diff --git a/modules/swagger-codegen/src/test/resources/2_0/binaryDataTest.json b/modules/swagger-codegen/src/test/resources/2_0/binaryDataTest.json new file mode 100644 index 000000000000..5ae05f9ae83f --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/binaryDataTest.json @@ -0,0 +1,51 @@ +{ + "swagger": "2.0", + "info": { + "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. 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://helloreverb.com/terms/", + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "basePath": "/v2", + "schemes": [ + "http" + ], + "paths": { + "/tests/binaryResponse": { + "post": { + "summary": "Echo test", + "operationId": "echotest", + "consumes": [ + "application/octet-stream" + ], + "produces": [ + "application/octet-stream" + ], + "parameters": [ + { + "name": "InputBinaryData", + "in": "body", + "required": true, + "schema": { + "type": "string", + "format": "binary" + } + } + ], + "responses": { + "200": { + "description": "OutputBinaryData", + "schema": { + "type": "string", + "format": "binary" + } + } + } + } + } + } +} diff --git a/modules/swagger-codegen-cli/src/test/resources/petstore.json b/modules/swagger-codegen/src/test/resources/petstore.json similarity index 100% rename from modules/swagger-codegen-cli/src/test/resources/petstore.json rename to modules/swagger-codegen/src/test/resources/petstore.json diff --git a/modules/swagger-codegen/src/test/scala/CodegenTest.scala b/modules/swagger-codegen/src/test/scala/CodegenTest.scala index 0e76f5088dff..015932948de6 100644 --- a/modules/swagger-codegen/src/test/scala/CodegenTest.scala +++ b/modules/swagger-codegen/src/test/scala/CodegenTest.scala @@ -139,4 +139,19 @@ class CodegenTest extends FlatSpec with Matchers { val op = codegen.fromOperation(path, "get", p, model.getDefinitions()) op.returnType should be("String") } + + it should "return byte array when response format is byte" in { + val model = new SwaggerParser() + .read("src/test/resources/2_0/binaryDataTest.json") + System.err.println("model is " + model); + val codegen = new DefaultCodegen() + + val path = "/tests/binaryResponse" + val p = model.getPaths().get(path).getPost() + val op = codegen.fromOperation(path, "post", p, model.getDefinitions()) + op.returnType should be("byte[]") + op.bodyParam.dataType should be ("byte[]") + op.bodyParam.isBinary should equal (true); + op.responses.get(0).isBinary should equal(true); + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala b/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala index e5191e1ae238..30a70ca6dfbc 100644 --- a/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala +++ b/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala @@ -31,4 +31,55 @@ class JavaModelEnumTest extends FlatSpec with Matchers { enumVar.baseType should be("String") enumVar.isEnum should equal(true) } + + it should "not override identical parent enums" in { + + val identicalEnumProperty = new StringProperty() + identicalEnumProperty.setEnum(List("VALUE1", "VALUE2", "VALUE3").asJava) + + val subEnumProperty = new StringProperty() + subEnumProperty.setEnum(List("SUB1", "SUB2", "SUB3").asJava) + + // Add one enum ptoperty to the parent + val parentProperties = new java.util.HashMap[String, Property]() + parentProperties.put("sharedThing", identicalEnumProperty) + + // Add TWO enums to the subType model; one of which is identical to the one in parent class + val subProperties = new java.util.HashMap[String, Property]() + subProperties.put("sharedThing", identicalEnumProperty) + subProperties.put("unsharedThing", identicalEnumProperty) + + val parentModel = new ModelImpl(); + parentModel.setProperties(parentProperties); + parentModel.name("parentModel"); + + val subModel = new ModelImpl(); + subModel.setProperties(subProperties); + subModel.name("subModel"); + + val model = new ComposedModel() + .parent(new RefModel(parentModel.getName())) + .child(subModel) + .interfaces(new java.util.ArrayList[RefModel]()) + + val codegen = new JavaClientCodegen() + val allModels = new java.util.HashMap[String, Model]() + allModels.put(codegen.toModelName(parentModel.getName()), parentModel) + allModels.put(codegen.toModelName(subModel.getName()), subModel) + + val cm = codegen.fromModel("sample", model, allModels) + + cm.name should be("sample") + cm.classname should be("Sample") + cm.parent should be("ParentModel") + cm.imports.asScala should be(Set("ParentModel")) + + // Assert that only the unshared/uninherited enum remains + cm.vars.size should be (1) + val enumVar = cm.vars.get(0) + enumVar.baseName should be("unsharedThing") + enumVar.datatype should be("String") + enumVar.datatypeWithEnum should be("UnsharedThingEnum") + enumVar.isEnum should equal(true) + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala b/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala index 81e252aa117a..1d044fbfdbec 100644 --- a/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala @@ -2,6 +2,7 @@ package Java import io.swagger.codegen.languages.JavaClientCodegen import io.swagger.models._ +import io.swagger.models.parameters._ import io.swagger.models.properties._ import io.swagger.util.Json import org.junit.runner.RunWith @@ -354,6 +355,20 @@ class JavaModelTest extends FlatSpec with Matchers { vars.get(0).name should be("createdAt") } + it should "convert query[password] to queryPassword" in { + val model = new ModelImpl() + .description("a sample model") + .property("query[password]", new StringProperty()) + + val codegen = new JavaClientCodegen() + val cm = codegen.fromModel("sample", model) + val vars = cm.vars + vars.get(0).baseName should be("query[password]") + vars.get(0).getter should be("getQueryPassword") + vars.get(0).setter should be("setQueryPassword") + vars.get(0).name should be("queryPassword") + } + it should "properly escape names per 567" in { val model = new ModelImpl() .description("a sample model") @@ -364,6 +379,28 @@ class JavaModelTest extends FlatSpec with Matchers { val vars = cm.vars cm.classname should be("WithDots") } + + it should "convert a modelwith binary data" in { + val model = new ModelImpl() + .description("model with binary") + .property("inputBinaryData", new ByteArrayProperty()); + + val codegen = new JavaClientCodegen() + val cm = codegen.fromModel("sample", model) + val vars = cm.vars + + vars.get(0).baseName should be ("inputBinaryData") + vars.get(0).getter should be ("getInputBinaryData") + vars.get(0).setter should be ("setInputBinaryData") + vars.get(0).datatype should be ("byte[]") + vars.get(0).name should be ("inputBinaryData") + vars.get(0).defaultValue should be ("null") + vars.get(0).baseType should be ("byte[]") + vars.get(0).hasMore should equal (null) + vars.get(0).required should equal (null) + vars.get(0).isNotContainer should equal (true) + + } } @@ -382,7 +419,6 @@ class JavaModelTest2 extends FlatSpec with Matchers { cm.vars.size should be(1) val vars = cm.vars - Json.prettyPrint(vars.get(0)) vars.get(0).baseName should be("_") vars.get(0).getter should be("getU") vars.get(0).setter should be("setU") @@ -393,4 +429,17 @@ class JavaModelTest2 extends FlatSpec with Matchers { vars.get(0).hasMore should equal(null) vars.get(0).isNotContainer should equal(true) } + + it should "convert a parameter" in { + val parameter = new QueryParameter() + .property( + new IntegerProperty()) + .name("limit") + .required(true) + + val codegen = new JavaClientCodegen() + val cp = codegen.fromParameter(parameter, null) + + cp.allowableValues should be (null) + } } diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index 69e7802c487f..dbb092e98163 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -4,7 +4,7 @@ io.swagger swagger-codegen-project - 2.1.3-SNAPSHOT + 2.1.4-SNAPSHOT ../.. swagger-generator diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java index f6d924c00ad5..0e71119e67a1 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java @@ -1,12 +1,12 @@ /** * Copyright 2015 SmartBear Software - *

+ *

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

+ *

* 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java index ac28d1cc5f43..50019486ec38 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java @@ -1,12 +1,12 @@ /** * Copyright 2015 SmartBear Software - *

+ *

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

+ *

* 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java index 7a15e82073a7..b90c6ee319d6 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java @@ -1,12 +1,12 @@ /** * Copyright 2015 SmartBear Software - *

+ *

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

+ *

* 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java index dbd6a1463ee6..339cac259c1f 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java @@ -1,12 +1,12 @@ /** * Copyright 2015 SmartBear Software - *

+ *

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

+ *

* 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java index 0f3ce2e8cc99..8fe9d41fb7ec 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java @@ -1,12 +1,12 @@ /** * Copyright 2015 SmartBear Software - *

+ *

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

+ *

* 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java index 501cd2ddd826..614adcc61bc7 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java @@ -1,12 +1,12 @@ /** * Copyright 2015 SmartBear Software - *

+ *

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

+ *

* 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java index dc55ad00582d..45b3b7b7bbff 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java @@ -1,12 +1,12 @@ /** * Copyright 2015 SmartBear Software - *

+ *

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

+ *

* 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java index 6daf764a45db..07ee795f5884 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java @@ -1,12 +1,12 @@ /** * Copyright 2015 SmartBear Software - *

+ *

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

+ *

* 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java index 11e63d5cbcb5..ca0a0e620182 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java @@ -1,12 +1,12 @@ /** * Copyright 2015 SmartBear Software - *

+ *

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

+ *

* 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. diff --git a/pom.xml b/pom.xml index ca4a2219ba7a..4f0d717140aa 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ swagger-codegen-project pom swagger-codegen-project - 2.1.3-SNAPSHOT + 2.1.4-SNAPSHOT https://github.com/swagger-api/swagger-codegen scm:git:git@github.com:swagger-api/swagger-codegen.git @@ -68,6 +68,27 @@ target ${project.artifactId}-${project.version} + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire-version} + + none:none + + + + test-testng + test + + test + + + none:none + org.testng:testng + + + + maven-dependency-plugin @@ -292,7 +313,19 @@ - samples/client/petstore/java + samples/client/petstore/java/default + + + + java-client-jersey2 + + + env + java + + + + samples/client/petstore/java/jersey2 @@ -377,12 +410,13 @@ samples/client/petstore/android-java - samples/client/petstore/java + samples/client/petstore/java/default + samples/client/petstore/java/jersey2 samples/client/petstore/scala - samples/server/petstore/jaxrs samples/server/petstore/spring-mvc samples/client/petstore/ruby + samples/server/petstore/jaxrs @@ -444,6 +478,18 @@ ${junit-version} test + + org.testng + testng + ${testng-version} + test + + + org.jmockit + jmockit + ${jmockit-version} + test + @@ -459,7 +505,7 @@ 1.0.10 2.11.1 2.3.4 - 1.5.4-SNAPSHOT + 1.5.3 2.1.4 2.3 1.2 @@ -469,5 +515,9 @@ 1.6.3 3.2.1 1.9 + 6.9.6 + 2.18.1 + 1.19 + 0.9.10 diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile.bat b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile.bat index bb6ae8097eac..909633566901 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile.bat +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile.bat @@ -1,3 +1,3 @@ SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319 -%CSCPATH%\csc /reference:bin/Newtonsoft.Json.dll;bin/RestSharp.dll /target:library /out:bin/.dll /recurse:src\*.cs /doc:bin/.xml +%CSCPATH%\csc /reference:bin/Newtonsoft.Json.dll;bin/RestSharp.dll /target:library /out:bin/IO.Swagger.dll /recurse:src\*.cs /doc:bin/IO.Swagger.xml diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs index 9041bbf42f09..4d87e7bd9c6e 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs @@ -49,6 +49,16 @@ namespace IO.Swagger.Client { get { return _defaultHeaderMap; } } + + ///

+ /// Gets the status code of the previous request + /// + public int StatusCode { get; private set; } + + /// + /// Gets the response headers of the previous request + /// + public Dictionary ResponseHeaders { get; private set; } // Creates and sets up a RestRequest prior to a call. private RestRequest PrepareRequest( @@ -110,7 +120,10 @@ namespace IO.Swagger.Client { var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - return (Object)RestClient.Execute(request); + var response = RestClient.Execute(request); + StatusCode = (int) response.StatusCode; + ResponseHeaders = response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()); + return (Object) response; } /// @@ -133,7 +146,10 @@ namespace IO.Swagger.Client { var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - return (Object) await RestClient.ExecuteTaskAsync(request); + var response = await RestClient.ExecuteTaskAsync(request); + StatusCode = (int)response.StatusCode; + ResponseHeaders = response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()); + return (Object)response; } /// @@ -154,7 +170,7 @@ namespace IO.Swagger.Client /// Escaped string. public string EscapeString(string str) { - return RestSharp.Contrib.HttpUtility.UrlEncode(str); + return RestSharp.Extensions.StringExtensions.UrlDecode(str); } /// diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj index 670402c0cd2f..982ecc7a3158 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj @@ -32,15 +32,15 @@ Lib\SwaggerClient\bin\Newtonsoft.Json.dll - - Lib\SwaggerClient\bin\RestSharp.dll - packages\NUnit.2.6.4\lib\nunit.framework.dll + + Lib\SwaggerClient\bin\RestSharp.dll + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll index 0fa7c24ab8af..8f38016c832b 100755 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb index 1830197d9e77..290bbd5f2e08 100644 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll index 0fa7c24ab8af..8f38016c832b 100755 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll and b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb index 1830197d9e77..290bbd5f2e08 100644 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb and b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb differ diff --git a/samples/client/petstore/java/default/hello.txt b/samples/client/petstore/java/default/hello.txt new file mode 100644 index 000000000000..6769dd60bdf5 --- /dev/null +++ b/samples/client/petstore/java/default/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/pom.xml b/samples/client/petstore/java/default/pom.xml similarity index 98% rename from samples/client/petstore/java/pom.xml rename to samples/client/petstore/java/default/pom.xml index 058733e08fcd..3cef1c564c91 100644 --- a/samples/client/petstore/java/pom.xml +++ b/samples/client/petstore/java/default/pom.xml @@ -112,6 +112,8 @@ swagger-annotations ${swagger-annotations-version} + + com.sun.jersey jersey-client @@ -122,6 +124,8 @@ jersey-multipart ${jersey-version} + + com.fasterxml.jackson.core jackson-core @@ -141,7 +145,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda 2.1.5 - + joda-time joda-time diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java similarity index 76% rename from samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java index 87ecc8312514..bc2dab2e8a8d 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java @@ -1,17 +1,14 @@ package io.swagger.client; -import com.fasterxml.jackson.core.JsonGenerator.Feature; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.api.client.WebResource.Builder; + import com.sun.jersey.multipart.FormDataMultiPart; +import com.sun.jersey.multipart.file.FileDataBodyPart; import javax.ws.rs.core.Response.Status.Family; import javax.ws.rs.core.MediaType; @@ -29,6 +26,7 @@ import java.util.TimeZone; import java.net.URLEncoder; import java.io.IOException; +import java.io.File; import java.io.UnsupportedEncodingException; import java.text.DateFormat; @@ -40,11 +38,13 @@ import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); private boolean debugging = false; private String basePath = "http://petstore.swagger.io/v2"; + private JSON json = new JSON(); private Map authentications; @@ -336,50 +336,38 @@ public class ApiClient { } /** - * Deserialize the given JSON string to Java object. - * - * @param json The JSON string - * @param containerType The container type, one of "list", "array" or "" - * @param cls The type of the Java object - * @return The deserialized Java object + * Serialize the given Java object into string according the given + * Content-Type (only JSON is supported for now). */ - public Object deserialize(String json, String containerType, Class cls) throws ApiException { - if(null != containerType) { - containerType = containerType.toLowerCase(); - } - try{ - if("list".equals(containerType) || "array".equals(containerType)) { - JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls); - List response = (List) JsonUtil.getJsonMapper().readValue(json, typeInfo); - return response; - } - else if(String.class.equals(cls)) { - if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) - return json.substring(1, json.length() - 2); - else - return json; - } - else { - return JsonUtil.getJsonMapper().readValue(json, cls); - } - } - catch (IOException e) { - throw new ApiException(500, e.getMessage(), null, json); + public String serialize(Object obj, String contentType) throws ApiException { + if (contentType.startsWith("application/json")) { + return json.serialize(obj); + } else { + throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); } } /** - * Serialize the given Java object into JSON string. + * Deserialize response body to Java object according to the Content-Type. */ - public String serialize(Object obj) throws ApiException { - try { - if (obj != null) - return JsonUtil.getJsonMapper().writeValueAsString(obj); - else - return null; - } - catch (Exception e) { - throw new ApiException(500, e.getMessage()); + public T deserialize(ClientResponse response, TypeRef returnType) throws ApiException { + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = contentTypes.get(0); + if (contentType == null) + throw new ApiException(500, "missing Content-Type in response"); + + String body; + if (response.hasEntity()) + body = (String) response.getEntity(String.class); + else + body = ""; + + if (contentType.startsWith("application/json")) { + return json.deserialize(body, returnType); + } else { + throw new ApiException(500, "can not deserialize Content-Type: " + contentType); } } @@ -395,9 +383,10 @@ public class ApiClient { * @param accept The request's Accept header * @param contentType The request's Content-Type header * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response * @return The response body in type of string */ - public String invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); Client client = getClient(); @@ -423,90 +412,89 @@ public class ApiClient { else builder = client.resource(basePath + path + querystring).accept(accept); - for(String key : headerParams.keySet()) { + for (String key : headerParams.keySet()) { builder = builder.header(key, headerParams.get(key)); } - for(String key : defaultHeaderMap.keySet()) { - if(!headerParams.containsKey(key)) { + for (String key : defaultHeaderMap.keySet()) { + if (!headerParams.containsKey(key)) { builder = builder.header(key, defaultHeaderMap.get(key)); } } + String encodedFormParams = null; + if (contentType.startsWith("multipart/form-data")) { + FormDataMultiPart mp = new FormDataMultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + mp.field(param.getKey(), file.getName()); + mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE)); + } else { + mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); + } + } + body = mp; + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + encodedFormParams = this.getXWWWFormUrlencodedParams(formParams); + } + ClientResponse response = null; - if("GET".equals(method)) { + if ("GET".equals(method)) { response = (ClientResponse) builder.get(ClientResponse.class); - } - else if ("POST".equals(method)) { - if (contentType.startsWith("application/x-www-form-urlencoded")) { - String encodedFormParams = this - .getXWWWFormUrlencodedParams(formParams); - response = builder.type(contentType).post(ClientResponse.class, - encodedFormParams); + } else if ("POST".equals(method)) { + if (encodedFormParams != null) { + response = builder.type(contentType).post(ClientResponse.class, encodedFormParams); } else if (body == null) { response = builder.post(ClientResponse.class, null); - } else if(body instanceof FormDataMultiPart) { + } else if (body instanceof FormDataMultiPart) { response = builder.type(contentType).post(ClientResponse.class, body); - } - else - response = builder.type(contentType).post(ClientResponse.class, serialize(body)); - } - else if ("PUT".equals(method)) { - if ("application/x-www-form-urlencoded".equals(contentType)) { - String encodedFormParams = this - .getXWWWFormUrlencodedParams(formParams); - response = builder.type(contentType).put(ClientResponse.class, - encodedFormParams); - } else if(body == null) { - response = builder.put(ClientResponse.class, serialize(body)); } else { - response = builder.type(contentType).put(ClientResponse.class, serialize(body)); + response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType)); } - } - else if ("DELETE".equals(method)) { - if ("application/x-www-form-urlencoded".equals(contentType)) { - String encodedFormParams = this - .getXWWWFormUrlencodedParams(formParams); - response = builder.type(contentType).delete(ClientResponse.class, - encodedFormParams); + } else if ("PUT".equals(method)) { + if (encodedFormParams != null) { + response = builder.type(contentType).put(ClientResponse.class, encodedFormParams); + } else if(body == null) { + response = builder.put(ClientResponse.class, serialize(body, contentType)); + } else { + response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType)); + } + } else if ("DELETE".equals(method)) { + if (encodedFormParams != null) { + response = builder.type(contentType).delete(ClientResponse.class, encodedFormParams); } else if(body == null) { response = builder.delete(ClientResponse.class); } else { - response = builder.type(contentType).delete(ClientResponse.class, serialize(body)); + response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType)); } - } - else { + } else { throw new ApiException(500, "unknown method type " + method); } - if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { + if (response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { return null; - } - else if(response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { - if(response.hasEntity()) { - return (String) response.getEntity(String.class); - } - else { - return ""; - } - } - else { + } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { + if (returnType == null) + return null; + else + return deserialize(response, returnType); + } else { String message = "error"; String respBody = null; - if(response.hasEntity()) { - try{ + if (response.hasEntity()) { + try { respBody = String.valueOf(response.getEntity(String.class)); message = respBody; - } - catch (RuntimeException e) { + } catch (RuntimeException e) { // e.printStackTrace(); } } throw new ApiException( - response.getStatusInfo().getStatusCode(), - message, - response.getHeaders(), - respBody); + response.getStatusInfo().getStatusCode(), + message, + response.getHeaders(), + respBody); } } @@ -526,15 +514,14 @@ public class ApiClient { /** * Encode the given form parameters as request body. */ - private String getXWWWFormUrlencodedParams(Map formParams) { + private String getXWWWFormUrlencodedParams(Map formParams) { StringBuilder formParamBuilder = new StringBuilder(); - for (Entry param : formParams.entrySet()) { - String keyStr = parameterToString(param.getKey()); + for (Entry param : formParams.entrySet()) { + String keyStr = param.getKey(); String valueStr = parameterToString(param.getValue()); - try { - formParamBuilder.append(URLEncoder.encode(keyStr, "utf8")) + formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8")) .append("=") .append(URLEncoder.encode(valueStr, "utf8")); formParamBuilder.append("&"); @@ -542,11 +529,12 @@ public class ApiClient { // move on to next } } + String encodedFormParams = formParamBuilder.toString(); if (encodedFormParams.endsWith("&")) { - encodedFormParams = encodedFormParams.substring(0, - encodedFormParams.length() - 1); + encodedFormParams = encodedFormParams.substring(0, encodedFormParams.length() - 1); } + return encodedFormParams; } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java similarity index 88% rename from samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java index a39785eb47ec..679786deb107 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java @@ -3,6 +3,7 @@ package io.swagger.client; import java.util.Map; import java.util.List; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") public class ApiException extends Exception { private int code = 0; private String message = null; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java similarity index 81% rename from samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java index 04899a110f63..0a674b8d52ae 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java @@ -1,5 +1,6 @@ package io.swagger.client; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 000000000000..5523b921e45c --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,54 @@ +package io.swagger.client; + +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; + +import java.io.IOException; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T18:19:30.060+08:00") +public class JSON { + private ObjectMapper mapper; + + public JSON() { + mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.registerModule(new JodaModule()); + } + + /** + * Serialize the given Java object into JSON string. + */ + public String serialize(Object obj) throws ApiException { + try { + if (obj != null) + return mapper.writeValueAsString(obj); + else + return null; + } catch (Exception e) { + throw new ApiException(400, e.getMessage()); + } + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, TypeRef returnType) throws ApiException { + JavaType javaType = mapper.constructType(returnType.getType()); + try { + return mapper.readValue(body, javaType); + } catch (IOException e) { + if (returnType.getType().equals(String.class)) + return (T) body; + else + throw new ApiException(500, e.getMessage(), null, body); + } + } +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java similarity index 84% rename from samples/client/petstore/java/src/main/java/io/swagger/client/Pair.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java index 4b7112f6db65..9f9e2c96b4cc 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java @@ -1,5 +1,6 @@ package io.swagger.client; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java similarity index 90% rename from samples/client/petstore/java/src/main/java/io/swagger/client/StringUtil.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java index 5b5af2d5ce03..de5e940ba55d 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java @@ -1,5 +1,6 @@ package io.swagger.client; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java new file mode 100644 index 000000000000..cd69bd71e7c6 --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java @@ -0,0 +1,26 @@ +package io.swagger.client; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +public class TypeRef { + private final Type type; + + public TypeRef() { + this.type = getGenericType(getClass()); + } + + private static Type getGenericType(Class klass) { + Type superclass = klass.getGenericSuperclass(); + if (superclass instanceof Class) { + throw new RuntimeException("No type parameter provided"); + } + ParameterizedType parameterized = (ParameterizedType) superclass; + return parameterized.getActualTypeArguments()[0]; + } + + public Type getType() { + return type; + } +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java similarity index 57% rename from samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java index c9b7a2a917a6..75dfc35beb1c 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java @@ -4,6 +4,7 @@ import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.TypeRef; import io.swagger.client.model.*; @@ -12,15 +13,11 @@ import java.util.*; import io.swagger.client.model.Pet; import java.io.File; -import com.sun.jersey.multipart.FormDataMultiPart; -import com.sun.jersey.multipart.file.FileDataBodyPart; - -import javax.ws.rs.core.MediaType; - import java.io.File; import java.util.Map; import java.util.HashMap; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") public class PetApi { private ApiClient apiClient; @@ -57,7 +54,9 @@ public class PetApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -73,29 +72,10 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -114,7 +94,9 @@ public class PetApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -130,29 +112,10 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -171,7 +134,7 @@ public class PetApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); queryParams.addAll(apiClient.parameterToPairs("multi", "status", status)); @@ -179,6 +142,8 @@ public class PetApi { + + final String[] accepts = { "application/json", "application/xml" }; @@ -189,29 +154,11 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (List) apiClient.deserialize(response, "array", Pet.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "petstore_auth" }; + + TypeRef returnType = new TypeRef>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -230,7 +177,7 @@ public class PetApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); queryParams.addAll(apiClient.parameterToPairs("multi", "tags", tags)); @@ -238,6 +185,8 @@ public class PetApi { + + final String[] accepts = { "application/json", "application/xml" }; @@ -248,29 +197,11 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (List) apiClient.deserialize(response, "array", Pet.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "petstore_auth" }; + + TypeRef returnType = new TypeRef>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -295,7 +226,9 @@ public class PetApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -311,29 +244,11 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "api_key", "petstore_auth" }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (Pet) apiClient.deserialize(response, "", Pet.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "api_key", "petstore_auth" }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -360,12 +275,18 @@ public class PetApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + if (name != null) + formParams.put("name", name); + if (status != null) + formParams.put("status", status); + + final String[] accepts = { "application/json", "application/xml" }; @@ -376,43 +297,10 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if (name != null) { - hasFields = true; - mp.field("name", apiClient.parameterToString(name), MediaType.MULTIPART_FORM_DATA_TYPE); - } - - if (status != null) { - hasFields = true; - mp.field("status", apiClient.parameterToString(status), MediaType.MULTIPART_FORM_DATA_TYPE); - } - - if(hasFields) - postBody = mp; - } - else { - if (name != null) - formParams.put("name", apiClient.parameterToString(name)); - if (status != null) - formParams.put("status", apiClient.parameterToString(status)); - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -438,7 +326,7 @@ public class PetApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); @@ -446,6 +334,8 @@ public class PetApi { headerParams.put("api_key", apiClient.parameterToString(apiKey)); + + final String[] accepts = { "application/json", "application/xml" }; @@ -456,29 +346,10 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -505,12 +376,18 @@ public class PetApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + if (additionalMetadata != null) + formParams.put("additionalMetadata", additionalMetadata); + if (file != null) + formParams.put("file", file); + + final String[] accepts = { "application/json", "application/xml" }; @@ -521,43 +398,10 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if (additionalMetadata != null) { - hasFields = true; - mp.field("additionalMetadata", apiClient.parameterToString(additionalMetadata), MediaType.MULTIPART_FORM_DATA_TYPE); - } - - if (file != null) { - hasFields = true; - mp.field("file", file.getName()); - mp.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)); - } - - if(hasFields) - postBody = mp; - } - else { - if (additionalMetadata != null) - formParams.put("additionalMetadata", apiClient.parameterToString(additionalMetadata)); - - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java similarity index 61% rename from samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java index 498b6d4a6b89..a488fb374450 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java @@ -4,6 +4,7 @@ import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.TypeRef; import io.swagger.client.model.*; @@ -12,15 +13,11 @@ import java.util.*; import java.util.Map; import io.swagger.client.model.Order; -import com.sun.jersey.multipart.FormDataMultiPart; -import com.sun.jersey.multipart.file.FileDataBodyPart; - -import javax.ws.rs.core.MediaType; - import java.io.File; import java.util.Map; import java.util.HashMap; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") public class StoreApi { private ApiClient apiClient; @@ -56,7 +53,9 @@ public class StoreApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -72,29 +71,11 @@ public class StoreApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "api_key" }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (Map) apiClient.deserialize(response, "map", Map.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "api_key" }; + + TypeRef returnType = new TypeRef>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -113,7 +94,9 @@ public class StoreApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -129,29 +112,11 @@ public class StoreApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (Order) apiClient.deserialize(response, "", Order.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -176,7 +141,9 @@ public class StoreApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -192,29 +159,11 @@ public class StoreApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (Order) apiClient.deserialize(response, "", Order.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -239,7 +188,9 @@ public class StoreApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -255,29 +206,10 @@ public class StoreApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java similarity index 60% rename from samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java index 3bff204ac02b..3dee565a271b 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java @@ -4,6 +4,7 @@ import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.TypeRef; import io.swagger.client.model.*; @@ -12,15 +13,11 @@ import java.util.*; import io.swagger.client.model.User; import java.util.*; -import com.sun.jersey.multipart.FormDataMultiPart; -import com.sun.jersey.multipart.file.FileDataBodyPart; - -import javax.ws.rs.core.MediaType; - import java.io.File; import java.util.Map; import java.util.HashMap; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") public class UserApi { private ApiClient apiClient; @@ -57,7 +54,9 @@ public class UserApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -73,29 +72,10 @@ public class UserApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -114,7 +94,9 @@ public class UserApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -130,29 +112,10 @@ public class UserApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -171,7 +134,9 @@ public class UserApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -187,29 +152,10 @@ public class UserApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -229,7 +175,7 @@ public class UserApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); queryParams.addAll(apiClient.parameterToPairs("", "username", username)); @@ -239,6 +185,8 @@ public class UserApi { + + final String[] accepts = { "application/json", "application/xml" }; @@ -249,29 +197,11 @@ public class UserApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (String) apiClient.deserialize(response, "", String.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -289,7 +219,9 @@ public class UserApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -305,29 +237,10 @@ public class UserApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -352,7 +265,9 @@ public class UserApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -368,29 +283,11 @@ public class UserApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (User) apiClient.deserialize(response, "", User.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -416,7 +313,9 @@ public class UserApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -432,29 +331,10 @@ public class UserApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -479,7 +359,9 @@ public class UserApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -495,29 +377,10 @@ public class UserApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java similarity index 90% rename from samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 0e5ca9c7c538..dccddad00886 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -5,6 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java similarity index 69% rename from samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java index 98b1a6900b93..7efcc795425a 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java @@ -5,6 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List queryParams, Map headerParams); diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java similarity index 88% rename from samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 980b24311bea..41d7988af0d6 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -8,6 +8,7 @@ import java.util.List; import java.io.UnsupportedEncodingException; import javax.xml.bind.DatatypeConverter; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") public class HttpBasicAuth implements Authentication { private String username; private String password; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java similarity index 68% rename from samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java index 39fba5498c0e..20520b968133 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java @@ -5,6 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") public class OAuth implements Authentication { @Override public void applyToParams(List queryParams, Map headerParams) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 000000000000..b7ccc46204c0 --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,53 @@ +package io.swagger.client.model; + + + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +public class Category { + + private Long id = null; + private String name = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 000000000000..e89c1f3fb408 --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,127 @@ +package io.swagger.client.model; + +import java.util.Date; + + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T18:19:30.060+08:00") +public class Order { + + private Long id = null; + private Long petId = null; + private Integer quantity = null; + private Date shipDate = null; + +public enum StatusEnum { + PLACED("placed"), APPROVED("approved"), DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} + + private StatusEnum status = null; + private Boolean complete = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("shipDate") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + + /** + * Order Status + **/ + @ApiModelProperty(value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" petId: ").append(petId).append("\n"); + sb.append(" quantity: ").append(quantity).append("\n"); + sb.append(" shipDate: ").append(shipDate).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append(" complete: ").append(complete).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java new file mode 100644 index 000000000000..b3b0e1b5347f --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,129 @@ +package io.swagger.client.model; + +import io.swagger.client.model.Category; +import java.util.*; +import io.swagger.client.model.Tag; + + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T18:19:30.060+08:00") +public class Pet { + + private Long id = null; + private Category category = null; + private String name = null; + private List photoUrls = new ArrayList(); + private List tags = new ArrayList(); + +public enum StatusEnum { + AVAILABLE("available"), PENDING("pending"), SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} + + private StatusEnum status = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("category") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" category: ").append(category).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append(" photoUrls: ").append(photoUrls).append("\n"); + sb.append(" tags: ").append(tags).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java new file mode 100644 index 000000000000..2550d7c76364 --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,53 @@ +package io.swagger.client.model; + + + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +public class Tag { + + private Long id = null; + private String name = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java new file mode 100644 index 000000000000..d27f1c2658d8 --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,138 @@ +package io.swagger.client.model; + + + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +public class User { + + private Long id = null; + private String username = null; + private String firstName = null; + private String lastName = null; + private String email = null; + private String password = null; + private String phone = null; + private Integer userStatus = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("username") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("lastName") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("email") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("phone") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + + /** + * User Status + **/ + @ApiModelProperty(value = "User Status") + @JsonProperty("userStatus") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" username: ").append(username).append("\n"); + sb.append(" firstName: ").append(firstName).append("\n"); + sb.append(" lastName: ").append(lastName).append("\n"); + sb.append(" email: ").append(email).append("\n"); + sb.append(" password: ").append(password).append("\n"); + sb.append(" phone: ").append(phone).append("\n"); + sb.append(" userStatus: ").append(userStatus).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java similarity index 100% rename from samples/client/petstore/java/src/test/java/io/swagger/client/ApiClientTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ConfigurationTest.java similarity index 100% rename from samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/client/ConfigurationTest.java diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/StringUtilTest.java similarity index 100% rename from samples/client/petstore/java/src/test/java/io/swagger/client/StringUtilTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/client/StringUtilTest.java diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java similarity index 100% rename from samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java similarity index 100% rename from samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java diff --git a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java similarity index 97% rename from samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java index b6ad5fb05275..0a8f8a1665d2 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -86,7 +86,7 @@ public class PetApiTest { public void testFindPetsByStatus() throws Exception { Pet pet = createRandomPet(); pet.setName("programmer"); - pet.setStatus(Pet.StatusEnum.available); + pet.setStatus(Pet.StatusEnum.AVAILABLE); api.updatePet(pet); @@ -108,7 +108,7 @@ public class PetApiTest { public void testFindPetsByTags() throws Exception { Pet pet = createRandomPet(); pet.setName("monster"); - pet.setStatus(Pet.StatusEnum.available); + pet.setStatus(Pet.StatusEnum.AVAILABLE); List tags = new ArrayList(); Tag tag1 = new Tag(); @@ -183,7 +183,7 @@ public class PetApiTest { category.setName("really-happy"); pet.setCategory(category); - pet.setStatus(Pet.StatusEnum.available); + pet.setStatus(Pet.StatusEnum.AVAILABLE); List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); pet.setPhotoUrls(photos); diff --git a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java similarity index 97% rename from samples/client/petstore/java/src/test/java/io/swagger/petstore/test/StoreApiTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java index 508764b8c2db..a1fd7e345a81 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -64,7 +64,7 @@ public class StoreApiTest { order.setPetId(new Long(200)); order.setQuantity(new Integer(13)); order.setShipDate(new java.util.Date()); - order.setStatus(Order.StatusEnum.placed); + order.setStatus(Order.StatusEnum.PLACED); order.setComplete(true); return order; diff --git a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java similarity index 100% rename from samples/client/petstore/java/src/test/java/io/swagger/petstore/test/UserApiTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java diff --git a/samples/client/petstore/java/jersey2/pom.xml b/samples/client/petstore/java/jersey2/pom.xml new file mode 100644 index 000000000000..eee88cd24293 --- /dev/null +++ b/samples/client/petstore/java/jersey2/pom.xml @@ -0,0 +1,171 @@ + + 4.0.0 + io.swagger + swagger-petstore-jersey2 + jar + swagger-petstore-jersey2 + 1.0.0 + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + org.glassfish.jersey.core + jersey-client + ${jersey-version} + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey-version} + + + + + 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} + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 2.6 + 2.4.2 + 2.3 + 1.0.0 + 4.8.1 + + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 000000000000..3ddf4621ae83 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,533 @@ +package io.swagger.client; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Form; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.filter.LoggingFilter; +import org.glassfish.jersey.media.multipart.FormDataBodyPart; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Date; +import java.util.TimeZone; + +import java.net.URLEncoder; + +import java.io.IOException; +import java.io.File; +import java.io.UnsupportedEncodingException; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.text.ParseException; + +import io.swagger.client.auth.Authentication; +import io.swagger.client.auth.HttpBasicAuth; +import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.OAuth; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +public class ApiClient { + private Map hostMap = new HashMap(); + private Map defaultHeaderMap = new HashMap(); + private boolean debugging = false; + private String basePath = "http://petstore.swagger.io/v2"; + private JSON json = new JSON(); + + private Map authentications; + + private DateFormat dateFormat; + + public ApiClient() { + // Use ISO 8601 format for date and datetime. + // See https://en.wikipedia.org/wiki/ISO_8601 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + // Set default User-Agent. + setUserAgent("Java-Swagger"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + return this; + } + + /** + * Get the date format used to parse/format date parameters. + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + */ + public ApiClient getDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + return this; + } + + /** + * Parse the given string into Date object. + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given parameter object into string. + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection)param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /* + Format to {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) return null; + if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) return "application/json"; + if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + */ + public Entity serialize(Object obj, String contentType) throws ApiException { + if (contentType.startsWith("application/json")) { + return Entity.json(json.serialize(obj)); + } else { + throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); + } + } + + /** + * Deserialize response body to Java object according to the Content-Type. + */ + public T deserialize(Response response, TypeRef returnType) throws ApiException { + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = String.valueOf(contentTypes.get(0)); + if (contentType == null) + throw new ApiException(500, "missing Content-Type in response"); + + String body; + if (response.hasEntity()) + body = (String) response.readEntity(String.class); + else + body = ""; + + if (contentType.startsWith("application/json")) { + return json.deserialize(body, returnType); + } else { + throw new ApiException(500, "can not deserialize Content-Type: " + contentType); + } + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @return The response body in type of string + */ + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final ClientConfig clientConfig = new ClientConfig(); + clientConfig.register(MultiPartFeature.class); + if (debugging) { + clientConfig.register(LoggingFilter.class); + } + Client client = ClientBuilder.newClient(clientConfig); + + WebTarget target = client.target(this.basePath).path(path); + + if (queryParams != null) { + for (Pair queryParam : queryParams) { + if (queryParam.getValue() != null) { + target = target.queryParam(queryParam.getName(), queryParam.getValue()); + } + } + } + + Invocation.Builder invocationBuilder = target.request(contentType).accept(accept); + + for (String key : headerParams.keySet()) { + String value = headerParams.get(key); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + + for (String key : defaultHeaderMap.keySet()) { + if (!headerParams.containsKey(key)) { + String value = defaultHeaderMap.get(key); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + } + + Entity formEntity = null; + + if (contentType.startsWith("multipart/form-data")) { + MultiPart multipart = new MultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + + FormDataMultiPart mp = new FormDataMultiPart(); + mp.bodyPart(new FormDataBodyPart(param.getKey(), file.getName())); + multipart.bodyPart(mp, MediaType.MULTIPART_FORM_DATA_TYPE); + + multipart.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + } else { + FormDataMultiPart mp = new FormDataMultiPart(); + mp.bodyPart(new FormDataBodyPart(param.getKey(), parameterToString(param.getValue()))); + multipart.bodyPart(mp, MediaType.MULTIPART_FORM_DATA_TYPE); + } + } + formEntity = Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA_TYPE); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + Form form = new Form(); + for (Entry param: formParams.entrySet()) { + form.param(param.getKey(), parameterToString(param.getValue())); + } + formEntity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); + } + + Response response = null; + + if ("GET".equals(method)) { + response = invocationBuilder.get(); + } else if ("POST".equals(method)) { + if (formEntity != null) { + response = invocationBuilder.post(formEntity); + } else if (body == null) { + response = invocationBuilder.post(null); + } else { + response = invocationBuilder.post(serialize(body, contentType)); + } + } else if ("PUT".equals(method)) { + if (formEntity != null) { + response = invocationBuilder.put(formEntity); + } else if (body == null) { + response = invocationBuilder.put(null); + } else { + response = invocationBuilder.put(serialize(body, contentType)); + } + } else if ("DELETE".equals(method)) { + response = invocationBuilder.delete(); + } else { + throw new ApiException(500, "unknown method type " + method); + } + + if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { + return null; + } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { + if (returnType == null) + return null; + else + return deserialize(response, returnType); + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { + try { + respBody = String.valueOf(response.readEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + Map> responseHeaders = new HashMap>(); + for (String key: response.getHeaders().keySet()) { + List values = response.getHeaders().get(key); + List headers = new ArrayList(); + for (Object o : values) { + headers.add(String.valueOf(o)); + } + responseHeaders.put(key, headers); + } + throw new ApiException( + response.getStatus(), + message, + responseHeaders, + respBody); + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ + private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java new file mode 100644 index 000000000000..48b196e2af7e --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java @@ -0,0 +1,48 @@ +package io.swagger.client; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +public class ApiException extends Exception { + private int code = 0; + private String message = null; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(int code, String message) { + this.code = code; + this.message = message; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this.code = code; + this.message = message; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public int getCode() { + return code; + } + + public String getMessage() { + return message; + } + + /** + * Get the HTTP response headers. + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java new file mode 100644 index 000000000000..e94cd5c0aa36 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java @@ -0,0 +1,22 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 000000000000..3095c7bacead --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,54 @@ +package io.swagger.client; + +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; + +import java.io.IOException; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T16:42:49.539+08:00") +public class JSON { + private ObjectMapper mapper; + + public JSON() { + mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.registerModule(new JodaModule()); + } + + /** + * Serialize the given Java object into JSON string. + */ + public String serialize(Object obj) throws ApiException { + try { + if (obj != null) + return mapper.writeValueAsString(obj); + else + return null; + } catch (Exception e) { + throw new ApiException(400, e.getMessage()); + } + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, TypeRef returnType) throws ApiException { + JavaType javaType = mapper.constructType(returnType.getType()); + try { + return mapper.readValue(body, javaType); + } catch (IOException e) { + if (returnType.getType().equals(String.class)) + return (T) body; + else + throw new ApiException(500, e.getMessage(), null, body); + } + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java new file mode 100644 index 000000000000..cb0e034bd638 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java @@ -0,0 +1,39 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java new file mode 100644 index 000000000000..50e37eb367a5 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java @@ -0,0 +1,42 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

+ * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java new file mode 100644 index 000000000000..1444bca5a064 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java @@ -0,0 +1,26 @@ +package io.swagger.client; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +public class TypeRef { + private final Type type; + + public TypeRef() { + this.type = getGenericType(getClass()); + } + + private static Type getGenericType(Class klass) { + Type superclass = klass.getGenericSuperclass(); + if (superclass instanceof Class) { + throw new RuntimeException("No type parameter provided"); + } + ParameterizedType parameterized = (ParameterizedType) superclass; + return parameterized.getActualTypeArguments()[0]; + } + + public Type getType() { + return type; + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 000000000000..ca72d88b1304 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,407 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.TypeRef; + +import io.swagger.client.model.*; + +import java.util.*; + +import io.swagger.client.model.Pet; +import java.io.File; + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + * @return void + */ + public void updatePet (Pet body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + "application/json", "application/xml" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + * @return void + */ + public void addPet (Pet body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + "application/json", "application/xml" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + * @return List + */ + public List findPetsByStatus (List status) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + queryParams.addAll(apiClient.parameterToPairs("multi", "status", status)); + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + TypeRef returnType = new TypeRef>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @return List + */ + public List findPetsByTags (List tags) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + queryParams.addAll(apiClient.parameterToPairs("multi", "tags", tags)); + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + TypeRef returnType = new TypeRef>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @return Pet + */ + public Pet getPetById (Long petId) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); + } + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth", "api_key" }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @return void + */ + public void updatePetWithForm (String petId, String name, String status) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); + } + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + if (name != null) + formParams.put("name", name); + if (status != null) + formParams.put("status", status); + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + "application/x-www-form-urlencoded" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + * @return void + */ + public void deletePet (Long petId, String apiKey) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); + } + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + if (apiKey != null) + headerParams.put("api_key", apiClient.parameterToString(apiKey)); + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @return void + */ + public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); + } + + + // create path and map variables + String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + if (additionalMetadata != null) + formParams.put("additionalMetadata", additionalMetadata); + if (file != null) + formParams.put("file", file); + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + "multipart/form-data" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 000000000000..2abbae3f714d --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,215 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.TypeRef; + +import io.swagger.client.model.*; + +import java.util.*; + +import java.util.Map; +import io.swagger.client.model.Order; + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map + */ + public Map getInventory () throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/store/inventory".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "api_key" }; + + TypeRef returnType = new TypeRef>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return Order + */ + public Order placeOrder (Order body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/store/order".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @return Order + */ + public Order getOrderById (String orderId) throws ApiException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); + } + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + * @return void + */ + public void deleteOrder (String orderId) throws ApiException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); + } + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 000000000000..7959290acd67 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,386 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.TypeRef; + +import io.swagger.client.model.*; + +import java.util.*; + +import io.swagger.client.model.User; +import java.util.*; + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @return void + */ + public void createUser (User body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + */ + public void createUsersWithArrayInput (List body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + */ + public void createUsersWithListInput (List body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user/createWithList".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return String + */ + public String loginUser (String username, String password) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/user/login".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + queryParams.addAll(apiClient.parameterToPairs("", "username", username)); + + queryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Logs out current logged in user session + * + * @return void + */ + public void logoutUser () throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/user/logout".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + */ + public User getUserByName (String username) throws ApiException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + * @return void + */ + public void updateUser (String username, User body) throws ApiException { + Object postBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @return void + */ + public void deleteUser (String username) throws ApiException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 000000000000..87a4a90a49cd --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,59 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location == "query") { + queryParams.add(new Pair(paramName, value)); + } else if (location == "header") { + headerParams.put(paramName, value); + } + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java new file mode 100644 index 000000000000..b35133a0c94f --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java @@ -0,0 +1,12 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +public interface Authentication { + /** Apply authentication settings to header and query params. */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 000000000000..7d224efefbb4 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -0,0 +1,41 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; +import javax.xml.bind.DatatypeConverter; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + try { + headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 000000000000..06debad62e47 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java @@ -0,0 +1,14 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +public class OAuth implements Authentication { + @Override + public void applyToParams(List queryParams, Map headerParams) { + // TODO: support oauth + } +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java similarity index 86% rename from samples/client/petstore/java/src/main/java/io/swagger/client/model/Category.java rename to samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java index d43f6a9758fb..f0dab47c7f7e 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") public class Category { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 000000000000..2477288848da --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,127 @@ +package io.swagger.client.model; + +import java.util.Date; + + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T16:42:49.539+08:00") +public class Order { + + private Long id = null; + private Long petId = null; + private Integer quantity = null; + private Date shipDate = null; + +public enum StatusEnum { + PLACED("placed"), APPROVED("approved"), DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} + + private StatusEnum status = null; + private Boolean complete = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("shipDate") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + + /** + * Order Status + **/ + @ApiModelProperty(value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" petId: ").append(petId).append("\n"); + sb.append(" quantity: ").append(quantity).append("\n"); + sb.append(" shipDate: ").append(shipDate).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append(" complete: ").append(complete).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java new file mode 100644 index 000000000000..1ed729475562 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,129 @@ +package io.swagger.client.model; + +import io.swagger.client.model.Category; +import java.util.*; +import io.swagger.client.model.Tag; + + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T16:42:49.539+08:00") +public class Pet { + + private Long id = null; + private Category category = null; + private String name = null; + private List photoUrls = new ArrayList(); + private List tags = new ArrayList(); + +public enum StatusEnum { + AVAILABLE("available"), PENDING("pending"), SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} + + private StatusEnum status = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("category") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" category: ").append(category).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append(" photoUrls: ").append(photoUrls).append("\n"); + sb.append(" tags: ").append(tags).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java similarity index 86% rename from samples/client/petstore/java/src/main/java/io/swagger/client/model/Tag.java rename to samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java index 63a2ca3b7390..3bf1b196e1d8 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") public class Tag { private Long id = null; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java similarity index 95% rename from samples/client/petstore/java/src/main/java/io/swagger/client/model/User.java rename to samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java index 0ace5b7e30a3..0d454ec95aa4 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") public class User { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java new file mode 100644 index 000000000000..802c0cae3b97 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java @@ -0,0 +1,193 @@ +package io.swagger.client; + +import io.swagger.client.auth.*; + +import java.util.*; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiClientTest { + ApiClient apiClient = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + } + + @Test + public void testSelectHeaderAccept() { + String[] accepts = {"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/xml", "application/json"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + String[] contentTypes = {"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/xml", "application/json"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + @Test + public void testSetUsername() { + try { + apiClient.setUsername("my-username"); + fail("there should be no HTTP basic authentications"); + } catch (RuntimeException e) { + } + } + + @Test + public void testSetPassword() { + try { + apiClient.setPassword("my-password"); + fail("there should be no HTTP basic authentications"); + } catch (RuntimeException e) { + } + } + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = (ApiKeyAuth) apiClient.getAuthentications().get("api_key"); + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1)); + List pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + + // single empty string + List pairs = apiClient.parameterToPairs("csv", "param-a", " "); + assertEquals(1, pairs.size()); + + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = apiClient.parameterToPairs("csv", name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "\\|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = apiClient.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = apiClient.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + } + } +} diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ConfigurationTest.java new file mode 100644 index 000000000000..b95eb74605ea --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +package io.swagger.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ConfigurationTest { + @Test + public void testDefaultApiClient() { + ApiClient apiClient = Configuration.getDefaultApiClient(); + assertNotNull(apiClient); + assertEquals("http://petstore.swagger.io/v2", apiClient.getBasePath()); + assertFalse(apiClient.isDebugging()); + } +} diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/StringUtilTest.java new file mode 100644 index 000000000000..4b03c7a98120 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/StringUtilTest.java @@ -0,0 +1,33 @@ +package io.swagger.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class StringUtilTest { + @Test + public void testContainsIgnoreCase() { + assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null)); + + assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def")); + assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC")); + assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null)); + } + + @Test + public void testJoin() { + String[] array = {"aa", "bb", "cc"}; + assertEquals("aa,bb,cc", StringUtil.join(array, ",")); + assertEquals("aa, bb, cc", StringUtil.join(array, ", ")); + assertEquals("aabbcc", StringUtil.join(array, "")); + assertEquals("aa bb cc", StringUtil.join(array, " ")); + assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n")); + + assertEquals("", StringUtil.join(new String[]{}, ",")); + assertEquals("abc", StringUtil.join(new String[]{"abc"}, ",")); + } +} diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java new file mode 100644 index 000000000000..5bdb4fb78fba --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams); + + assertEquals(1, queryParams.size()); + for (Pair queryParam : queryParams) { + assertEquals("my-api-key", queryParam.getValue()); + } + + // no changes to header parameters + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); + } +} diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java new file mode 100644 index 000000000000..52c5497ba83e --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,52 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @Before + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization")); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization")); + } +} diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java new file mode 100644 index 000000000000..0a8f8a1665d2 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -0,0 +1,192 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.Configuration; + +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.*; +import static org.junit.Assert.*; + +public class PetApiTest { + PetApi api = null; + + @Before + public void setup() { + api = new PetApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } + + @Test + public void testApiClient() { + // the default api client is used + assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); + + ApiClient oldClient = api.getApiClient(); + + ApiClient newClient = new ApiClient(); + newClient.setBasePath("http://example.com"); + newClient.setDebugging(true); + + // set api client via constructor + api = new PetApi(newClient); + assertNotNull(api.getApiClient()); + assertEquals("http://example.com", api.getApiClient().getBasePath()); + assertTrue(api.getApiClient().isDebugging()); + + // set api client via setter method + api.setApiClient(oldClient); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); + } + + @Test + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(fetched.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (ApiException e) { + assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(System.currentTimeMillis()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } +} diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java new file mode 100644 index 000000000000..a1fd7e345a81 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -0,0 +1,72 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiException; + +import io.swagger.client.*; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.util.Map; + +import org.junit.*; +import static org.junit.Assert.*; + +public class StoreApiTest { + StoreApi api = null; + + @Before + public void setup() { + api = new StoreApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } + + @Test + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); + } + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(String.valueOf(order.getId())); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(String.valueOf(order.getId())); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + try { + api.getOrderById(String.valueOf(order.getId())); + // fail("expected an error"); + } catch (ApiException e) { + // ok + } + } + + private Order createOrder() { + Order order = new Order(); + order.setId(new Long(System.currentTimeMillis())); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(new java.util.Date()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + return order; + } +} diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java new file mode 100644 index 000000000000..26e46bfa6024 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -0,0 +1,86 @@ +package io.swagger.petstore.test; + +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.util.Arrays; + +import org.junit.*; +import static org.junit.Assert.*; + +public class UserApiTest { + UserApi api = null; + + @Before + public void setup() { + api = new UserApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } + + @Test + public void testCreateUser() throws Exception { + User user = createUser(); + + api.createUser(user); + + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); + + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); + } + + @Test + public void logoutUser() throws Exception { + api.logoutUser(); + } + + private User createUser() { + User user = new User(); + user.setId(System.currentTimeMillis()); + user.setUsername("fred"); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; + } +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/JsonUtil.java b/samples/client/petstore/java/src/main/java/io/swagger/client/JsonUtil.java deleted file mode 100644 index 8e7e686dd0ce..000000000000 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/JsonUtil.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.swagger.client; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.core.JsonGenerator.Feature; - -import com.fasterxml.jackson.datatype.joda.*; - -public class JsonUtil { - public static ObjectMapper mapper; - - static { - mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.registerModule(new JodaModule()); - } - - public static ObjectMapper getJsonMapper() { - return mapper; - } -} diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h index 7802a5b46c0e..84f28faa8c6c 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h @@ -172,6 +172,7 @@ extern NSString *const SWGResponseObjectErrorKey; * * @param path Request url. * @param method Request method. + * @param pathParams Request path parameters. * @param queryParams Request query parameters. * @param body Request body. * @param headerParams Request header parameters. @@ -184,6 +185,7 @@ extern NSString *const SWGResponseObjectErrorKey; */ -(NSNumber*) requestWithCompletionBlock:(NSString*) path method:(NSString*) method + pathParams:(NSDictionary *) pathParams queryParams:(NSDictionary*) queryParams formParams:(NSDictionary *) formParams files:(NSDictionary *) files @@ -195,4 +197,11 @@ extern NSString *const SWGResponseObjectErrorKey; responseType:(NSString *) responseType completionBlock:(void (^)(id, NSError *))completionBlock; +/** + * Sanitize object for request + * + * @param object The query/path/header/form/body param to be sanitized. + */ +- (id) sanitizeForSerialization:(id) object; + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index 22b5c256402b..906169f4d129 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -467,6 +467,7 @@ static void (^reachabilityChangeBlock)(int); -(NSNumber*) requestWithCompletionBlock: (NSString*) path method: (NSString*) method + pathParams: (NSDictionary *) pathParams queryParams: (NSDictionary*) queryParams formParams: (NSDictionary *) formParams files: (NSDictionary *) files @@ -499,12 +500,25 @@ static void (^reachabilityChangeBlock)(int); self.responseSerializer = [AFHTTPResponseSerializer serializer]; } + // sanitize parameters + pathParams = [self sanitizeForSerialization:pathParams]; + queryParams = [self sanitizeForSerialization:queryParams]; + headerParams = [self sanitizeForSerialization:headerParams]; + formParams = [self sanitizeForSerialization:formParams]; + body = [self sanitizeForSerialization:body]; + // auth setting [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; + NSMutableString *resourcePath = [NSMutableString stringWithString:path]; + [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", key, @"}"]] + withString:[SWGApiClient escape:obj]]; + }]; + NSMutableURLRequest * request = nil; - NSString* pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; + NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams]; if ([pathWithQueryParams hasPrefix:@"/"]) { pathWithQueryParams = [pathWithQueryParams substringFromIndex:1]; } @@ -540,20 +554,21 @@ static void (^reachabilityChangeBlock)(int); } } + // request cache BOOL hasHeaderParams = false; if(headerParams != nil && [headerParams count] > 0) { hasHeaderParams = true; } if(offlineState) { - NSLog(@"%@ cache forced", path); + NSLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; } else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - NSLog(@"%@ cache enabled", path); + NSLog(@"%@ cache enabled", resourcePath); [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; } else { - NSLog(@"%@ cache disabled", path); + NSLog(@"%@ cache disabled", resourcePath); [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } @@ -671,4 +686,44 @@ static void (^reachabilityChangeBlock)(int); *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } +- (id) sanitizeForSerialization:(id) object { + if (object == nil) { + return nil; + } + else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[SWGQueryParamCollection class]]) { + return object; + } + else if ([object isKindOfClass:[NSDate class]]) { + return [object ISO8601String]; + } + else if ([object isKindOfClass:[NSArray class]]) { + NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[object count]]; + [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + if (obj) { + [sanitizedObjs addObject:[self sanitizeForSerialization:obj]]; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[NSDictionary class]]) { + NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[object count]]; + [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + if (obj) { + [sanitizedObjs setValue:[self sanitizeForSerialization:obj] forKey:key]; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[SWGObject class]]) { + return [object toDictionary]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] + userInfo:nil]; + @throw e; + } +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.h b/samples/client/petstore/objc/SwaggerClient/SWGPet.h index e340e0e2b86a..84f10969e5be 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.h @@ -7,8 +7,8 @@ * Do not edit the class manually. */ -#import "SWGTag.h" #import "SWGCategory.h" +#import "SWGTag.h" @protocol SWGPet diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m index f2e7fb640307..d79584f90bfe 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m @@ -80,7 +80,8 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -115,27 +116,12 @@ NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; bodyParam = body; - - if(bodyParam != nil && [bodyParam isKindOfClass:[NSArray class]]){ - NSMutableArray *objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)bodyParam) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[(SWGObject*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyParam = objs; - } - else if([bodyParam respondsToSelector:@selector(toDictionary)]) { - bodyParam = [(SWGObject*)bodyParam toDictionary]; - } return [self.apiClient requestWithCompletionBlock: resourcePath method: @"PUT" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -172,7 +158,8 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -207,27 +194,12 @@ NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; bodyParam = body; - - if(bodyParam != nil && [bodyParam isKindOfClass:[NSArray class]]){ - NSMutableArray *objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)bodyParam) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[(SWGObject*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyParam = objs; - } - else if([bodyParam respondsToSelector:@selector(toDictionary)]) { - bodyParam = [(SWGObject*)bodyParam toDictionary]; - } return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -264,7 +236,8 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -310,6 +283,7 @@ return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -346,7 +320,8 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -392,6 +367,7 @@ return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -433,8 +409,11 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (petId != nil) { + pathParams[@"petId"] = petId; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -462,7 +441,7 @@ NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"api_key", @"petstore_auth"]; + NSArray *authSettings = @[@"petstore_auth", @"api_key"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -474,6 +453,7 @@ return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -521,8 +501,11 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (petId != nil) { + pathParams[@"petId"] = petId; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -558,11 +541,15 @@ - formParams[@"name"] = name; + if (name) { + formParams[@"name"] = name; + } - formParams[@"status"] = status; + if (status) { + formParams[@"status"] = status; + } @@ -570,6 +557,7 @@ return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -614,8 +602,11 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (petId != nil) { + pathParams[@"petId"] = petId; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -657,6 +648,7 @@ return [self.apiClient requestWithCompletionBlock: resourcePath method: @"DELETE" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -704,8 +696,11 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (petId != nil) { + pathParams[@"petId"] = petId; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -741,7 +736,9 @@ - formParams[@"additionalMetadata"] = additionalMetadata; + if (additionalMetadata) { + formParams[@"additionalMetadata"] = additionalMetadata; + } @@ -753,6 +750,7 @@ return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m index ed792988597f..792147ebed14 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m @@ -77,7 +77,8 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -117,6 +118,7 @@ return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -153,7 +155,8 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -188,27 +191,12 @@ NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; bodyParam = body; - - if(bodyParam != nil && [bodyParam isKindOfClass:[NSArray class]]){ - NSMutableArray *objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)bodyParam) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[(SWGObject*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyParam = objs; - } - else if([bodyParam respondsToSelector:@selector(toDictionary)]) { - bodyParam = [(SWGObject*)bodyParam toDictionary]; - } return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -250,8 +238,11 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (orderId != nil) { + pathParams[@"orderId"] = orderId; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -291,6 +282,7 @@ return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -332,8 +324,11 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (orderId != nil) { + pathParams[@"orderId"] = orderId; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -373,6 +368,7 @@ return [self.apiClient requestWithCompletionBlock: resourcePath method: @"DELETE" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m index 46a76b35b577..92dd00fa28da 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m @@ -80,7 +80,8 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -115,27 +116,12 @@ NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; bodyParam = body; - - if(bodyParam != nil && [bodyParam isKindOfClass:[NSArray class]]){ - NSMutableArray *objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)bodyParam) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[(SWGObject*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyParam = objs; - } - else if([bodyParam respondsToSelector:@selector(toDictionary)]) { - bodyParam = [(SWGObject*)bodyParam toDictionary]; - } return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -172,7 +158,8 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -207,27 +194,12 @@ NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; bodyParam = body; - - if(bodyParam != nil && [bodyParam isKindOfClass:[NSArray class]]){ - NSMutableArray *objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)bodyParam) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[(SWGObject*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyParam = objs; - } - else if([bodyParam respondsToSelector:@selector(toDictionary)]) { - bodyParam = [(SWGObject*)bodyParam toDictionary]; - } return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -264,7 +236,8 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -299,27 +272,12 @@ NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; bodyParam = body; - - if(bodyParam != nil && [bodyParam isKindOfClass:[NSArray class]]){ - NSMutableArray *objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)bodyParam) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[(SWGObject*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyParam = objs; - } - else if([bodyParam respondsToSelector:@selector(toDictionary)]) { - bodyParam = [(SWGObject*)bodyParam toDictionary]; - } return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -359,7 +317,8 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -407,6 +366,7 @@ return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -440,7 +400,8 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -480,6 +441,7 @@ return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -521,8 +483,11 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (username != nil) { + pathParams[@"username"] = username; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -562,6 +527,7 @@ return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -606,8 +572,11 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (username != nil) { + pathParams[@"username"] = username; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -642,27 +611,12 @@ NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; bodyParam = body; - - if(bodyParam != nil && [bodyParam isKindOfClass:[NSArray class]]){ - NSMutableArray *objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)bodyParam) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[(SWGObject*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyParam = objs; - } - else if([bodyParam respondsToSelector:@selector(toDictionary)]) { - bodyParam = [(SWGObject*)bodyParam toDictionary]; - } return [self.apiClient requestWithCompletionBlock: resourcePath method: @"PUT" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -704,8 +658,11 @@ if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; } - - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (username != nil) { + pathParams[@"username"] = username; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -745,6 +702,7 @@ return [self.apiClient requestWithCompletionBlock: resourcePath method: @"DELETE" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m index d19180dc008e..e9f1a46af3ba 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m @@ -1,7 +1,12 @@ #import #import +#import #import #import +#import +#import +#import +#import @interface SWGApiClientTest : XCTestCase @@ -98,4 +103,65 @@ XCTAssertEqualObjects(basicAuthCredentials, [config getBasicAuthToken]); } +- (void)testSanitizeForSerialization { + id result; + id data; + + // nil + data = nil; + result = [self.apiClient sanitizeForSerialization:data]; + XCTAssertEqualObjects(result, data); + + // NSString + data = @"test string"; + result = [self.apiClient sanitizeForSerialization:data]; + XCTAssertEqualObjects(result, data); + + // NSNumber + data = @1; + result = [self.apiClient sanitizeForSerialization:data]; + XCTAssertEqualObjects(result, data); + + // SWGQueryParamCollection + data = [[SWGQueryParamCollection alloc] init]; + result = [self.apiClient sanitizeForSerialization:data]; + XCTAssertEqualObjects(result, data); + + // NSDate + data = [NSDate dateWithISO8601String:@"1997-07-16T19:20:30.45+01:00"]; + result = [self.apiClient sanitizeForSerialization:data]; + XCTAssertEqualObjects(result, [data ISO8601String]); + + data = [NSDate dateWithISO8601String:@"1997-07-16"]; + result = [self.apiClient sanitizeForSerialization:data]; + XCTAssertEqualObjects(result, [data ISO8601String]); + + // model + NSDictionary *petDict = @{@"id": @1, @"name": @"monkey", + @"category": @{@"id": @1, @"name": @"test category"}, + @"tags": @[@{@"id": @1, @"name": @"test tag1"}, + @{@"id": @2, @"name": @"test tag2"}], + @"status": @"available", + @"photoUrls": @[@"http://foo.bar.com/3", @"http://foo.bar.com/4"]}; + data = [[SWGPet alloc] initWithDictionary:petDict error:nil]; + result = [self.apiClient sanitizeForSerialization:data]; + XCTAssertEqualObjects(result, petDict); + + // NSArray + data = @[@1]; + result = [self.apiClient sanitizeForSerialization:data]; + XCTAssertEqualObjects(result, data); + + // NSArray of models + NSArray *arrayOfPetDict = @[petDict]; + data = [NSArray arrayWithObject:[[SWGPet alloc] initWithDictionary:petDict error:nil]]; + result = [self.apiClient sanitizeForSerialization:data]; + XCTAssertEqualObjects(result, arrayOfPetDict); + + // NSDictionary + data = @{@"test key": @"test value"}; + result = [self.apiClient sanitizeForSerialization:data]; + XCTAssertEqualObjects(result, data); +} + @end diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 535c623118ac..0d281b9d1fa3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -191,9 +191,9 @@ class ObjectSerializer $values[] = $this->deserialize($value, $subClass); } $deserialized = $values; - } elseif ($class === 'DateTime') { + } elseif ($class === '\DateTime') { $deserialized = new \DateTime($data); - } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { + } elseif (in_array($class, array('integer', 'int', 'void', 'number', 'object', 'double', 'float', 'byte', 'DateTime', 'string', 'mixed', 'boolean', 'bool'))) { settype($data, $class); $deserialized = $data; } elseif ($class === '\SplFileObject') { diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php index 7672667a2358..3eb0d11a9b2b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php @@ -31,6 +31,31 @@ class OrderApiTest extends \PHPUnit_Framework_TestCase $order = new Swagger\Client\Model\Order(); $order->setStatus("invalid_value"); } + + // test deseralization of order + public function testDeserializationOfOrder() + { + $order_json = <<deserialize(json_decode($order_json), 'Swagger\Client\Model\Order'); + + $this->assertInstanceOf('Swagger\Client\Model\Order', $order); + $this->assertSame(10, $order->getId()); + $this->assertSame(20, $order->getPetId()); + $this->assertSame(30, $order->getQuantity()); + $this->assertTrue(new DateTime("2015-08-22T07:13:36.613Z") == $order->getShipDate()); + $this->assertSame("placed", $order->getStatus()); + $this->assertSame(false, $order->getComplete()); + } } diff --git a/samples/client/petstore/python/.coverage b/samples/client/petstore/python/.coverage new file mode 100644 index 000000000000..d58a8fe9c63f Binary files /dev/null and b/samples/client/petstore/python/.coverage differ diff --git a/samples/client/petstore/python/dev-requirements.txt.log b/samples/client/petstore/python/dev-requirements.txt.log new file mode 100644 index 000000000000..9394a7240303 --- /dev/null +++ b/samples/client/petstore/python/dev-requirements.txt.log @@ -0,0 +1,15 @@ +Collecting nose (from -r dev-requirements.txt (line 1)) + Using cached nose-1.3.7-py2-none-any.whl +Collecting tox (from -r dev-requirements.txt (line 2)) + Using cached tox-2.1.1-py2.py3-none-any.whl +Collecting coverage (from -r dev-requirements.txt (line 3)) +Collecting randomize (from -r dev-requirements.txt (line 4)) + Using cached randomize-0.13-py2.py3-none-any.whl +Collecting virtualenv>=1.11.2 (from tox->-r dev-requirements.txt (line 2)) + Using cached virtualenv-13.1.2-py2.py3-none-any.whl +Collecting py>=1.4.17 (from tox->-r dev-requirements.txt (line 2)) + Using cached py-1.4.30-py2.py3-none-any.whl +Collecting pluggy<0.4.0,>=0.3.0 (from tox->-r dev-requirements.txt (line 2)) + Using cached pluggy-0.3.0-py2.py3-none-any.whl +Installing collected packages: nose, virtualenv, py, pluggy, tox, coverage, randomize +Successfully installed coverage-3.7.1 nose-1.3.7 pluggy-0.3.0 py-1.4.30 randomize-0.13 tox-2.1.1 virtualenv-13.1.2 diff --git a/samples/client/petstore/python/setup.py b/samples/client/petstore/python/setup.py index e66e9689343e..8564466b0dda 100644 --- a/samples/client/petstore/python/setup.py +++ b/samples/client/petstore/python/setup.py @@ -8,13 +8,11 @@ VERSION = "1.0.0" -# To install the library, open a Terminal shell, then run this -# file by typing: +# To install the library, run the following # # python setup.py install # -# You need to have the setuptools module installed. -# Try reading the setuptools documentation: +# prerequisite: setuptools # http://pypi.python.org/pypi/setuptools REQUIRES = ["urllib3 >= 1.10", "six >= 1.9", "certifi", "python-dateutil"] diff --git a/samples/client/petstore/python/swagger_client.egg-info/PKG-INFO b/samples/client/petstore/python/swagger_client.egg-info/PKG-INFO new file mode 100644 index 000000000000..d4fe6f978b3f --- /dev/null +++ b/samples/client/petstore/python/swagger_client.egg-info/PKG-INFO @@ -0,0 +1,12 @@ +Metadata-Version: 1.0 +Name: swagger-client +Version: 1.0.0 +Summary: Swagger Petstore +Home-page: UNKNOWN +Author: UNKNOWN +Author-email: apiteam@swagger.io +License: UNKNOWN +Description: This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + +Keywords: Swagger,Swagger Petstore +Platform: UNKNOWN diff --git a/samples/client/petstore/python/swagger_client.egg-info/SOURCES.txt b/samples/client/petstore/python/swagger_client.egg-info/SOURCES.txt new file mode 100644 index 000000000000..a7d91c0b8ce2 --- /dev/null +++ b/samples/client/petstore/python/swagger_client.egg-info/SOURCES.txt @@ -0,0 +1,29 @@ +setup.cfg +setup.py +swagger_client/__init__.py +swagger_client/api_client.py +swagger_client/configuration.py +swagger_client/rest.py +swagger_client.egg-info/PKG-INFO +swagger_client.egg-info/SOURCES.txt +swagger_client.egg-info/dependency_links.txt +swagger_client.egg-info/requires.txt +swagger_client.egg-info/top_level.txt +swagger_client/apis/__init__.py +swagger_client/apis/pet_api.py +swagger_client/apis/store_api.py +swagger_client/apis/user_api.py +swagger_client/models/__init__.py +swagger_client/models/category.py +swagger_client/models/order.py +swagger_client/models/pet.py +swagger_client/models/tag.py +swagger_client/models/user.py +tests/__init__.py +tests/test_api_client.py +tests/test_api_exception.py +tests/test_deserialization.py +tests/test_order_model.py +tests/test_pet_api.py +tests/test_pet_model.py +tests/test_store_api.py \ No newline at end of file diff --git a/samples/client/petstore/python/swagger_client.egg-info/dependency_links.txt b/samples/client/petstore/python/swagger_client.egg-info/dependency_links.txt new file mode 100644 index 000000000000..8b137891791f --- /dev/null +++ b/samples/client/petstore/python/swagger_client.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/samples/client/petstore/python/swagger_client.egg-info/requires.txt b/samples/client/petstore/python/swagger_client.egg-info/requires.txt new file mode 100644 index 000000000000..367a059209fe --- /dev/null +++ b/samples/client/petstore/python/swagger_client.egg-info/requires.txt @@ -0,0 +1,4 @@ +urllib3 >= 1.10 +six >= 1.9 +certifi +python-dateutil diff --git a/samples/client/petstore/python/swagger_client.egg-info/top_level.txt b/samples/client/petstore/python/swagger_client.egg-info/top_level.txt new file mode 100644 index 000000000000..9a02a75c0585 --- /dev/null +++ b/samples/client/petstore/python/swagger_client.egg-info/top_level.txt @@ -0,0 +1,2 @@ +swagger_client +tests diff --git a/samples/client/petstore/python/swagger_client/api_client.py b/samples/client/petstore/python/swagger_client/api_client.py index ca9a3c051042..1030bf9a8385 100644 --- a/samples/client/petstore/python/swagger_client/api_client.py +++ b/samples/client/petstore/python/swagger_client/api_client.py @@ -14,11 +14,13 @@ Copyright 2015 SmartBear Software 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. + + ref: https://github.com/swagger-api/swagger-codegen """ from __future__ import absolute_import from . import models -from .rest import RESTClient +from .rest import RESTClientObject from .rest import ApiException import os @@ -56,7 +58,7 @@ class ApiClient(object): templates. NOTE: This class is auto generated by the swagger code generator program. - https://github.com/swagger-api/swagger-codegen + Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. :param host: The base path for the server to call. @@ -69,13 +71,14 @@ class ApiClient(object): """ Constructor of the class. """ + self.rest_client = RESTClientObject() self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value self.host = host self.cookie = cookie # Set default User-Agent. - self.user_agent = 'Python-Swagger' + self.user_agent = 'Python-Swagger/1.0.0' @property def user_agent(self): @@ -202,11 +205,9 @@ class ApiClient(object): # and attributes which value is not None. # Convert attribute name to json key in # model definition for request. - obj_dict = {obj.attribute_map[key[1:]]: val - for key, val in iteritems(obj.__dict__) - if key != 'swagger_types' - and key != 'attribute_map' - and val is not None} + obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) + for attr, _ in iteritems(obj.swagger_types) + if getattr(obj, attr) is not None} return {key: self.sanitize_for_serialization(val) for key, val in iteritems(obj_dict)} @@ -282,7 +283,8 @@ class ApiClient(object): body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None): """ - Makes the HTTP request and return the deserialized data. + Makes the HTTP request (synchronous) and return the deserialized data. + To make an async request, define a function for callback. :param resource_path: Path to method endpoint. :param method: Method to call. @@ -329,32 +331,35 @@ class ApiClient(object): Makes the HTTP request using RESTClient. """ if method == "GET": - return RESTClient.GET(url, - query_params=query_params, - headers=headers) + return self.rest_client.GET(url, + query_params=query_params, + headers=headers) elif method == "HEAD": - return RESTClient.HEAD(url, - query_params=query_params, - headers=headers) + return self.rest_client.HEAD(url, + query_params=query_params, + headers=headers) elif method == "POST": - return RESTClient.POST(url, - headers=headers, - post_params=post_params, - body=body) + return self.rest_client.POST(url, + query_params=query_params, + headers=headers, + post_params=post_params, + body=body) elif method == "PUT": - return RESTClient.PUT(url, - headers=headers, - post_params=post_params, - body=body) + return self.rest_client.PUT(url, + query_params=query_params, + headers=headers, + post_params=post_params, + body=body) elif method == "PATCH": - return RESTClient.PATCH(url, - headers=headers, - post_params=post_params, - body=body) + return self.rest_client.PATCH(url, + query_params=query_params, + headers=headers, + post_params=post_params, + body=body) elif method == "DELETE": - return RESTClient.DELETE(url, - query_params=query_params, - headers=headers) + return self.rest_client.DELETE(url, + query_params=query_params, + headers=headers) else: raise ValueError( "http method must be `GET`, `HEAD`," @@ -449,9 +454,8 @@ class ApiClient(object): def __deserialize_file(self, response): """ - Saves response body into a file in (the defined) temporary folder, - using the filename from the `Content-Disposition` header if provided, - otherwise a random filename. + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. :param response: RESTResponse. :return: file path. diff --git a/samples/client/petstore/python/swagger_client/apis/pet_api.py b/samples/client/petstore/python/swagger_client/apis/pet_api.py index 1c34da118c14..ad053a7d72d9 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -33,6 +33,7 @@ class PetApi(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. + Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): @@ -41,7 +42,7 @@ class PetApi(object): self.api_client = api_client else: if not config.api_client: - config.api_client = ApiClient('http://petstore.swagger.io/v2') + config.api_client = ApiClient() self.api_client = config.api_client def update_pet(self, **kwargs): @@ -49,7 +50,7 @@ class PetApi(object): Update an existing pet - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -124,7 +125,7 @@ class PetApi(object): Add a new pet to the store - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -199,7 +200,7 @@ class PetApi(object): Finds Pets by status Multiple status values can be provided with comma seperated strings - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -274,7 +275,7 @@ class PetApi(object): Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -349,7 +350,7 @@ class PetApi(object): Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -427,7 +428,7 @@ class PetApi(object): Updates a pet in the store with form data - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -511,7 +512,7 @@ class PetApi(object): Deletes a pet - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -592,7 +593,7 @@ class PetApi(object): uploads an image - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): diff --git a/samples/client/petstore/python/swagger_client/apis/store_api.py b/samples/client/petstore/python/swagger_client/apis/store_api.py index 4dca0af85e2c..9e08a0b2f473 100644 --- a/samples/client/petstore/python/swagger_client/apis/store_api.py +++ b/samples/client/petstore/python/swagger_client/apis/store_api.py @@ -33,6 +33,7 @@ class StoreApi(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. + Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): @@ -41,7 +42,7 @@ class StoreApi(object): self.api_client = api_client else: if not config.api_client: - config.api_client = ApiClient('http://petstore.swagger.io/v2') + config.api_client = ApiClient() self.api_client = config.api_client def get_inventory(self, **kwargs): @@ -49,7 +50,7 @@ class StoreApi(object): Returns pet inventories by status Returns a map of status codes to quantities - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -121,7 +122,7 @@ class StoreApi(object): Place an order for a pet - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -196,7 +197,7 @@ class StoreApi(object): Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -274,7 +275,7 @@ class StoreApi(object): Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): diff --git a/samples/client/petstore/python/swagger_client/apis/user_api.py b/samples/client/petstore/python/swagger_client/apis/user_api.py index 4897abe8801e..1c96e1e923ee 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/swagger_client/apis/user_api.py @@ -33,6 +33,7 @@ class UserApi(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. + Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): @@ -41,7 +42,7 @@ class UserApi(object): self.api_client = api_client else: if not config.api_client: - config.api_client = ApiClient('http://petstore.swagger.io/v2') + config.api_client = ApiClient() self.api_client = config.api_client def create_user(self, **kwargs): @@ -49,7 +50,7 @@ class UserApi(object): Create user This can only be done by the logged in user. - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -124,7 +125,7 @@ class UserApi(object): Creates list of users with given input array - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -199,7 +200,7 @@ class UserApi(object): Creates list of users with given input array - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -274,7 +275,7 @@ class UserApi(object): Logs user into the system - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -352,7 +353,7 @@ class UserApi(object): Logs out current logged in user session - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -424,7 +425,7 @@ class UserApi(object): Get user by user name - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -502,7 +503,7 @@ class UserApi(object): Updated user This can only be done by the logged in user. - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): @@ -583,7 +584,7 @@ class UserApi(object): Delete user This can only be done by the logged in user. - This method makes a synchronous HTTP request by default.To make an + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): diff --git a/samples/client/petstore/python/swagger_client/configuration.py b/samples/client/petstore/python/swagger_client/configuration.py index 8f469b726539..4ca9342c0571 100644 --- a/samples/client/petstore/python/swagger_client/configuration.py +++ b/samples/client/petstore/python/swagger_client/configuration.py @@ -14,6 +14,8 @@ Copyright 2015 SmartBear Software 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. + + ref: https://github.com/swagger-api/swagger-codegen """ from __future__ import absolute_import @@ -23,9 +25,9 @@ import urllib3 try: import httplib except ImportError: - # python3 + # for python3 import http.client as httplib - + import sys import logging @@ -44,7 +46,7 @@ def singleton(cls, *args, **kw): class Configuration(object): """ NOTE: This class is auto generated by the swagger code generator program. - https://github.com/swagger-api/swagger-codegen + Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. """ @@ -56,7 +58,7 @@ class Configuration(object): self.host = "http://petstore.swagger.io/v2" # Default api client self.api_client = None - # Temp file folder for download + # Temp file folder for downloading files self.temp_folder_path = None # Authentication Settings @@ -77,6 +79,12 @@ class Configuration(object): self.__debug = False self.init_logger() + # SSL/TLS verification + # Set this to false to skip verifying SSL certificate when calling API from https server. + self.verify_ssl = True + # Set this to customize the certificate file to verify the peer. + self.ssl_ca_cert = None + def init_logger(self): """ Initializes logger settings. @@ -139,7 +147,7 @@ class Configuration(object): def get_basic_auth_token(self): """ - Gets basic auth header string. + Gets HTTP basic authentication header (string). :return: The token for basic HTTP authentication. """ diff --git a/samples/client/petstore/python/swagger_client/models/category.py b/samples/client/petstore/python/swagger_client/models/category.py index 615e65ea8399..06ad3b8421f2 100644 --- a/samples/client/petstore/python/swagger_client/models/category.py +++ b/samples/client/petstore/python/swagger_client/models/category.py @@ -14,6 +14,8 @@ Copyright 2015 SmartBear Software 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. + + Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -27,7 +29,7 @@ class Category(object): """ def __init__(self): """ - Swagger model + Category - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. @@ -93,28 +95,27 @@ class Category(object): def to_dict(self): """ - Return model properties dict + Returns the model properties as a dict """ result = {} - for name, prop in iteritems(self.__dict__): - if name == "attribute_map" or name == "swagger_types": - continue - if isinstance(prop, list): - result[name[1:]] = list(map( + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - prop + value )) - elif hasattr(prop, "to_dict"): - result[name[1:]] = prop.to_dict() + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() else: - result[name[1:]] = prop + result[attr] = value return result def to_str(self): """ - Return model properties str + Returns the string representation of the model """ return pformat(self.to_dict()) diff --git a/samples/client/petstore/python/swagger_client/models/order.py b/samples/client/petstore/python/swagger_client/models/order.py index a381853b91f8..40e4504de87b 100644 --- a/samples/client/petstore/python/swagger_client/models/order.py +++ b/samples/client/petstore/python/swagger_client/models/order.py @@ -14,6 +14,8 @@ Copyright 2015 SmartBear Software 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. + + Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -27,7 +29,7 @@ class Order(object): """ def __init__(self): """ - Swagger model + Order - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. @@ -199,28 +201,27 @@ class Order(object): def to_dict(self): """ - Return model properties dict + Returns the model properties as a dict """ result = {} - for name, prop in iteritems(self.__dict__): - if name == "attribute_map" or name == "swagger_types": - continue - if isinstance(prop, list): - result[name[1:]] = list(map( + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - prop + value )) - elif hasattr(prop, "to_dict"): - result[name[1:]] = prop.to_dict() + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() else: - result[name[1:]] = prop + result[attr] = value return result def to_str(self): """ - Return model properties str + Returns the string representation of the model """ return pformat(self.to_dict()) diff --git a/samples/client/petstore/python/swagger_client/models/pet.py b/samples/client/petstore/python/swagger_client/models/pet.py index 57dc93387a90..d8700908eb78 100644 --- a/samples/client/petstore/python/swagger_client/models/pet.py +++ b/samples/client/petstore/python/swagger_client/models/pet.py @@ -14,6 +14,8 @@ Copyright 2015 SmartBear Software 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. + + Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -27,7 +29,7 @@ class Pet(object): """ def __init__(self): """ - Swagger model + Pet - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. @@ -199,28 +201,27 @@ class Pet(object): def to_dict(self): """ - Return model properties dict + Returns the model properties as a dict """ result = {} - for name, prop in iteritems(self.__dict__): - if name == "attribute_map" or name == "swagger_types": - continue - if isinstance(prop, list): - result[name[1:]] = list(map( + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - prop + value )) - elif hasattr(prop, "to_dict"): - result[name[1:]] = prop.to_dict() + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() else: - result[name[1:]] = prop + result[attr] = value return result def to_str(self): """ - Return model properties str + Returns the string representation of the model """ return pformat(self.to_dict()) diff --git a/samples/client/petstore/python/swagger_client/models/tag.py b/samples/client/petstore/python/swagger_client/models/tag.py index bfa389520a3c..262fc10f338c 100644 --- a/samples/client/petstore/python/swagger_client/models/tag.py +++ b/samples/client/petstore/python/swagger_client/models/tag.py @@ -14,6 +14,8 @@ Copyright 2015 SmartBear Software 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. + + Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -27,7 +29,7 @@ class Tag(object): """ def __init__(self): """ - Swagger model + Tag - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. @@ -93,28 +95,27 @@ class Tag(object): def to_dict(self): """ - Return model properties dict + Returns the model properties as a dict """ result = {} - for name, prop in iteritems(self.__dict__): - if name == "attribute_map" or name == "swagger_types": - continue - if isinstance(prop, list): - result[name[1:]] = list(map( + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - prop + value )) - elif hasattr(prop, "to_dict"): - result[name[1:]] = prop.to_dict() + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() else: - result[name[1:]] = prop + result[attr] = value return result def to_str(self): """ - Return model properties str + Returns the string representation of the model """ return pformat(self.to_dict()) diff --git a/samples/client/petstore/python/swagger_client/models/user.py b/samples/client/petstore/python/swagger_client/models/user.py index 7380bc945821..7f74d20f3d37 100644 --- a/samples/client/petstore/python/swagger_client/models/user.py +++ b/samples/client/petstore/python/swagger_client/models/user.py @@ -14,6 +14,8 @@ Copyright 2015 SmartBear Software 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. + + Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat @@ -27,7 +29,7 @@ class User(object): """ def __init__(self): """ - Swagger model + User - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. @@ -243,28 +245,27 @@ class User(object): def to_dict(self): """ - Return model properties dict + Returns the model properties as a dict """ result = {} - for name, prop in iteritems(self.__dict__): - if name == "attribute_map" or name == "swagger_types": - continue - if isinstance(prop, list): - result[name[1:]] = list(map( + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - prop + value )) - elif hasattr(prop, "to_dict"): - result[name[1:]] = prop.to_dict() + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() else: - result[name[1:]] = prop + result[attr] = value return result def to_str(self): """ - Return model properties str + Returns the string representation of the model """ return pformat(self.to_dict()) diff --git a/samples/client/petstore/python/swagger_client/rest.py b/samples/client/petstore/python/swagger_client/rest.py index 8a8e55eb3d12..1481cbff3d52 100644 --- a/samples/client/petstore/python/swagger_client/rest.py +++ b/samples/client/petstore/python/swagger_client/rest.py @@ -18,6 +18,7 @@ Copyright 2015 SmartBear Software Credit: this file (rest.py) is modified based on rest.py in Dropbox Python SDK: https://www.dropbox.com/developers/core/sdks/python """ +from __future__ import absolute_import import sys import io @@ -29,6 +30,8 @@ import logging # python 2 and python 3 compatibility library from six import iteritems +from .configuration import Configuration + try: import urllib3 except ImportError: @@ -69,31 +72,24 @@ class RESTResponse(io.IOBase): class RESTClientObject(object): def __init__(self, pools_size=4): - # http pool manager - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size - ) + if Configuration().verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + if Configuration().ssl_ca_cert: + ca_certs = Configuration().ssl_ca_cert + else: + # if not set certificate file, use Mozilla's root certificates. + ca_certs = certifi.where() # https pool manager - # certificates validated using Mozilla’s root certificates - self.ssl_pool_manager = urllib3.PoolManager( + self.pool_manager = urllib3.PoolManager( num_pools=pools_size, - cert_reqs=ssl.CERT_REQUIRED, - ca_certs=certifi.where() + cert_reqs=cert_reqs, + ca_certs=ca_certs ) - def agent(self, url): - """ - Use `urllib3.util.parse_url` for backward compatibility. - Return proper pool manager for the http/https schemes. - """ - url = urllib3.util.parse_url(url) - scheme = url.scheme - if scheme == 'https': - return self.ssl_pool_manager - else: - return self.pool_manager - def request(self, method, url, query_params=None, headers=None, body=None, post_params=None): """ @@ -120,32 +116,37 @@ class RESTClientObject(object): if 'Content-Type' not in headers: headers['Content-Type'] = 'application/json' - # For `POST`, `PUT`, `PATCH` - if method in ['POST', 'PUT', 'PATCH']: - if query_params: - url += '?' + urlencode(query_params) - if headers['Content-Type'] == 'application/json': - r = self.agent(url).request(method, url, - body=json.dumps(body), - headers=headers) - if headers['Content-Type'] == 'application/x-www-form-urlencoded': - r = self.agent(url).request(method, url, - fields=post_params, - encode_multipart=False, - headers=headers) - if headers['Content-Type'] == 'multipart/form-data': - # must del headers['Content-Type'], or the correct Content-Type - # which generated by urllib3 will be overwritten. - del headers['Content-Type'] - r = self.agent(url).request(method, url, - fields=post_params, - encode_multipart=True, - headers=headers) - # For `GET`, `HEAD`, `DELETE` - else: - r = self.agent(url).request(method, url, - fields=query_params, - headers=headers) + try: + # For `POST`, `PUT`, `PATCH` + if method in ['POST', 'PUT', 'PATCH']: + if query_params: + url += '?' + urlencode(query_params) + if headers['Content-Type'] == 'application/json': + r = self.pool_manager.request(method, url, + body=json.dumps(body), + headers=headers) + if headers['Content-Type'] == 'application/x-www-form-urlencoded': + r = self.pool_manager.request(method, url, + fields=post_params, + encode_multipart=False, + headers=headers) + if headers['Content-Type'] == 'multipart/form-data': + # must del headers['Content-Type'], or the correct Content-Type + # which generated by urllib3 will be overwritten. + del headers['Content-Type'] + r = self.pool_manager.request(method, url, + fields=post_params, + encode_multipart=True, + headers=headers) + # For `GET`, `HEAD`, `DELETE` + else: + r = self.pool_manager.request(method, url, + fields=query_params, + headers=headers) + except urllib3.exceptions.SSLError as e: + msg = "{0}\n{1}".format(type(e).__name__, str(e)) + raise ApiException(status=0, reason=msg) + r = RESTResponse(r) # In the python 3, the response.data is bytes. @@ -176,21 +177,24 @@ class RESTClientObject(object): headers=headers, query_params=query_params) - def POST(self, url, headers=None, post_params=None, body=None): + def POST(self, url, headers=None, query_params=None, post_params=None, body=None): return self.request("POST", url, headers=headers, + query_params=query_params, post_params=post_params, body=body) - def PUT(self, url, headers=None, post_params=None, body=None): + def PUT(self, url, headers=None, query_params=None, post_params=None, body=None): return self.request("PUT", url, headers=headers, + query_params=query_params, post_params=post_params, body=body) - def PATCH(self, url, headers=None, post_params=None, body=None): + def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None): return self.request("PATCH", url, headers=headers, + query_params=query_params, post_params=post_params, body=body) @@ -224,58 +228,20 @@ class ApiException(Exception): return error_message -class RESTClient(object): - """ - A class with all class methods to perform JSON requests. - """ - IMPL = RESTClientObject() - @classmethod - def request(cls, *n, **kw): - """ - Perform a REST request and parse the response. - """ - return cls.IMPL.request(*n, **kw) - @classmethod - def GET(cls, *n, **kw): - """ - Perform a GET request using `RESTClient.request()`. - """ - return cls.IMPL.GET(*n, **kw) - @classmethod - def HEAD(cls, *n, **kw): - """ - Perform a HEAD request using `RESTClient.request()`. - """ - return cls.IMPL.GET(*n, **kw) - @classmethod - def POST(cls, *n, **kw): - """ - Perform a POST request using `RESTClient.request()` - """ - return cls.IMPL.POST(*n, **kw) - @classmethod - def PUT(cls, *n, **kw): - """ - Perform a PUT request using `RESTClient.request()` - """ - return cls.IMPL.PUT(*n, **kw) - @classmethod - def PATCH(cls, *n, **kw): - """ - Perform a PATCH request using `RESTClient.request()` - """ - return cls.IMPL.PATCH(*n, **kw) - @classmethod - def DELETE(cls, *n, **kw): - """ - Perform a DELETE request using `RESTClient.request()` - """ - return cls.IMPL.DELETE(*n, **kw) + + + + + + + + + diff --git a/samples/client/petstore/python/tests/test_api_client.py b/samples/client/petstore/python/tests/test_api_client.py index 903fde458152..61c57cb7e460 100644 --- a/samples/client/petstore/python/tests/test_api_client.py +++ b/samples/client/petstore/python/tests/test_api_client.py @@ -10,6 +10,7 @@ $ nosetests -v import os import time import unittest +from dateutil.parser import parse import swagger_client import swagger_client.configuration @@ -51,7 +52,7 @@ class ApiClientTests(unittest.TestCase): accepts = ['APPLICATION/JSON', 'APPLICATION/XML'] accept = self.api_client.select_header_accept(accepts) self.assertEqual(accept, 'application/json') - + accepts = ['application/json', 'application/xml'] accept = self.api_client.select_header_accept(accepts) self.assertEqual(accept, 'application/json') @@ -72,19 +73,95 @@ class ApiClientTests(unittest.TestCase): content_types = ['APPLICATION/JSON', 'APPLICATION/XML'] content_type = self.api_client.select_header_content_type(content_types) self.assertEqual(content_type, 'application/json') - + content_types = ['application/json', 'application/xml'] content_type = self.api_client.select_header_content_type(content_types) self.assertEqual(content_type, 'application/json') - + content_types = ['application/xml', 'application/json'] content_type = self.api_client.select_header_content_type(content_types) self.assertEqual(content_type, 'application/json') - + content_types = ['text/plain', 'application/xml'] content_type = self.api_client.select_header_content_type(content_types) self.assertEqual(content_type, 'text/plain') - + content_types = [] content_type = self.api_client.select_header_content_type(content_types) self.assertEqual(content_type, 'application/json') + + def test_sanitize_for_serialization(self): + # None + data = None + result = self.api_client.sanitize_for_serialization(None) + self.assertEqual(result, data) + + # str + data = "test string" + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, data) + + # int + data = 1 + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, data) + + # bool + data = True + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, data) + + # date + data = parse("1997-07-16").date() # date + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, "1997-07-16") + + # datetime + data = parse("1997-07-16T19:20:30.45+01:00") # datetime + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, "1997-07-16T19:20:30.450000+01:00") + + # list + data = [1] + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, data) + + # dict + data = {"test key": "test value"} + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, data) + + # model + pet_dict = {"id": 1, "name": "monkey", + "category": {"id": 1, "name": "test category"}, + "tags": [{"id": 1, "name": "test tag1"}, + {"id": 2, "name": "test tag2"}], + "status": "available", + "photoUrls": ["http://foo.bar.com/3", + "http://foo.bar.com/4"]} + pet = swagger_client.Pet() + pet.id = pet_dict["id"] + pet.name = pet_dict["name"] + cate = swagger_client.Category() + cate.id = pet_dict["category"]["id"] + cate.name = pet_dict["category"]["name"] + pet.category = cate + tag1 = swagger_client.Tag() + tag1.id = pet_dict["tags"][0]["id"] + tag1.name = pet_dict["tags"][0]["name"] + tag2 = swagger_client.Tag() + tag2.id = pet_dict["tags"][1]["id"] + tag2.name = pet_dict["tags"][1]["name"] + pet.tags = [tag1, tag2] + pet.status = pet_dict["status"] + pet.photo_urls = pet_dict["photoUrls"] + + data = pet + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, pet_dict) + + # list of models + list_of_pet_dict = [pet_dict] + data = [pet] + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, list_of_pet_dict) diff --git a/samples/client/wordnik/android-java/pom.xml b/samples/client/wordnik/android-java/pom.xml index 0be5e486152a..f2a84451d837 100644 --- a/samples/client/wordnik/android-java/pom.xml +++ b/samples/client/wordnik/android-java/pom.xml @@ -152,7 +152,7 @@ - 1.5.1-M1 + 1.5.3 2.1.4 4.8.1 1.0.0 diff --git a/samples/server/petstore/java-inflector/README.md b/samples/server/petstore/java-inflector/README.md new file mode 100644 index 000000000000..c1309670c5ad --- /dev/null +++ b/samples/server/petstore/java-inflector/README.md @@ -0,0 +1,8 @@ +# Swagger Inflector + +Run with + +``` +mvn package jetty:run +`` + diff --git a/samples/server/petstore/java-inflector/inflector.yaml b/samples/server/petstore/java-inflector/inflector.yaml new file mode 100644 index 000000000000..25ec6dde3f2e --- /dev/null +++ b/samples/server/petstore/java-inflector/inflector.yaml @@ -0,0 +1,10 @@ +controllerPackage: io.swagger.handler +modelPackage: io.swagger.model +swaggerUrl: ./src/main/swagger/swagger.json +modelMappings: + User : io.swagger.model.User + Category : io.swagger.model.Category + Pet : io.swagger.model.Pet + Tag : io.swagger.model.Tag + Order : io.swagger.model.Order + diff --git a/samples/server/petstore/java-inflector/pom.xml b/samples/server/petstore/java-inflector/pom.xml new file mode 100644 index 000000000000..7b7ec1d8b3d6 --- /dev/null +++ b/samples/server/petstore/java-inflector/pom.xml @@ -0,0 +1,92 @@ + + + org.sonatype.oss + oss-parent + 5 + + 4.0.0 + io.swagger + swagger-inflector-server + jar + swagger-inflector-server + 1.0.0 + + 2.2.0 + + + + install + target + ${project.artifactId}-${project.version} + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + **/logback.xml + + + + development + ${project.url} + ${project.version} + io.swagger + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty-version} + + . + + inflector.yaml + src/main/swagger/swagger.yaml + + 1 + + / + + + 8080 + 60000 + + + + + + + + + io.swagger + swagger-inflector + 1.0.0-SNAPSHOT + + + + 1.0.0 + 1.5.3 + 9.2.9.v20150224 + 1.0.1 + 4.8.2 + 1.6.3 + + \ No newline at end of file diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java new file mode 100644 index 000000000000..9f31acf53da9 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java @@ -0,0 +1,73 @@ +package io.swagger.handler; + +import io.swagger.inflector.models.RequestContext; +import io.swagger.inflector.models.ResponseContext; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import java.io.File; +import java.util.List; + +import io.swagger.model.*; + +import io.swagger.model.Pet; +import java.io.File; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-08-24T17:25:49.737-07:00") +public class PetController { + /** + * Uncomment and implement as you see fit. These operations will map + * Direclty to operation calls from the routing logic. Because the inflector + * Code allows you to implement logic incrementally, they are disabled. + **/ + + /* + public ResponseContext updatePet(RequestContext request , Pet body) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext addPet(RequestContext request , Pet body) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext findPetsByStatus(RequestContext request , List status) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext findPetsByTags(RequestContext request , List tags) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext getPetById(RequestContext request , Long petId) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext updatePetWithForm(RequestContext request , String petId, String name, String status) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext deletePet(RequestContext request , Long petId, String apiKey) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext uploadFile(RequestContext request , Long petId, String additionalMetadata, FormDataContentDisposition fileDetail) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + +} + diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java new file mode 100644 index 000000000000..3506b6b920c6 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java @@ -0,0 +1,49 @@ +package io.swagger.handler; + +import io.swagger.inflector.models.RequestContext; +import io.swagger.inflector.models.ResponseContext; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import java.io.File; +import java.util.List; + +import io.swagger.model.*; + +import java.util.Map; +import io.swagger.model.Order; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-08-24T17:25:49.737-07:00") +public class StoreController { + /** + * Uncomment and implement as you see fit. These operations will map + * Direclty to operation calls from the routing logic. Because the inflector + * Code allows you to implement logic incrementally, they are disabled. + **/ + + /* + public ResponseContext getInventory(RequestContext request ) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext placeOrder(RequestContext request , Order body) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext getOrderById(RequestContext request , String orderId) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext deleteOrder(RequestContext request , String orderId) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + +} + diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java new file mode 100644 index 000000000000..3ca4fa0e3941 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java @@ -0,0 +1,73 @@ +package io.swagger.handler; + +import io.swagger.inflector.models.RequestContext; +import io.swagger.inflector.models.ResponseContext; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import java.io.File; +import java.util.List; + +import io.swagger.model.*; + +import io.swagger.model.User; +import java.util.*; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-08-24T17:25:49.737-07:00") +public class UserController { + /** + * Uncomment and implement as you see fit. These operations will map + * Direclty to operation calls from the routing logic. Because the inflector + * Code allows you to implement logic incrementally, they are disabled. + **/ + + /* + public ResponseContext createUser(RequestContext request , User body) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext createUsersWithArrayInput(RequestContext request , List body) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext createUsersWithListInput(RequestContext request , List body) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext loginUser(RequestContext request , String username, String password) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext logoutUser(RequestContext request ) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext getUserByName(RequestContext request , String username) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext updateUser(RequestContext request , String username, User body) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext deleteUser(RequestContext request , String username) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + +} + diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Category.java new file mode 100644 index 000000000000..03a37fef5b09 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Category.java @@ -0,0 +1,51 @@ +package io.swagger.model; + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-08-24T17:25:49.737-07:00") +public class Category { + + private Long id = null; + private String name = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Order.java new file mode 100644 index 000000000000..de3a2f8b9eb7 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Order.java @@ -0,0 +1,112 @@ +package io.swagger.model; + +import java.util.Date; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-08-24T17:25:49.737-07:00") +public class Order { + + private Long id = null; + private Long petId = null; + private Integer quantity = null; + private Date shipDate = null; + public enum StatusEnum { + placed, approved, delivered, + }; + private StatusEnum status = null; + private Boolean complete = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("shipDate") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + + /** + * Order Status + **/ + @ApiModelProperty(value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" petId: ").append(petId).append("\n"); + sb.append(" quantity: ").append(quantity).append("\n"); + sb.append(" shipDate: ").append(shipDate).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append(" complete: ").append(complete).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Pet.java new file mode 100644 index 000000000000..eb81026f6012 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Pet.java @@ -0,0 +1,114 @@ +package io.swagger.model; + +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.*; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-08-24T17:25:49.737-07:00") +public class Pet { + + private Long id = null; + private Category category = null; + private String name = null; + private List photoUrls = new ArrayList(); + private List tags = new ArrayList(); + public enum StatusEnum { + available, pending, sold, + }; + private StatusEnum status = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("category") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" category: ").append(category).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append(" photoUrls: ").append(photoUrls).append("\n"); + sb.append(" tags: ").append(tags).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Tag.java new file mode 100644 index 000000000000..8c8f2597461d --- /dev/null +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Tag.java @@ -0,0 +1,51 @@ +package io.swagger.model; + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-08-24T17:25:49.737-07:00") +public class Tag { + + private Long id = null; + private String name = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/User.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/User.java new file mode 100644 index 000000000000..be5261cdb70e --- /dev/null +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/User.java @@ -0,0 +1,136 @@ +package io.swagger.model; + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-08-24T17:25:49.737-07:00") +public class User { + + private Long id = null; + private String username = null; + private String firstName = null; + private String lastName = null; + private String email = null; + private String password = null; + private String phone = null; + private Integer userStatus = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("username") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("lastName") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("email") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("phone") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + + /** + * User Status + **/ + @ApiModelProperty(value = "User Status") + @JsonProperty("userStatus") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" username: ").append(username).append("\n"); + sb.append(" firstName: ").append(firstName).append("\n"); + sb.append(" lastName: ").append(lastName).append("\n"); + sb.append(" email: ").append(email).append("\n"); + sb.append(" password: ").append(password).append("\n"); + sb.append(" phone: ").append(phone).append("\n"); + sb.append(" userStatus: ").append(userStatus).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/java-inflector/src/main/swagger/swagger.json b/samples/server/petstore/java-inflector/src/main/swagger/swagger.json new file mode 100644 index 000000000000..36ecd60503e0 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/main/swagger/swagger.json @@ -0,0 +1,770 @@ +{ + "swagger" : "2.0", + "info" : { + "description" : "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. 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", + "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/json", "application/xml" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "Pet object that needs to be added to the store", + "required" : false, + "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/json", "application/xml" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "Pet object that needs to be added to the store", + "required" : false, + "schema" : { + "$ref" : "#/definitions/Pet" + } + } ], + "responses" : { + "405" : { + "description" : "Validation exception" + }, + "404" : { + "description" : "Pet not found" + }, + "400" : { + "description" : "Invalid ID supplied" + } + }, + "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/json", "application/xml" ], + "parameters" : [ { + "name" : "status", + "in" : "query", + "description" : "Status values that need to be considered for filter", + "required" : false, + "type" : "array", + "items" : { + "type" : "string" + }, + "collectionFormat" : "multi", + "default" : "available" + } ], + "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/json", "application/xml" ], + "parameters" : [ { + "name" : "tags", + "in" : "query", + "description" : "Tags to filter by", + "required" : false, + "type" : "array", + "items" : { + "type" : "string" + }, + "collectionFormat" : "multi" + } ], + "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 pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", + "operationId" : "getPetById", + "produces" : [ "application/json", "application/xml" ], + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet that needs to be fetched", + "required" : true, + "type" : "integer", + "format" : "int64" + } ], + "responses" : { + "404" : { + "description" : "Pet not found" + }, + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/Pet" + } + }, + "400" : { + "description" : "Invalid ID supplied" + } + }, + "security" : [ { + "api_key" : [ ] + }, { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + }, + "post" : { + "tags" : [ "pet" ], + "summary" : "Updates a pet in the store with form data", + "description" : "", + "operationId" : "updatePetWithForm", + "consumes" : [ "application/x-www-form-urlencoded" ], + "produces" : [ "application/json", "application/xml" ], + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet that needs to be updated", + "required" : true, + "type" : "string" + }, { + "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/json", "application/xml" ], + "parameters" : [ { + "name" : "api_key", + "in" : "header", + "description" : "", + "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", "application/xml" ], + "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" : { + "default" : { + "description" : "successful operation" + } + }, + "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", "application/xml" ], + "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/json", "application/xml" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "order placed for purchasing the pet", + "required" : false, + "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/json", "application/xml" ], + "parameters" : [ { + "name" : "orderId", + "in" : "path", + "description" : "ID of pet that needs to be fetched", + "required" : true, + "type" : "string" + } ], + "responses" : { + "404" : { + "description" : "Order not found" + }, + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/Order" + } + }, + "400" : { + "description" : "Invalid ID supplied" + } + } + }, + "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/json", "application/xml" ], + "parameters" : [ { + "name" : "orderId", + "in" : "path", + "description" : "ID of the order that needs to be deleted", + "required" : true, + "type" : "string" + } ], + "responses" : { + "404" : { + "description" : "Order not found" + }, + "400" : { + "description" : "Invalid ID supplied" + } + } + } + }, + "/user" : { + "post" : { + "tags" : [ "user" ], + "summary" : "Create user", + "description" : "This can only be done by the logged in user.", + "operationId" : "createUser", + "produces" : [ "application/json", "application/xml" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "Created user object", + "required" : false, + "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/json", "application/xml" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "List of user object", + "required" : false, + "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/json", "application/xml" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "List of user object", + "required" : false, + "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/json", "application/xml" ], + "parameters" : [ { + "name" : "username", + "in" : "query", + "description" : "The user name for login", + "required" : false, + "type" : "string" + }, { + "name" : "password", + "in" : "query", + "description" : "The password for login in clear text", + "required" : false, + "type" : "string" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "type" : "string" + } + }, + "400" : { + "description" : "Invalid username/password supplied" + } + } + } + }, + "/user/logout" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Logs out current logged in user session", + "description" : "", + "operationId" : "logoutUser", + "produces" : [ "application/json", "application/xml" ], + "parameters" : [ ], + "responses" : { + "default" : { + "description" : "successful operation" + } + } + } + }, + "/user/{username}" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Get user by user name", + "description" : "", + "operationId" : "getUserByName", + "produces" : [ "application/json", "application/xml" ], + "parameters" : [ { + "name" : "username", + "in" : "path", + "description" : "The name that needs to be fetched. Use user1 for testing. ", + "required" : true, + "type" : "string" + } ], + "responses" : { + "404" : { + "description" : "User not found" + }, + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/User" + }, + "examples" : { + "application/json" : { + "id" : 1, + "username" : "johnp", + "firstName" : "John", + "lastName" : "Public", + "email" : "johnp@swagger.io", + "password" : "-secret-", + "phone" : "0123456789", + "userStatus" : 0 + } + } + }, + "400" : { + "description" : "Invalid username supplied" + } + } + }, + "put" : { + "tags" : [ "user" ], + "summary" : "Updated user", + "description" : "This can only be done by the logged in user.", + "operationId" : "updateUser", + "produces" : [ "application/json", "application/xml" ], + "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" : false, + "schema" : { + "$ref" : "#/definitions/User" + } + } ], + "responses" : { + "404" : { + "description" : "User not found" + }, + "400" : { + "description" : "Invalid user supplied" + } + } + }, + "delete" : { + "tags" : [ "user" ], + "summary" : "Delete user", + "description" : "This can only be done by the logged in user.", + "operationId" : "deleteUser", + "produces" : [ "application/json", "application/xml" ], + "parameters" : [ { + "name" : "username", + "in" : "path", + "description" : "The name that needs to be deleted", + "required" : true, + "type" : "string" + } ], + "responses" : { + "404" : { + "description" : "User not found" + }, + "400" : { + "description" : "Invalid username supplied" + } + } + } + } + }, + "securityDefinitions" : { + "api_key" : { + "type" : "apiKey", + "name" : "api_key", + "in" : "header" + }, + "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" + } + } + }, + "definitions" : { + "User" : { + "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" + } + }, + "Category" : { + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "xml" : { + "name" : "Category" + } + }, + "Pet" : { + "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" + } + }, + "Tag" : { + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "xml" : { + "name" : "Tag" + } + }, + "Order" : { + "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" + } + }, + "xml" : { + "name" : "Order" + } + } + } +} \ No newline at end of file diff --git a/samples/server/petstore/java-inflector/src/main/webapp/WEB-INF/web.xml b/samples/server/petstore/java-inflector/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 000000000000..34a2eea6bcfa --- /dev/null +++ b/samples/server/petstore/java-inflector/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,24 @@ + + + + swagger-inflector + org.glassfish.jersey.servlet.ServletContainer + + javax.ws.rs.Application + io.swagger.inflector.SwaggerInflector + + 1 + + + swagger-inflector + /* + + + CORSFilter + io.swagger.inflector.utils.CORSFilter + + + CORSFilter + /* + + \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/pom.xml b/samples/server/petstore/jaxrs/pom.xml index cac2f6daf795..ae9f3e06162f 100644 --- a/samples/server/petstore/jaxrs/pom.xml +++ b/samples/server/petstore/jaxrs/pom.xml @@ -119,13 +119,12 @@ jersey-server ${jersey-version} - - org.scalatest - scalatest_2.9.1 - ${scala-test-version} - test + javax.servlet + servlet-api + ${servlet-api-version} + junit junit @@ -133,9 +132,30 @@ test - javax.servlet - servlet-api - ${servlet-api-version} + com.sun.jersey + jersey-client + ${jersey-version} + test + + + org.testng + testng + 6.8.8 + test + + + junit + junit + + + snakeyaml + org.yaml + + + bsh + org.beanshell + + @@ -148,11 +168,10 @@ - 1.5.0 + 1.5.3 9.2.9.v20150224 - 1.13 + 1.18.1 1.6.3 - 1.6.1 4.8.1 2.5 diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java index cae767c0393f..300636842ba1 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java @@ -1,5 +1,6 @@ package io.swagger.api; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java index c2eeacf13d3f..e7ad9b521ac4 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java @@ -5,8 +5,8 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") public class ApiOriginFilter implements javax.servlet.Filter { - @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) response; @@ -16,11 +16,7 @@ public class ApiOriginFilter implements javax.servlet.Filter { chain.doFilter(request, response); } - @Override - public void destroy() { - } + public void destroy() {} - @Override - public void init(FilterConfig filterConfig) throws ServletException { - } + public void init(FilterConfig filterConfig) throws ServletException {} } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java index 9e5b0ee44e2d..6d6958c1c907 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java @@ -3,6 +3,7 @@ package io.swagger.api; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java index 9c8410e47ab8..c3eab326e644 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java @@ -1,5 +1,6 @@ package io.swagger.api; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java index 055fa75c80bc..f583f1e64cfc 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java @@ -26,6 +26,7 @@ import javax.ws.rs.*; @io.swagger.annotations.Api(value = "/pet", description = "the pet API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") public class PetApi { private final PetApiService delegate = PetApiServiceFactory.getPetApi(); @@ -36,11 +37,11 @@ public class PetApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception"), + @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = Void.class), - @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found"), + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Void.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class) }) public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { @@ -52,7 +53,7 @@ public class PetApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input") }) + @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { @@ -64,9 +65,9 @@ public class PetApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List") @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue="available") @QueryParam("status") List status) throws NotFoundException { @@ -78,9 +79,9 @@ public class PetApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List") @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) public Response findPetsByTags(@ApiParam(value = "Tags to filter by") @QueryParam("tags") List tags) throws NotFoundException { @@ -92,11 +93,11 @@ public class PetApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found"), + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class), - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class) }) public Response getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("petId") Long petId) throws NotFoundException { @@ -108,7 +109,7 @@ public class PetApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input") }) + @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathParam("petId") String petId, @ApiParam(value = "Updated name of the pet" )@FormParam("name") String name, @@ -122,12 +123,12 @@ public class PetApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) - public Response deletePet(@ApiParam(value = "" )@HeaderParam("api_key") String apiKey, - @ApiParam(value = "Pet id to delete",required=true ) @PathParam("petId") Long petId) + public Response deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathParam("petId") Long petId, + @ApiParam(value = "" )@HeaderParam("api_key") String apiKey) throws NotFoundException { - return delegate.deletePet(apiKey,petId); + return delegate.deletePet(petId,apiKey); } @POST @Path("/{petId}/uploadImage") @@ -135,12 +136,12 @@ public class PetApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathParam("petId") Long petId, @ApiParam(value = "Additional data to pass to server" )@FormParam("additionalMetadata") String additionalMetadata, - @ApiParam(value = "file to upload") @FormDataParam("file") InputStream inputStream, - @ApiParam(value = "file detail") @FormDataParam("file") FormDataContentDisposition fileDetail) + @FormDataParam("file") InputStream inputStream, + @FormDataParam("file") FormDataContentDisposition fileDetail) throws NotFoundException { return delegate.uploadFile(petId,additionalMetadata,fileDetail); } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java index 6e8060269eb6..708dc647f911 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java @@ -18,6 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") public abstract class PetApiService { public abstract Response updatePet(Pet body) @@ -38,7 +39,7 @@ public abstract class PetApiService { public abstract Response updatePetWithForm(String petId,String name,String status) throws NotFoundException; - public abstract Response deletePet(String apiKey,Long petId) + public abstract Response deletePet(Long petId,String apiKey) throws NotFoundException; public abstract Response uploadFile(Long petId,String additionalMetadata,FormDataContentDisposition fileDetail) diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java index f5215862ba78..a487439cb3f9 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java @@ -26,6 +26,7 @@ import javax.ws.rs.*; @io.swagger.annotations.Api(value = "/store", description = "the store API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") public class StoreApi { private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); @@ -34,9 +35,9 @@ public class StoreApi { @Path("/inventory") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "map") + @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map") @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation") }) + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) public Response getInventory() throws NotFoundException { @@ -48,9 +49,9 @@ public class StoreApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ) Order body) throws NotFoundException { @@ -62,11 +63,11 @@ public class StoreApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found"), + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class), - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class) }) public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("orderId") String orderId) throws NotFoundException { @@ -78,9 +79,9 @@ public class StoreApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found"), + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Void.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class) }) public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathParam("orderId") String orderId) throws NotFoundException { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java index 5566e9c9b570..955d640d1b5f 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java @@ -18,6 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") public abstract class StoreApiService { public abstract Response getInventory() diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java index f904b77746b4..d7bde1b17534 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java @@ -26,6 +26,7 @@ import javax.ws.rs.*; @io.swagger.annotations.Api(value = "/user", description = "the user API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") public class UserApi { private final UserApiService delegate = UserApiServiceFactory.getUserApi(); @@ -36,7 +37,7 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) public Response createUser(@ApiParam(value = "Created user object" ) User body) throws NotFoundException { @@ -48,7 +49,7 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ) List body) throws NotFoundException { @@ -60,7 +61,7 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) public Response createUsersWithListInput(@ApiParam(value = "List of user object" ) List body) throws NotFoundException { @@ -72,9 +73,9 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = String.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) public Response loginUser(@ApiParam(value = "The user name for login") @QueryParam("username") String username, @ApiParam(value = "The password for login in clear text") @QueryParam("password") String password) @@ -87,7 +88,7 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) public Response logoutUser() throws NotFoundException { @@ -99,11 +100,11 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found"), + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class), - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = User.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = User.class) }) public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathParam("username") String username) throws NotFoundException { @@ -115,9 +116,9 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found"), + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class) }) public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathParam("username") String username, @ApiParam(value = "Updated user object" ) User body) @@ -130,9 +131,9 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found"), + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class) }) public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathParam("username") String username) throws NotFoundException { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java index 6a09fcd0feb5..e838a00e2829 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java @@ -18,6 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") public abstract class UserApiService { public abstract Response createUser(User body) diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java index 56f86f70737c..57666c8444b8 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") public class Category { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java index 4d0c133e9362..99b3c758473e 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") public class Order { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java index 076a8cf8142f..0b01a065022e 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java @@ -1,21 +1,22 @@ package io.swagger.model; import io.swagger.model.Category; -import java.util.*; import io.swagger.model.Tag; +import java.util.*; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") public class Pet { private Long id = null; private Category category = null; private String name = null; - private List photoUrls = new ArrayList() ; - private List tags = new ArrayList() ; + private List photoUrls = new ArrayList(); + private List tags = new ArrayList(); public enum StatusEnum { available, pending, sold, }; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java index 99dd07c00f7a..935e04025c87 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") public class Tag { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java index d5f43a4c25e8..6d6fb0c1d94e 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") public class User { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java index fb0bb2bc3ded..c3a7cbf8bf77 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java @@ -3,11 +3,13 @@ package io.swagger.api.factories; import io.swagger.api.PetApiService; import io.swagger.api.impl.PetApiServiceImpl; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T22:18:00.553-07:00") public class PetApiServiceFactory { - private final static PetApiService service = new PetApiServiceImpl(); + private final static PetApiService service = new PetApiServiceImpl(); - public static PetApiService getPetApi() { - return service; - } + public static PetApiService getPetApi() + { + return service; + } } diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java index 325f5ba7ae0c..9eb7af458dd9 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java @@ -3,11 +3,13 @@ package io.swagger.api.factories; import io.swagger.api.StoreApiService; import io.swagger.api.impl.StoreApiServiceImpl; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T22:18:00.553-07:00") public class StoreApiServiceFactory { - private final static StoreApiService service = new StoreApiServiceImpl(); + private final static StoreApiService service = new StoreApiServiceImpl(); - public static StoreApiService getStoreApi() { - return service; - } + public static StoreApiService getStoreApi() + { + return service; + } } diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java index 9a802740e2ca..2f381c6b4591 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java @@ -3,11 +3,13 @@ package io.swagger.api.factories; import io.swagger.api.UserApiService; import io.swagger.api.impl.UserApiServiceImpl; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T22:18:00.553-07:00") public class UserApiServiceFactory { - private final static UserApiService service = new UserApiServiceImpl(); + private final static UserApiService service = new UserApiServiceImpl(); - public static UserApiService getUserApi() { - return service; - } + public static UserApiService getUserApi() + { + return service; + } } diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 3af5a9cd420e..c7ee88aaf638 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -1,69 +1,80 @@ package io.swagger.api.impl; -import com.sun.jersey.core.header.FormDataContentDisposition; import io.swagger.api.*; -import io.swagger.api.NotFoundException; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + import io.swagger.model.Pet; +import java.io.File; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; -import java.util.List; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T22:18:00.553-07:00") public class PetApiServiceImpl extends PetApiService { - - @Override - public Response updatePet(Pet body) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response addPet(Pet body) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response findPetsByStatus(List status) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response findPetsByTags(List tags) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response getPetById(Long petId) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response updatePetWithForm(String petId, String name, String status) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response deletePet(String apiKey, Long petId) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response uploadFile(Long petId, String additionalMetadata, FormDataContentDisposition fileDetail) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - + + @Override + public Response updatePet(Pet body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response addPet(Pet body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response findPetsByStatus(List status) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response findPetsByTags(List tags) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getPetById(Long petId) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response updatePetWithForm(String petId,String name,String status) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response deletePet(Long petId,String apiKey) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response uploadFile(Long petId,String additionalMetadata,FormDataContentDisposition fileDetail) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + } diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 9494c3adc89f..7dbf5e75dd27 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -1,39 +1,52 @@ package io.swagger.api.impl; import io.swagger.api.*; -import io.swagger.api.NotFoundException; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.util.Map; import io.swagger.model.Order; +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + import javax.ws.rs.core.Response; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T22:18:00.553-07:00") public class StoreApiServiceImpl extends StoreApiService { - - @Override - public Response getInventory() - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response placeOrder(Order body) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response getOrderById(String orderId) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response deleteOrder(String orderId) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - + + @Override + public Response getInventory() + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response placeOrder(Order body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getOrderById(String orderId) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response deleteOrder(String orderId) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + } diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index 5a8e7a976c4b..cdbc9afed191 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -1,68 +1,80 @@ package io.swagger.api.impl; import io.swagger.api.*; -import io.swagger.api.NotFoundException; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + import io.swagger.model.User; +import java.util.*; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; -import java.util.List; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T22:18:00.553-07:00") public class UserApiServiceImpl extends UserApiService { - - @Override - public Response createUser(User body) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response createUsersWithArrayInput(List body) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response createUsersWithListInput(List body) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response loginUser(String username, String password) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response logoutUser() - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response getUserByName(String username) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response updateUser(String username, User body) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response deleteUser(String username) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - + + @Override + public Response createUser(User body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response createUsersWithArrayInput(List body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response createUsersWithListInput(List body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response loginUser(String username,String password) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response logoutUser() + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getUserByName(String username) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response updateUser(String username,User body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response deleteUser(String username) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + } diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/ApiClient.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/ApiClient.java new file mode 100644 index 000000000000..9af0c10b5439 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/ApiClient.java @@ -0,0 +1,553 @@ +package io.swagger.client; + +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.client.config.DefaultClientConfig; +import com.sun.jersey.api.client.filter.LoggingFilter; +import com.sun.jersey.api.client.WebResource.Builder; + +import com.sun.jersey.multipart.FormDataMultiPart; +import com.sun.jersey.multipart.file.FileDataBodyPart; + +import javax.ws.rs.core.Response.Status.Family; +import javax.ws.rs.core.MediaType; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Date; +import java.util.TimeZone; + +import java.net.URLEncoder; + +import java.io.IOException; +import java.io.File; +import java.io.UnsupportedEncodingException; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.text.ParseException; + +import io.swagger.client.auth.Authentication; +import io.swagger.client.auth.HttpBasicAuth; +import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.OAuth; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class ApiClient { + private Map hostMap = new HashMap(); + private Map defaultHeaderMap = new HashMap(); + private boolean debugging = false; + private String basePath = "http://petstore.swagger.io/v2"; + private JSON json = new JSON(); + + private Map authentications; + + private DateFormat dateFormat; + + public ApiClient() { + // Use ISO 8601 format for date and datetime. + // See https://en.wikipedia.org/wiki/ISO_8601 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + // Set default User-Agent. + setUserAgent("Java-Swagger"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + return this; + } + + /** + * Get the date format used to parse/format date parameters. + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + */ + public ApiClient getDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + return this; + } + + /** + * Parse the given string into Date object. + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given parameter object into string. + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection)param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /* + Format to {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) return null; + if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) return "application/json"; + if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Serialize the given Java object into string according the given + * Content-Type (only JSON is supported for now). + */ + public String serialize(Object obj, String contentType) throws ApiException { + if (contentType.startsWith("application/json")) { + return json.serialize(obj); + } else { + throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); + } + } + + /** + * Deserialize response body to Java object according to the Content-Type. + */ + public T deserialize(ClientResponse response, TypeRef returnType) throws ApiException { + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = contentTypes.get(0); + if (contentType == null) + throw new ApiException(500, "missing Content-Type in response"); + + String body; + if (response.hasEntity()) + body = (String) response.getEntity(String.class); + else + body = ""; + + if (contentType.startsWith("application/json")) { + return json.deserialize(body, returnType); + } else { + throw new ApiException(500, "can not deserialize Content-Type: " + contentType); + } + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @return The response body in type of string + */ + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + Client client = getClient(); + + StringBuilder b = new StringBuilder(); + b.append("?"); + if (queryParams != null){ + for (Pair queryParam : queryParams){ + if (!queryParam.getName().isEmpty()) { + b.append(escapeString(queryParam.getName())); + b.append("="); + b.append(escapeString(queryParam.getValue())); + b.append("&"); + } + } + } + + String querystring = b.substring(0, b.length() - 1); + + Builder builder; + if (accept == null) + builder = client.resource(basePath + path + querystring).getRequestBuilder(); + else + builder = client.resource(basePath + path + querystring).accept(accept); + + for (String key : headerParams.keySet()) { + builder = builder.header(key, headerParams.get(key)); + } + for (String key : defaultHeaderMap.keySet()) { + if (!headerParams.containsKey(key)) { + builder = builder.header(key, defaultHeaderMap.get(key)); + } + } + + String encodedFormParams = null; + if (contentType.startsWith("multipart/form-data")) { + FormDataMultiPart mp = new FormDataMultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + mp.field(param.getKey(), file.getName()); + mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE)); + } else { + mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); + } + } + body = mp; + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + encodedFormParams = this.getXWWWFormUrlencodedParams(formParams); + } + + ClientResponse response = null; + + if ("GET".equals(method)) { + response = (ClientResponse) builder.get(ClientResponse.class); + } else if ("POST".equals(method)) { + if (encodedFormParams != null) { + response = builder.type(contentType).post(ClientResponse.class, encodedFormParams); + } else if (body == null) { + response = builder.post(ClientResponse.class, null); + } else if (body instanceof FormDataMultiPart) { + response = builder.type(contentType).post(ClientResponse.class, body); + } else { + response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType)); + } + } else if ("PUT".equals(method)) { + if (encodedFormParams != null) { + response = builder.type(contentType).put(ClientResponse.class, encodedFormParams); + } else if(body == null) { + response = builder.put(ClientResponse.class, serialize(body, contentType)); + } else { + response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType)); + } + } else if ("DELETE".equals(method)) { + if (encodedFormParams != null) { + response = builder.type(contentType).delete(ClientResponse.class, encodedFormParams); + } else if(body == null) { + response = builder.delete(ClientResponse.class); + } else { + response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType)); + } + } else { + throw new ApiException(500, "unknown method type " + method); + } + + if (response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { + return null; + } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { + if (returnType == null) + return null; + else + return deserialize(response, returnType); + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { + try { + respBody = String.valueOf(response.getEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + throw new ApiException( + response.getStatusInfo().getStatusCode(), + message, + response.getHeaders(), + respBody); + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ + private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Encode the given form parameters as request body. + */ + private String getXWWWFormUrlencodedParams(Map formParams) { + StringBuilder formParamBuilder = new StringBuilder(); + + for (Entry param : formParams.entrySet()) { + String keyStr = param.getKey(); + String valueStr = parameterToString(param.getValue()); + try { + formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8")) + .append("=") + .append(URLEncoder.encode(valueStr, "utf8")); + formParamBuilder.append("&"); + } catch (UnsupportedEncodingException e) { + // move on to next + } + } + + String encodedFormParams = formParamBuilder.toString(); + if (encodedFormParams.endsWith("&")) { + encodedFormParams = encodedFormParams.substring(0, encodedFormParams.length() - 1); + } + + return encodedFormParams; + } + + /** + * Get an existing client or create a new client to handle HTTP request. + */ + private Client getClient() { + if(!hostMap.containsKey(basePath)) { + Client client = Client.create(); + if (debugging) + client.addFilter(new LoggingFilter()); + hostMap.put(basePath, client); + } + return hostMap.get(basePath); + } +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/ApiException.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/ApiException.java new file mode 100644 index 000000000000..605f8c3769d7 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/ApiException.java @@ -0,0 +1,48 @@ +package io.swagger.client; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class ApiException extends Exception { + private int code = 0; + private String message = null; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(int code, String message) { + this.code = code; + this.message = message; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this.code = code; + this.message = message; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public int getCode() { + return code; + } + + public String getMessage() { + return message; + } + + /** + * Get the HTTP response headers. + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/Configuration.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/Configuration.java new file mode 100644 index 000000000000..524006fd7bd3 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/Configuration.java @@ -0,0 +1,22 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/JSON.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/JSON.java new file mode 100644 index 000000000000..3514e41778eb --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/JSON.java @@ -0,0 +1,52 @@ +package io.swagger.client; + +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; + +import java.io.IOException; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class JSON { + private ObjectMapper mapper; + + public JSON() { + mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.registerModule(new JodaModule()); + } + + /** + * Serialize the given Java object into JSON string. + */ + public String serialize(Object obj) throws ApiException { + try { + if (obj != null) + return mapper.writeValueAsString(obj); + else + return null; + } catch (Exception e) { + throw new ApiException(400, e.getMessage()); + } + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, TypeRef returnType) throws ApiException { + JavaType javaType = mapper.constructType(returnType.getType()); + try { + return mapper.readValue(body, javaType); + } catch (IOException e) { + if (returnType.getType().equals(String.class)) + return (T) body; + else + throw new ApiException(500, e.getMessage(), null, body); + } + } +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/Pair.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/Pair.java new file mode 100644 index 000000000000..e7dd3350637d --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/Pair.java @@ -0,0 +1,39 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/StringUtil.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/StringUtil.java new file mode 100644 index 000000000000..c80bc8a1647c --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/StringUtil.java @@ -0,0 +1,42 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

+ * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/TypeRef.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/TypeRef.java new file mode 100644 index 000000000000..15eb3ea05bad --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/TypeRef.java @@ -0,0 +1,26 @@ +package io.swagger.client; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class TypeRef { + private final Type type; + + public TypeRef() { + this.type = getGenericType(getClass()); + } + + private static Type getGenericType(Class klass) { + Type superclass = klass.getGenericSuperclass(); + if (superclass instanceof Class) { + throw new RuntimeException("No type parameter provided"); + } + ParameterizedType parameterized = (ParameterizedType) superclass; + return parameterized.getActualTypeArguments()[0]; + } + + public Type getType() { + return type; + } +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/PetApi.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/PetApi.java new file mode 100644 index 000000000000..5b71f7c199cb --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,407 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.TypeRef; + +import io.swagger.client.model.*; + +import java.util.*; + +import io.swagger.client.model.Pet; +import java.io.File; + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + * @return void + */ + public void updatePet (Pet body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + "application/json", "application/xml" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + * @return void + */ + public void addPet (Pet body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + "application/json", "application/xml" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + * @return List + */ + public List findPetsByStatus (List status) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + queryParams.addAll(apiClient.parameterToPairs("multi", "status", status)); + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + TypeRef returnType = new TypeRef>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @return List + */ + public List findPetsByTags (List tags) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + queryParams.addAll(apiClient.parameterToPairs("multi", "tags", tags)); + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + TypeRef returnType = new TypeRef>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @return Pet + */ + public Pet getPetById (Long petId) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); + } + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "api_key", "petstore_auth" }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @return void + */ + public void updatePetWithForm (String petId, String name, String status) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); + } + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + if (name != null) + formParams.put("name", name); + if (status != null) + formParams.put("status", status); + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + "application/x-www-form-urlencoded" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + * @return void + */ + public void deletePet (Long petId, String apiKey) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); + } + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + if (apiKey != null) + headerParams.put("api_key", apiClient.parameterToString(apiKey)); + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @return void + */ + public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); + } + + + // create path and map variables + String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + if (additionalMetadata != null) + formParams.put("additionalMetadata", additionalMetadata); + if (file != null) + formParams.put("file", file); + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + "multipart/form-data" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/StoreApi.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 000000000000..7c0430b5f718 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,215 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.TypeRef; + +import io.swagger.client.model.*; + +import java.util.*; + +import java.util.Map; +import io.swagger.client.model.Order; + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map + */ + public Map getInventory () throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/store/inventory".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "api_key" }; + + TypeRef returnType = new TypeRef>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return Order + */ + public Order placeOrder (Order body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/store/order".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @return Order + */ + public Order getOrderById (String orderId) throws ApiException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); + } + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + * @return void + */ + public void deleteOrder (String orderId) throws ApiException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); + } + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/UserApi.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/UserApi.java new file mode 100644 index 000000000000..a11ac7d16ed1 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,386 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.TypeRef; + +import io.swagger.client.model.*; + +import java.util.*; + +import io.swagger.client.model.User; +import java.util.*; + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @return void + */ + public void createUser (User body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + */ + public void createUsersWithArrayInput (List body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + */ + public void createUsersWithListInput (List body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user/createWithList".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return String + */ + public String loginUser (String username, String password) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/user/login".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + queryParams.addAll(apiClient.parameterToPairs("", "username", username)); + + queryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Logs out current logged in user session + * + * @return void + */ + public void logoutUser () throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/user/logout".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + */ + public User getUserByName (String username) throws ApiException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + * @return void + */ + public void updateUser (String username, User body) throws ApiException { + Object postBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @return void + */ + public void deleteUser (String username) throws ApiException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 000000000000..41094d084401 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,59 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location == "query") { + queryParams.add(new Pair(paramName, value)); + } else if (location == "header") { + headerParams.put(paramName, value); + } + } +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/Authentication.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/Authentication.java new file mode 100644 index 000000000000..5585eecdf1e2 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/Authentication.java @@ -0,0 +1,12 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public interface Authentication { + /** Apply authentication settings to header and query params. */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 000000000000..740d8993862d --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/HttpBasicAuth.java @@ -0,0 +1,41 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; +import javax.xml.bind.DatatypeConverter; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + try { + headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/OAuth.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 000000000000..b592d67848f7 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/OAuth.java @@ -0,0 +1,14 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class OAuth implements Authentication { + @Override + public void applyToParams(List queryParams, Map headerParams) { + // TODO: support oauth + } +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Category.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Category.java new file mode 100644 index 000000000000..0d1945b5804f --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Category.java @@ -0,0 +1,53 @@ +package io.swagger.client.model; + + + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class Category { + + private Long id = null; + private String name = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Order.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Order.java similarity index 93% rename from samples/client/petstore/java/src/main/java/io/swagger/client/model/Order.java rename to samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Order.java index 25864d8c9cc8..2a3892f29181 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Order.java +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Order.java @@ -2,12 +2,15 @@ package io.swagger.client.model; import java.util.Date; + + import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -public class Order { +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class Order { private Long id = null; private Long petId = null; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Pet.java similarity index 93% rename from samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java rename to samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Pet.java index d7c2038dead8..6cb7df1fde58 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Pet.java @@ -4,12 +4,15 @@ import io.swagger.client.model.Category; import io.swagger.client.model.Tag; import java.util.*; + + import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -public class Pet { +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class Pet { private Long id = null; private Category category = null; diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Tag.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Tag.java new file mode 100644 index 000000000000..fe212ea8ab6f --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Tag.java @@ -0,0 +1,53 @@ +package io.swagger.client.model; + + + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class Tag { + + private Long id = null; + private String name = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/User.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/User.java new file mode 100644 index 000000000000..5b9230b8e015 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/User.java @@ -0,0 +1,138 @@ +package io.swagger.client.model; + + + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +public class User { + + private Long id = null; + private String username = null; + private String firstName = null; + private String lastName = null; + private String email = null; + private String password = null; + private String phone = null; + private Integer userStatus = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("username") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("lastName") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("email") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("phone") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + + /** + * User Status + **/ + @ApiModelProperty(value = "User Status") + @JsonProperty("userStatus") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" username: ").append(username).append("\n"); + sb.append(" firstName: ").append(firstName).append("\n"); + sb.append(" lastName: ").append(lastName).append("\n"); + sb.append(" email: ").append(email).append("\n"); + sb.append(" password: ").append(password).append("\n"); + sb.append(" phone: ").append(phone).append("\n"); + sb.append(" userStatus: ").append(userStatus).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/test/integration/ResourceListingTestIT.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/test/integration/ResourceListingTestIT.java new file mode 100644 index 000000000000..f2b6ffffa68e --- /dev/null +++ b/samples/server/petstore/jaxrs/src/test/java/io/swagger/test/integration/ResourceListingTestIT.java @@ -0,0 +1,85 @@ +/* + * Copyright 2015 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 io.swagger.test.integration; + +import io.swagger.client.ApiClient; +import io.swagger.client.Pair; +import io.swagger.client.TypeRef; +import io.swagger.models.Operation; +import io.swagger.models.Response; +import io.swagger.models.Swagger; +import io.swagger.models.parameters.Parameter; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.util.Json; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import static org.testng.Assert.*; + +public class ResourceListingTestIT { + ApiClient client = new ApiClient(); + Swagger swagger = null; + + @BeforeClass + public void setup() throws Exception { + TypeRef ref = new TypeRef(){}; + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + String str = client.invokeAPI("/swagger.json", "GET", queryParams, null, headerParams, formParams, "application/json", "", new String[0], ref); + swagger = Json.mapper().readValue(str, Swagger.class); + assertNotNull(swagger); + } + + @Test + public void verifyFileInput() throws Exception { + Operation op = swagger.getPath("/pet/{petId}/uploadImage").getPost(); + List parameters = op.getParameters(); + Parameter petId = parameters.get(0); + assertEquals(petId.getName(), "petId"); + assertEquals(petId.getIn(), "path"); + + Parameter additionalMetadata = parameters.get(1); + assertEquals(additionalMetadata.getName(), "additionalMetadata"); + assertEquals(additionalMetadata.getIn(), "formData"); + + Parameter file = parameters.get(2); + assertEquals(file.getName(), "file"); + assertEquals(file.getIn(), "formData"); + } + + @Test + public void verifyMapResponse() throws Exception { + Operation op = swagger.getPath("/store/inventory").getGet(); + Response response = op.getResponses().get("200"); + + Property property = response.getSchema(); + assertTrue(property instanceof MapProperty); + + MapProperty mp = (MapProperty) property; + assertTrue(mp.getAdditionalProperties() instanceof IntegerProperty); + } +} \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc/pom.xml b/samples/server/petstore/spring-mvc/pom.xml index 1b49d0a46918..ad0b2c04acff 100644 --- a/samples/server/petstore/spring-mvc/pom.xml +++ b/samples/server/petstore/spring-mvc/pom.xml @@ -150,7 +150,7 @@ - 1.5.0 + 1.5.3 9.2.9.v20150224 1.13 1.6.3 diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java index cae767c0393f..d5cc468f9183 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java @@ -1,5 +1,6 @@ package io.swagger.api; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java index c2eeacf13d3f..4e9fe92b80ca 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -5,6 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") public class ApiOriginFilter implements javax.servlet.Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java index 9e5b0ee44e2d..5b1085f05d46 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -3,6 +3,7 @@ package io.swagger.api; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java index 9c8410e47ab8..04c8e861b3af 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java @@ -1,5 +1,6 @@ package io.swagger.api; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index 52ddc63c23cb..ae26430d13e8 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -30,6 +30,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/pet", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/pet", description = "the pet API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") public class PetApi { @@ -77,12 +78,12 @@ public class PetApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue = "available") @RequestParam(value = "status", required = false, defaultValue="available") List status + public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue = "available") @RequestParam(value = "status", required = false, defaultValue="available") List status ) throws NotFoundException { // do some magic! - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.OK); } @@ -95,12 +96,12 @@ public class PetApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity findPetsByTags(@ApiParam(value = "Tags to filter by") @RequestParam(value = "tags", required = false) List tags + public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by") @RequestParam(value = "tags", required = false) List tags ) throws NotFoundException { // do some magic! - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.OK); } @@ -157,10 +158,10 @@ public class PetApi { method = RequestMethod.DELETE) public ResponseEntity deletePet( -@ApiParam(value = "" ) @RequestHeader(value="apiKey", required=false) String apiKey +@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId , -@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId +@ApiParam(value = "" ) @RequestHeader(value="apiKey", required=false) String apiKey ) throws NotFoundException { // do some magic! diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java index c81693887db1..1da00f9bfa72 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java @@ -30,20 +30,21 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/store", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/store", description = "the store API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") public class StoreApi { - @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "map") + @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map") @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/inventory", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity getInventory() + public ResponseEntity> getInventory() throws NotFoundException { // do some magic! - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity>(HttpStatus.OK); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java index dd5fbc6c279e..13ef255488bb 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java @@ -30,6 +30,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/user", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/user", description = "the user API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") public class UserApi { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java index 7b2de09cdd61..d15249c8d74f 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java @@ -18,6 +18,7 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2; @EnableSwagger2 //Loads the spring beans required by the framework @PropertySource("classpath:swagger.properties") @Import(SwaggerUiConfiguration.class) +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") public class SwaggerConfig { @Bean ApiInfo apiInfo() { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java index ff8f366a880d..2732a7c04917 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java @@ -8,6 +8,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration @EnableWebMvc +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter { private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" }; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java index 05f7dae29ec2..1799d0da80aa 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java @@ -2,6 +2,7 @@ package io.swagger.configuration; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") public class WebApplication extends AbstractAnnotationConfigDispatcherServletInitializer { @Override diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java index 206e011dd487..629e5580e64b 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java @@ -3,6 +3,7 @@ package io.swagger.configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") public class WebMvcConfiguration extends WebMvcConfigurationSupport { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java index 56f86f70737c..734f3b75e79a 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") public class Category { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java index 4d0c133e9362..d58ff96620d1 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") public class Order { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java index 076a8cf8142f..a86d7296ec7d 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java @@ -1,21 +1,22 @@ package io.swagger.model; import io.swagger.model.Category; -import java.util.*; import io.swagger.model.Tag; +import java.util.*; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") public class Pet { private Long id = null; private Category category = null; private String name = null; - private List photoUrls = new ArrayList() ; - private List tags = new ArrayList() ; + private List photoUrls = new ArrayList(); + private List tags = new ArrayList(); public enum StatusEnum { available, pending, sold, }; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java index 99dd07c00f7a..d87fc671fbb7 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") public class Tag { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java index d5f43a4c25e8..1ef45c4bc669 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") public class User { private Long id = null;