diff --git a/.gitignore b/.gitignore index 5146bf4950..240fed40de 100644 --- a/.gitignore +++ b/.gitignore @@ -48,6 +48,7 @@ atlassian-ide-plugin.xml packages/ .pub .packages +.vagrant/ samples/client/petstore/php/SwaggerClient-php/composer.lock samples/client/petstore/php/SwaggerClient-php/vendor/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9309b70418..7758d8166d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,7 +2,7 @@ ## Before submitting an issue - - Before submitting an issue, search the [open issue](https://github.com/swagger-api/swagger-codegen/issues) and [closed issue](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aissue+is%3Aclosed) to ensure no one else has reported something similar before. + - Search the [open issue](https://github.com/swagger-api/swagger-codegen/issues) and [closed issue](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aissue+is%3Aclosed) to ensure no one else has reported something similar before. - The issue should contain details on how to repeat the issue, e.g. - the OpenAPI Spec for reproducing the issue (:bulb: use [Gist](https://gist.github.com) to share). If the OpenAPI Spec cannot be shared publicly, it will be hard for the community to help - version of Swagger Codegen @@ -31,7 +31,7 @@ For a list of variables available in the template, please refer to this [page](h Code change should conform to the programming style guide of the respective langauages: - C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx - Java: https://google.github.io/styleguide/javaguide.html -- JavaScript - https://github.com/airbnb/javascript +- JavaScript - https://github.com/airbnb/javascript/tree/master/es5 - ObjC: https://github.com/NYTimes/objective-c-style-guide - PHP: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md - Python: https://www.python.org/dev/peps/pep-0008/ diff --git a/README.md b/README.md index 9bd5fdb01f..3e7fec5177 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,13 @@ # Swagger Code Generator -[![Build Status](https://travis-ci.org/swagger-api/swagger-codegen.png)](https://travis-ci.org/swagger-api/swagger-codegen) +[![Build Status](https://travis-ci.org/swagger-api/swagger-codegen.svg)](https://travis-ci.org/swagger-api/swagger-codegen) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project/badge.svg?style=plastic)](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project) +[![PR Stats](http://issuestats.com/github/swagger-api/swagger-codegen/badge/pr)](http://issuestats.com/github/swagger-api/swagger-codegen) [![Issue Stats](http://issuestats.com/github/swagger-api/swagger-codegen/badge/issue)](http://issuestats.com/github/swagger-api/swagger-codegen) :star::star::star: If you would like to contribute, please refer to [guidelines](https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md) and a list of [open tasks](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aopen+is%3Aissue+label%3A%22Need+community+contribution%22).:star::star::star: ## Overview -This is the swagger codegen project, which allows generation of client libraries automatically from a Swagger-compliant server. +This is the swagger codegen project, which allows generation of client libraries automatically from a Swagger-compliant server. Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more. @@ -22,7 +23,7 @@ Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for addit - [Building](#building) - [Docker](#docker) - [Build and run](#build-and-run-using-docker) - - [Build a Node.js server stub](#build-a-nodejs-server-stub) + - [Run docker in Vagrant](#run-docker-in-vagrant) - [Public Docker image](#public-docker-image) - [Homebrew](#homebrew) - Generators @@ -103,19 +104,21 @@ mvn package ``` git clone https://github.com/swagger-api/swagger-codegen - cd swagger-codegen - ./run-in-docker.sh mvn package ``` -#### Build a Node.js server stub + +#### Run Docker in Vagrant +Prerequisite: install [Vagrant](https://www.vagrantup.com/downloads.html) and [VirtualBox](https://www.virtualbox.org/wiki/Downloads). ``` -./run-in-docker.sh generate \ - -i http://petstore.swagger.io/v2/swagger.json \ - -l nodejs \ - -o samples/server/petstore/nodejs +git clone http://github.com/swagger-api/swagger-codegen.git +cd swagger-codegen +vagrant up +vagrant ssh +cd /vagrant +sudo ./run-in-docker.sh mvn package ``` #### Public Docker image @@ -351,7 +354,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -o samples/client/petstore/java \ -c path/to/config.json ``` -Supported config options can be different per language. Running `config-help -l {lang}` will show available options. **These options are applied +Supported config options can be different per language. Running `config-help -l {lang}` will show available options. **These options are applied by passing them with `-D{optionName}={optionValue}**. ``` @@ -402,12 +405,12 @@ CONFIG OPTIONS retrofit2 - HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2) ``` -Your config file for java can look like +Your config file for Java can look like -``` +```json { "groupId":"com.my.company", - "artifactId":"MyClent", + "artifactId":"MyClient", "artifactVersion":"1.2.0", "library":"feign" } @@ -418,15 +421,15 @@ For all the unspecified options default values will be used. Another way to override default options is to extend the config class for the specific language. To change, for example, the prefix for the Objective-C generated files, simply subclass the ObjcClientCodegen.java: -``` +```java package com.mycompany.swagger.codegen; import io.swagger.codegen.languages.*; public class MyObjcCodegen extends ObjcClientCodegen { - static { - PREFIX = "HELO"; - } + static { + PREFIX = "HELO"; + } } ``` @@ -512,7 +515,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ ``` java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -i http://petstore.swagger.io/v2/swagger.json \ - -l flaskConnexion \ + -l python-flask \ -o samples/server/petstore/flaskConnexion ``` @@ -533,13 +536,22 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -o samples/server/petstore/scalatra ``` -### Java JAX-RS +### Java JAX-RS (Jersey v1.18) ``` java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -i http://petstore.swagger.io/v2/swagger.json \ -l jaxrs \ - -o samples/server/petstore/jaxrs + -o samples/server/petstore/jaxrs-jersey +``` + +### Java JAX-RS (Apache CXF 3) + +``` +java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ + -i http://petstore.swagger.io/v2/swagger.json \ + -l jaxrs-cxf \ + -o samples/server/petstore/jaxrs-cxf ``` ### Java Spring MVC @@ -553,7 +565,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ ### To build the codegen library -This will create the swagger-codegen library from source. +This will create the swagger-codegen library from source. ``` mvn package diff --git a/Vagrantfile b/Vagrantfile new file mode 100644 index 0000000000..a914db0a1e --- /dev/null +++ b/Vagrantfile @@ -0,0 +1,34 @@ +# -*- mode: ruby -*- +# vi: set ft=ruby : + +# Vagrantfile API/syntax version. Don't touch unless you know what you're doing! +VAGRANTFILE_API_VERSION = "2" + +Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| + + config.vm.box = "ubuntu/trusty64" + + config.vm.provider "virtualbox" do |v| + v.name = "swagger-codegen" + v.memory = 2048 + v.cpus = 2 + end + + config.vm.box_check_update = true + + #SSH + config.ssh.forward_agent = true + + config.ssh.shell = "bash -c 'BASH_ENV=/etc/profile exec bash'" + + #Provision + config.vm.provision "shell", inline: <<-SHELL + sudo apt-key adv --keyserver hkp://pgp.mit.edu:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D + sudo sh -c 'echo "deb https://apt.dockerproject.org/repo ubuntu-trusty main" > /etc/apt/sources.list.d/docker.list' + sudo apt-cache policy docker-engine + sudo apt-get update + sudo apt-get upgrade -y + sudo apt-get install -y docker-engine + SHELL + +end diff --git a/bin/go-petstore.sh b/bin/go-petstore.sh new file mode 100644 index 0000000000..239f31f0d7 --- /dev/null +++ b/bin/go-petstore.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 -t modules/swagger-codegen/src/main/resources/go -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l go -o samples/client/petstore/go" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-retrofit2rx.json b/bin/java-petstore-retrofit2rx.json new file mode 100644 index 0000000000..c9e4301f2d --- /dev/null +++ b/bin/java-petstore-retrofit2rx.json @@ -0,0 +1,4 @@ +{ + "library": "retrofit2", + "artifactId": "swagger-petstore-retrofit2-rx" +} diff --git a/bin/java-petstore-retrofit2rx.sh b/bin/java-petstore-retrofit2rx.sh new file mode 100755 index 0000000000..b032064414 --- /dev/null +++ b/bin/java-petstore-retrofit2rx.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-retrofit2rx.json -o samples/client/petstore/java/retrofit2rx -DuseRxJava=true" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-cxf-petstore-server.sh b/bin/jaxrs-cxf-petstore-server.sh new file mode 100755 index 0000000000..8049dde563 --- /dev/null +++ b/bin/jaxrs-cxf-petstore-server.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 -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l jaxrs-cxf -o samples/server/petstore/jaxrs-cxf" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/windows/go-petstore.bat b/bin/windows/go-petstore.bat new file mode 100644 index 0000000000..050bfd23cc --- /dev/null +++ b/bin/windows/go-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\go -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l go -o samples\client\petstore\go + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/swagger-codegen-cli/pom.xml b/modules/swagger-codegen-cli/pom.xml index 9100143a23..c118a6325e 100644 --- a/modules/swagger-codegen-cli/pom.xml +++ b/modules/swagger-codegen-cli/pom.xml @@ -89,13 +89,13 @@ org.testng testng - ${testng-version} + test org.jmockit jmockit - ${jmockit-version} + test diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java index 502e4d046b..98c0b8c05b 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java @@ -21,6 +21,7 @@ public class SwaggerCodegen { public static void main(String[] args) { + @SuppressWarnings("unchecked") Cli.CliBuilder builder = Cli.builder("swagger-codegen-cli") .withDescription("Swagger code generator CLI. More info on swagger.io") .withDefaultCommand(Langs.class) 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 d72295f4ca..04d60e2ec8 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 @@ -5,7 +5,7 @@ import io.airlift.airline.Option; import io.swagger.codegen.ClientOptInput; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.DefaultGenerator; -import io.swagger.codegen.cmd.utils.OptionUtils; +import io.swagger.codegen.utils.OptionUtils; import io.swagger.codegen.config.CodegenConfigurator; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; @@ -230,15 +230,15 @@ public class Generate implements Runnable { } } - private Set createSetFromCsvList(String csvProperty) { + private static Set createSetFromCsvList(String csvProperty) { final List values = OptionUtils.splitCommaSeparatedList(csvProperty); return new HashSet(values); } - private Map createMapFromKeyValuePairs(String commaSeparatedKVPairs) { + private static Map createMapFromKeyValuePairs(String commaSeparatedKVPairs) { final List> pairs = OptionUtils.parseCommaSeparatedTuples(commaSeparatedKVPairs); - Map result = new HashMap(); + Map result = new HashMap(); for (Pair pair : pairs) { result.put(pair.getLeft(), pair.getRight()); diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java index 9843024b10..c2dffbe620 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java @@ -33,7 +33,7 @@ import static com.google.common.base.Joiner.on; "specify, and includes default templates to include.") public class Meta implements Runnable { - private static final Logger LOG = LoggerFactory.getLogger(Meta.class); + private static final Logger LOGGER = LoggerFactory.getLogger(Meta.class); private static final String TEMPLATE_DIR_CLASSPATH = "codegen"; private static final String MUSTACHE_EXTENSION = ".mustache"; @@ -53,7 +53,7 @@ public class Meta implements Runnable { @Override public void run() { final File targetDir = new File(outputFolder); - LOG.info("writing to folder [{}]", targetDir.getAbsolutePath()); + LOGGER.info("writing to folder [{}]", targetDir.getAbsolutePath()); String mainClass = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name) + "Generator"; @@ -93,7 +93,7 @@ public class Meta implements Runnable { * @param data - map with additional params needed to process templates * @return converter object to pass to lambdaj */ - private Converter processFiles(final File targetDir, final Map data) { + private static Converter processFiles(final File targetDir, final Map data) { return new Converter() { private DefaultGenerator generator = new DefaultGenerator(); @@ -108,13 +108,13 @@ public class Meta implements Runnable { String formatted = template; if (support.templateFile.endsWith(MUSTACHE_EXTENSION)) { - LOG.info("writing file to {}", outputFile.getAbsolutePath()); + LOGGER.info("writing file to {}", outputFile.getAbsolutePath()); formatted = Mustache.compiler().withLoader(loader(generator)) .defaultValue("") .compile(template) .execute(data); } else { - LOG.info("copying file to {}", outputFile.getAbsolutePath()); + LOGGER.info("copying file to {}", outputFile.getAbsolutePath()); } FileUtils.writeStringToFile(outputFile, formatted); @@ -133,7 +133,7 @@ public class Meta implements Runnable { * @param generator - class with reader getter * @return loader for template */ - private Mustache.TemplateLoader loader(final DefaultGenerator generator) { + private static Mustache.TemplateLoader loader(final DefaultGenerator generator) { return new Mustache.TemplateLoader() { @Override public Reader getTemplate(String name) { @@ -149,7 +149,7 @@ public class Meta implements Runnable { * @param packageName - package name to convert * @return relative path */ - private String asPath(String packageName) { + private static String asPath(String packageName) { return packageName.replace(".", File.separator); } } diff --git a/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/GenerateTest.java b/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/GenerateTest.java index e07d0be461..36a560b776 100644 --- a/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/GenerateTest.java +++ b/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/GenerateTest.java @@ -12,6 +12,7 @@ import mockit.Verifications; import org.apache.commons.lang3.ArrayUtils; import org.testng.annotations.Test; +@SuppressWarnings("unused") public class GenerateTest { @Mocked diff --git a/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/utils/OptionUtilsTest.java b/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/utils/OptionUtilsTest.java index a7dc4d7f1c..db88cdcdb9 100644 --- a/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/utils/OptionUtilsTest.java +++ b/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/utils/OptionUtilsTest.java @@ -1,5 +1,6 @@ package io.swagger.codegen.cmd.utils; +import io.swagger.codegen.utils.OptionUtils; import org.apache.commons.lang3.tuple.Pair; import org.junit.Test; @@ -10,6 +11,7 @@ import java.util.List; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; +@SuppressWarnings("static-method") public class OptionUtilsTest { @Test @@ -30,7 +32,7 @@ public class OptionUtilsTest { doTupleListTest(null, new ArrayList>()); } - private void doTupleListTest(String input, List> expectedResults) { + private static void doTupleListTest(String input, List> expectedResults) { final List> result = OptionUtils.parseCommaSeparatedTuples(input); assertNotNull(result); assertEquals(result.size(), expectedResults.size()); @@ -41,7 +43,7 @@ public class OptionUtilsTest { } } - private void doCommaSeparatedListTest(String csvStr, List expectedResults) { + private static void doCommaSeparatedListTest(String csvStr, List expectedResults) { final List result = OptionUtils.splitCommaSeparatedList(csvStr); assertNotNull(result); assertEquals(result.size(), expectedResults.size()); diff --git a/modules/swagger-codegen-maven-plugin/pom.xml b/modules/swagger-codegen-maven-plugin/pom.xml index 850ac73553..52cf252d30 100644 --- a/modules/swagger-codegen-maven-plugin/pom.xml +++ b/modules/swagger-codegen-maven-plugin/pom.xml @@ -51,7 +51,7 @@ junit junit - 4.12 + test 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 c56b86588e..f0afc2999d 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 @@ -19,8 +19,10 @@ package io.swagger.codegen.plugin; import config.Config; import config.ConfigParser; import io.swagger.codegen.*; +import io.swagger.codegen.utils.OptionUtils; import io.swagger.models.Swagger; import io.swagger.parser.SwaggerParser; +import org.apache.commons.lang3.tuple.Pair; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -30,6 +32,7 @@ import org.apache.maven.project.MavenProject; import java.io.File; import java.util.HashMap; +import java.util.List; import java.util.Map; import static io.swagger.codegen.plugin.AdditionalParams.*; @@ -99,7 +102,7 @@ public class CodeGenMojo extends AbstractMojo { * A map of language-specific parameters as passed with the -c option to the command line */ @Parameter(name = "configOptions") - private Map configOptions; + private Map configOptions; /** * Add the output directory to the project as a source root, so that the @@ -160,6 +163,20 @@ public class CodeGenMojo extends AbstractMojo { configOptions.get(langCliOption.getOpt())); } } + if(configOptions.containsKey("import-mappings")) { + Map mappings = createMapFromKeyValuePairs(configOptions.get("import-mappings").toString()); + config.importMapping().putAll(mappings); + } + + if(configOptions.containsKey("type-mappings")) { + Map mappings = createMapFromKeyValuePairs(configOptions.get("type-mappings").toString()); + config.typeMapping().putAll(mappings); + } + + if(configOptions.containsKey("instantiation-types")) { + Map mappings = createMapFromKeyValuePairs(configOptions.get("instantiation-types").toString()); + config.instantiationTypes().putAll(mappings); + } } if (null != configurationFile) { @@ -200,4 +217,16 @@ public class CodeGenMojo extends AbstractMojo { project.addCompileSourceRoot(output.toString()); } } + + private static Map createMapFromKeyValuePairs(String commaSeparatedKVPairs) { + final List> pairs = OptionUtils.parseCommaSeparatedTuples(commaSeparatedKVPairs); + + Map result = new HashMap(); + + for (Pair pair : pairs) { + result.put(pair.getLeft(), pair.getRight()); + } + + return result; + } } diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index 29d2dc4e14..a5c4eedd74 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -101,7 +101,7 @@ org.apache.maven.plugins maven-release-plugin - 2.1 + org.apache.maven.plugins @@ -256,7 +256,7 @@ org.testng testng - ${testng-version} + test @@ -268,7 +268,7 @@ org.jmockit jmockit - ${jmockit-version} + test diff --git a/modules/swagger-codegen/src/main/java/config/ConfigParser.java b/modules/swagger-codegen/src/main/java/config/ConfigParser.java index 101fbb0d25..68cbb613f3 100644 --- a/modules/swagger-codegen/src/main/java/config/ConfigParser.java +++ b/modules/swagger-codegen/src/main/java/config/ConfigParser.java @@ -7,11 +7,16 @@ import java.io.File; import java.util.Iterator; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class ConfigParser { + private static final Logger LOGGER = LoggerFactory.getLogger(ConfigParser.class); + public static Config read(String location) { - System.out.println("reading config from " + location); + LOGGER.info("reading config from " + location); ObjectMapper mapper = new ObjectMapper(); @@ -27,11 +32,11 @@ public class ConfigParser { if (optionNode.getValue().isValueNode()) { config.setOption(optionNode.getKey(), optionNode.getValue().asText()); } else { - System.out.println("omitting non-value node " + optionNode.getKey()); + LOGGER.warn("omitting non-value node " + optionNode.getKey()); } } } catch (Exception e) { - System.out.println(e.getMessage()); + LOGGER.error(e.getMessage()); return null; } 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 d6bbb9fa52..5ed0785133 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 @@ -10,12 +10,18 @@ import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; +import java.util.Scanner; import java.util.regex.Pattern; -public abstract class AbstractGenerator { +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +public abstract class AbstractGenerator { + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractGenerator.class); + + @SuppressWarnings("static-method") public File writeToFile(String filename, String contents) throws IOException { - System.out.println("writing file " + filename); + LOGGER.info("writing file " + filename); File output = new File(filename); if (output.getParent() != null && !new File(output.getParent()).exists()) { @@ -36,10 +42,10 @@ public abstract class AbstractGenerator { if (reader == null) { throw new RuntimeException("no file found"); } - java.util.Scanner s = new java.util.Scanner(reader).useDelimiter("\\A"); + Scanner s = new Scanner(reader).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e.getMessage()); } throw new RuntimeException("can't load template " + name); } @@ -48,14 +54,11 @@ public abstract class AbstractGenerator { try { InputStream is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name)); if (is == null) { - is = new FileInputStream(new File(name)); - } - if (is == null) { - throw new RuntimeException("no file found"); + is = new FileInputStream(new File(name)); // May throw but never return a null value } return new InputStreamReader(is); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e.getMessage()); } throw new RuntimeException("can't load template " + name); } @@ -96,6 +99,7 @@ public abstract class AbstractGenerator { return this.getClass().getClassLoader().getResource(getCPResourcePath(name)) != null; } + @SuppressWarnings("static-method") public String getCPResourcePath(String name) { if (!"/".equals(File.separator)) { return name.replaceAll(Pattern.quote(File.separator), "/"); 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 571498c312..57918dd9b3 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 @@ -5,13 +5,8 @@ import io.swagger.codegen.auth.AuthParser; import io.swagger.models.Swagger; import io.swagger.models.auth.AuthorizationValue; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.ArrayList; import java.util.List; -import static org.apache.commons.lang3.StringUtils.isNotEmpty; - public class ClientOptInput { private CodegenConfig config; private ClientOpts opts; 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 ffb4a0112a..649f068d16 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 @@ -1,29 +1,34 @@ package io.swagger.codegen; -import config.Config; -import config.ConfigParser; -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; -import org.apache.commons.cli.BasicParser; -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.CommandLineParser; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Options; - import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ServiceLoader; +import org.apache.commons.cli.BasicParser; +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Options; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import config.Config; +import config.ConfigParser; +import io.swagger.models.Swagger; +import io.swagger.parser.SwaggerParser; + /** * @deprecated use instead {@link io.swagger.codegen.DefaultGenerator} * or cli interface from https://github.com/swagger-api/swagger-codegen/pull/547 */ @Deprecated public class Codegen extends DefaultGenerator { + + private static final Logger LOGGER = LoggerFactory.getLogger(Codegen.class); + static Map configs = new HashMap(); static String configString; static String debugInfoOptions = "\nThe following additional debug options are available for all codegen targets:" + @@ -32,10 +37,9 @@ public class Codegen extends DefaultGenerator { "\n -DdebugOperations prints operations passed to the template engine" + "\n -DdebugSupportingFiles prints additional data passed to the template engine"; + @SuppressWarnings("deprecation") public static void main(String[] args) { - StringBuilder sb = new StringBuilder(); - Options options = new Options(); options.addOption("h", "help", false, "shows this message"); options.addOption("l", "lang", true, "client language to generate.\nAvailable languages include:\n\t[" + configString + "]"); @@ -113,7 +117,7 @@ public class Codegen extends DefaultGenerator { .swagger(swagger); new Codegen().opts(clientOptInput).generate(); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e.getMessage(), e); } } @@ -138,9 +142,9 @@ public class Codegen extends DefaultGenerator { } else { // see if it's a class try { - System.out.println("loading class " + name); - Class customClass = Class.forName(name); - System.out.println("loaded"); + LOGGER.debug("loading class " + name); + Class customClass = Class.forName(name); + LOGGER.debug("loaded"); return (CodegenConfig) customClass.newInstance(); } catch (Exception e) { throw new RuntimeException("can't load class " + name); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index 4a4f9e037e..ce0b9ea2d8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -62,4 +62,21 @@ public class CodegenConstants { public static final String OPTIONAL_ASSEMBLY_INFO = "optionalAssemblyInfo"; public static final String OPTIONAL_ASSEMBLY_INFO_DESC = "Generate AssemblyInfo.cs (Default: true)."; + public static final String USE_COLLECTION = "useCollection"; + public static final String USE_COLLECTION_DESC = "Deserialize array types to Collection instead of List."; + + public static final String RETURN_ICOLLECTION = "returnICollection"; + public static final String RETURN_ICOLLECTION_DESC = "Return ICollection instead of the concrete type."; + + public static final String OPTIONAL_PROJECT_FILE = "optionalProjectFile"; + public static final String OPTIONAL_PROJECT_FILE_DESC = "Generate {PackageName}.csproj (Default: false)."; + + public static final String OPTIONAL_PROJECT_GUID = "packageGuid"; + public static final String OPTIONAL_PROJECT_GUID_DESC = "The GUID that will be associated with the C# project"; + + public static final String MODEL_PROPERTY_NAMING = "modelPropertyNaming"; + public static final String MODEL_PROPERTY_NAMING_DESC = "Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name"; + + public static enum MODEL_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case, original} + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index c5b9231341..956e906b44 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 @@ -38,7 +38,7 @@ public class CodegenOperation { * * @return true if parameter exists, false otherwise */ - private boolean nonempty(List params) { + private static boolean nonempty(List params) { return params != null && params.size() > 0; } 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 87352907ad..d80bc38a4c 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 @@ -40,6 +40,50 @@ public class CodegenProperty { public CodegenProperty items; public Map vendorExtensions; + @Override + public int hashCode() + { + final int prime = 31; + int result = 1; + result = prime * result + ((_enum == null) ? 0 : _enum.hashCode()); + result = prime * result + ((allowableValues == null) ? 0 : allowableValues.hashCode()); + result = prime * result + ((baseName == null) ? 0 : baseName.hashCode()); + result = prime * result + ((baseType == null) ? 0 : baseType.hashCode()); + result = prime * result + ((complexType == null) ? 0 : complexType.hashCode()); + result = prime * result + ((containerType == null) ? 0 : containerType.hashCode()); + result = prime * result + ((datatype == null) ? 0 : datatype.hashCode()); + result = prime * result + ((datatypeWithEnum == null) ? 0 : datatypeWithEnum.hashCode()); + result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode()); + result = prime * result + ((defaultValueWithParam == null) ? 0 : defaultValueWithParam.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((example == null) ? 0 : example.hashCode()); + result = prime * result + ((exclusiveMaximum == null) ? 0 : exclusiveMaximum.hashCode()); + result = prime * result + ((exclusiveMinimum == null) ? 0 : exclusiveMinimum.hashCode()); + result = prime * result + ((getter == null) ? 0 : getter.hashCode()); + result = prime * result + ((hasMore == null) ? 0 : hasMore.hashCode()); + result = prime * result + ((isContainer == null) ? 0 : isContainer.hashCode()); + result = prime * result + (isEnum ? 1231 : 1237); + result = prime * result + ((isNotContainer == null) ? 0 : isNotContainer.hashCode()); + result = prime * result + ((isPrimitiveType == null) ? 0 : isPrimitiveType.hashCode()); + result = prime * result + ((isReadOnly == null) ? 0 : isReadOnly.hashCode()); + result = prime * result + ((items == null) ? 0 : items.hashCode()); + result = prime * result + ((jsonSchema == null) ? 0 : jsonSchema.hashCode()); + result = prime * result + ((max == null) ? 0 : max.hashCode()); + result = prime * result + ((maxLength == null) ? 0 : maxLength.hashCode()); + result = prime * result + ((maximum == null) ? 0 : maximum.hashCode()); + result = prime * result + ((min == null) ? 0 : min.hashCode()); + result = prime * result + ((minLength == null) ? 0 : minLength.hashCode()); + result = prime * result + ((minimum == null) ? 0 : minimum.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((pattern == null) ? 0 : pattern.hashCode()); + result = prime * result + ((required == null) ? 0 : required.hashCode()); + result = prime * result + ((secondaryParam == null) ? 0 : secondaryParam.hashCode()); + result = prime * result + ((setter == null) ? 0 : setter.hashCode()); + result = prime * result + ((unescapedDescription == null) ? 0 : unescapedDescription.hashCode()); + result = prime * result + ((vendorExtensions == null) ? 0 : vendorExtensions.hashCode()); + return result; + } + @Override public boolean equals(Object obj) { if (obj == null) { 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 f9bd468a25..a66ef6db81 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 @@ -109,38 +109,48 @@ public class DefaultCodegen { } // override with any special post-processing + @SuppressWarnings("static-method") public Map postProcessModels(Map objs) { return objs; } // override with any special post-processing + @SuppressWarnings("static-method") public Map postProcessOperations(Map objs) { return objs; } // override with any special post-processing + @SuppressWarnings("static-method") public Map postProcessSupportingFileData(Map objs) { return objs; } // override to post-process any model properties - public void postProcessModelProperty(CodegenModel model, CodegenProperty property){} + @SuppressWarnings("unused") + public void postProcessModelProperty(CodegenModel model, CodegenProperty property){ + } // override to post-process any parameters - public void postProcessParameter(CodegenParameter parameter){} + @SuppressWarnings("unused") + public void postProcessParameter(CodegenParameter parameter){ + } //override with any special handling of the entire swagger spec + @SuppressWarnings("unused") public void preprocessSwagger(Swagger swagger) { } // override with any special handling of the entire swagger spec + @SuppressWarnings("unused") public void processSwagger(Swagger swagger) { } // override with any special text escaping logic + @SuppressWarnings("static-method") public String escapeText(String input) { - if (input != null) { - input = input.trim(); + if (input != null) { + input = input.trim(); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. String output = input.replaceAll("\n", "\\\\n"); output = output.replace("\r", "\\r"); output = output.replace("\"", "\\\""); @@ -274,7 +284,7 @@ public class DefaultCodegen { } /** - * Return the file name of the Api + * Return the file name of the Api Test * * @param name the file name of the Api * @return the file name of the Api @@ -304,7 +314,7 @@ public class DefaultCodegen { } /** - * Return the capitalized file name of the model + * Return the capitalized file name of the model test * * @param name the model name * @return the file name of the model @@ -322,13 +332,14 @@ public class DefaultCodegen { public String toModelTestFilename(String name) { return initialCaps(name) + "Test"; } - + /** * Return the operation ID (method name) * * @param operationId operation ID * @return the sanitized method name */ + @SuppressWarnings("static-method") public String toOperationId(String operationId) { // throw exception if method name is empty if (StringUtils.isEmpty(operationId)) { @@ -361,7 +372,7 @@ public class DefaultCodegen { * @return the sanitized parameter name */ public String toParamName(String name) { - name = removeNonNameElementToCamelCase(name); + name = removeNonNameElementToCamelCase(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. if (reservedWords.contains(name)) { return escapeReservedWord(name); } @@ -374,6 +385,7 @@ public class DefaultCodegen { * @param property Codegen property object * @return the Enum name */ + @SuppressWarnings("static-method") public String toEnumName(CodegenProperty property) { return StringUtils.capitalize(property.name) + "Enum"; } @@ -386,6 +398,7 @@ public class DefaultCodegen { * * throws Runtime exception as reserved word is not allowed (default behavior) */ + @SuppressWarnings("static-method") public String escapeReservedWord(String name) { throw new RuntimeException("reserved word " + name + " not allowed"); } @@ -495,6 +508,7 @@ public class DefaultCodegen { * @param operation Swagger operation object * @return string presentation of the example path */ + @SuppressWarnings("static-method") public String generateExamplePath(String path, Operation operation) { StringBuilder sb = new StringBuilder(); sb.append(path); @@ -577,6 +591,7 @@ public class DefaultCodegen { * @param p Swagger property object * @return string presentation of the default value of the property */ + @SuppressWarnings("static-method") public String toDefaultValue(Property p) { if (p instanceof StringProperty) { return "null"; @@ -623,42 +638,9 @@ public class DefaultCodegen { * @param p Swagger property object * @return string presentation of the default value of the property */ + @SuppressWarnings("static-method") public String toDefaultValueWithParam(String name, Property p) { - if (p instanceof StringProperty) { - return " = data." + name + ";"; - } else if (p instanceof BooleanProperty) { - return " = data." + name + ";"; - } else if (p instanceof DateProperty) { - return " = data." + name + ";"; - } else if (p instanceof DateTimeProperty) { - return " = data." + name + ";"; - } else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return " = data." + name + ";"; - } else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return " = data." + name + ";"; - } else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return " = data." + name + ";"; - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return " = data." + name + ";"; - } else { - return " = data." + name + ";"; - } + return " = data." + name + ";"; } /** @@ -666,6 +648,7 @@ public class DefaultCodegen { * @param p Swagger property object * @return string presentation of the type **/ + @SuppressWarnings("static-method") public String getSwaggerType(Property p) { String datatype = null; if (p instanceof StringProperty && "number".equals(p.getFormat())) { @@ -694,6 +677,8 @@ public class DefaultCodegen { datatype = "map"; } else if (p instanceof DecimalProperty) { datatype = "number"; + } else if ( p instanceof UUIDProperty) { + datatype = "UUID"; } else if (p instanceof RefProperty) { try { RefProperty r = (RefProperty) p; @@ -704,7 +689,7 @@ public class DefaultCodegen { } catch (Exception e) { LOGGER.warn("Error obtaining the datatype from RefProperty:" + p + ". Datatype default to Object"); datatype = "Object"; - e.printStackTrace(); + LOGGER.error(e.getMessage(), e); } } else { if (p != null) { @@ -720,6 +705,7 @@ public class DefaultCodegen { * @param name string to be snake-cased * @return snake-cased string */ + @SuppressWarnings("static-method") public String snakeCase(String name) { return (name.length() > 0) ? (Character.toLowerCase(name.charAt(0)) + name.substring(1)) : ""; } @@ -730,6 +716,7 @@ public class DefaultCodegen { * @param name string to be capitalized * @return capitalized string */ + @SuppressWarnings("static-method") public String initialCaps(String name) { return StringUtils.capitalize(name); } @@ -740,6 +727,7 @@ public class DefaultCodegen { * @param name name * @return a string presentation of the type */ + @SuppressWarnings("static-method") public String getTypeDeclaration(String name) { return name; } @@ -1102,7 +1090,7 @@ public class DefaultCodegen { ArrayProperty ap = (ArrayProperty) p; CodegenProperty cp = fromProperty(property.name, ap.getItems()); if (cp == null) { - LOGGER.warn("skipping invalid property " + Json.pretty(p)); + LOGGER.warn("skipping invalid property " + Json.pretty(p)); } else { property.baseType = getSwaggerType(p); if (!languageSpecificPrimitives.contains(cp.baseType)) { @@ -1145,7 +1133,7 @@ public class DefaultCodegen { } } - private Response findMethodResponse(Map responses) { + private static Response findMethodResponse(Map responses) { String code = null; for (String responseCode : responses.keySet()) { @@ -1618,7 +1606,6 @@ public class DefaultCodegen { // to use the built-in model parsing, we unwrap the ArrayModel // and get a single property from it ArrayModel impl = (ArrayModel) model; - CodegenModel cm = fromModel(bp.getName(), impl); // get the single property ArrayProperty ap = new ArrayProperty().items(impl.getItems()); ap.setRequired(param.getRequired()); @@ -1659,6 +1646,7 @@ public class DefaultCodegen { * @param schemes a map of Swagger SecuritySchemeDefinition object * @return a list of Codegen Security objects */ + @SuppressWarnings("static-method") public List fromSecurity(Map schemes) { if (schemes == null) { return Collections.emptyList(); @@ -1765,6 +1753,7 @@ public class DefaultCodegen { && !languageSpecificPrimitives.contains(type); } + @SuppressWarnings("static-method") protected List> toExamples(Map examples) { if (examples == null) { return null; @@ -1788,7 +1777,7 @@ public class DefaultCodegen { } } - private List addHasMore(List objs) { + private static List addHasMore(List objs) { if (objs != null) { for (int i = 0; i < objs.size(); i++) { if (i > 0) { @@ -1802,7 +1791,7 @@ public class DefaultCodegen { return objs; } - private Map addHasMore(Map objs) { + private static Map addHasMore(Map objs) { if (objs != null) { for (int i = 0; i < objs.size() - 1; i++) { if (i > 0) { @@ -1825,6 +1814,7 @@ public class DefaultCodegen { * @param co Codegen Operation object * @param operations map of Codegen operations */ + @SuppressWarnings("static-method") public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { List opList = operations.get(tag); if (opList == null) { @@ -1849,8 +1839,6 @@ public class DefaultCodegen { co.baseName = tag; } - - private void addParentContainer(CodegenModel m, String name, Property property) { final CodegenProperty tmp = fromProperty(name, property); addImport(m, tmp.complexType); @@ -1879,7 +1867,7 @@ public class DefaultCodegen { String secondPattern = "([a-z\\d])([A-Z])"; String replacementPattern = "$1_$2"; // Replace package separator with slash. - word = word.replaceAll("\\.", "/"); + word = word.replaceAll("\\.", "/"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // Replace $ with two underscores for inner classes. word = word.replaceAll("\\$", "__"); // Replace capital letter with _ plus lowercase letter. @@ -1896,6 +1884,7 @@ public class DefaultCodegen { * @param word The word * @return The dashized version of the word, e.g. "my-name" */ + @SuppressWarnings("static-method") protected String dashize(String word) { return underscore(word).replaceAll("[_ ]", "-"); } @@ -1910,7 +1899,7 @@ public class DefaultCodegen { * @param name The base name * @return The next name for the base name */ - private String generateNextName(String name) { + private static String generateNextName(String name) { Pattern pattern = Pattern.compile("\\d+\\z"); Matcher matcher = pattern.matcher(name); if (matcher.find()) { @@ -1975,9 +1964,10 @@ public class DefaultCodegen { * @param name string to be camelize * @return camelized string */ + @SuppressWarnings("static-method") public String removeNonNameElementToCamelCase(String name) { String nonNameElementPattern = "[-_:;#]"; - name = StringUtils.join(Lists.transform(Lists.newArrayList(name.split(nonNameElementPattern)), new Function() { + name = StringUtils.join(Lists.transform(Lists.newArrayList(name.split(nonNameElementPattern)), new Function() { // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. @Nullable @Override public String apply(String input) { @@ -2014,7 +2004,7 @@ public class DefaultCodegen { Pattern p = Pattern.compile("\\/(.?)"); Matcher m = p.matcher(word); while (m.find()) { - word = m.replaceFirst("." + m.group(1)/*.toUpperCase()*/); + word = m.replaceFirst("." + m.group(1)/*.toUpperCase()*/); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. m = p.matcher(word); } @@ -2118,6 +2108,7 @@ public class DefaultCodegen { return library; } + @SuppressWarnings("static-method") protected CliOption buildLibraryCliOption(Map supportedLibraries) { StringBuilder sb = new StringBuilder("library template (sub-template) to use:"); for (String lib : supportedLibraries.keySet()) { @@ -2132,6 +2123,7 @@ public class DefaultCodegen { * @param name string to be sanitize * @return sanitized string */ + @SuppressWarnings("static-method") 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 @@ -2145,7 +2137,7 @@ public class DefaultCodegen { } // input[] => input - name = name.replaceAll("\\[\\]", ""); + name = name.replaceAll("\\[\\]", ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // input[a][b] => input_a_b name = name.replaceAll("\\[", "_"); @@ -2167,6 +2159,5 @@ public class DefaultCodegen { // 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 c08babd96c..6da8958fe1 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 @@ -19,7 +19,7 @@ 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 Logger LOGGER = LoggerFactory.getLogger(DefaultGenerator.class); protected CodegenConfig config; protected ClientOptInput opts; @@ -240,7 +240,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } } if (System.getProperty("debugModels") != null) { - System.out.println("############ Model info ############"); + LOGGER.info("############ Model info ############"); Json.prettyPrint(allModels); } @@ -340,7 +340,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } } if (System.getProperty("debugOperations") != null) { - System.out.println("############ Operation info ############"); + LOGGER.info("############ Operation info ############"); Json.prettyPrint(allOperations); } @@ -379,7 +379,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { config.postProcessSupportingFileData(bundle); if (System.getProperty("debugSupportingFiles") != null) { - System.out.println("############ Supporting file info ############"); + LOGGER.info("############ Supporting file info ############"); Json.prettyPrint(bundle); } @@ -438,18 +438,14 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } File outputFile = new File(outputFilename); OutputStream out = new FileOutputStream(outputFile, false); - if (in != null && out != null) { - System.out.println("writing file " + outputFile); + if (in != null) { + LOGGER.info("writing file " + outputFile); IOUtils.copy(in, out); } else { if (in == null) { - System.out.println("can't open " + templateFile + " for input"); - } - if (out == null) { - System.out.println("can't open " + outputFile + " for output"); + LOGGER.error("can't open " + templateFile + " for input"); } } - files.add(outputFile); } } @@ -458,13 +454,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } } } - config.processSwagger(swagger); - return files; } - private void processMimeTypes(List mimeTypeList, Map operation, String source) { + private static void processMimeTypes(List mimeTypeList, Map operation, String source) { if (mimeTypeList != null && mimeTypeList.size() > 0) { List> c = new ArrayList>(); int count = 0; @@ -485,7 +479,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } } - private List sortModelsByInheritance(final Map definitions) { + private static List sortModelsByInheritance(final Map definitions) { List sortedModelKeys = new ArrayList(definitions.keySet()); Comparator cmp = new Comparator() { @Override @@ -558,7 +552,8 @@ 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"); + LOGGER.info("processOperation: resourcePath= " + resourcePath + "\t;" + httpMethod + " " + operation + + "\n"); } List tags = operation.getTags(); if (tags == null) { @@ -655,10 +650,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } } - private String generateParameterId(Parameter parameter) { + private static String generateParameterId(Parameter parameter) { return parameter.getName() + ":" + parameter.getIn(); } + @SuppressWarnings("static-method") protected String sanitizeTag(String tag) { // remove spaces and make strong case String[] parts = tag.split(" "); @@ -671,6 +667,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { return buf.toString().replaceAll("[^a-zA-Z ]", ""); } + @SuppressWarnings("static-method") public Map processOperations(CodegenConfig config, String tag, List ops) { Map operations = new HashMap(); Map objs = new HashMap(); @@ -731,6 +728,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { return operations; } + @SuppressWarnings("static-method") public Map processModels(CodegenConfig config, Map definitions, Map allDefinitions) { Map objs = new HashMap(); objs.put("package", config.modelPackage()); @@ -750,7 +748,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { Set importSet = new TreeSet(); for (String nextImport : allImports) { - Map im = new HashMap(); String mapping = config.importMapping().get(nextImport); if (mapping == null) { mapping = config.toModelImport(nextImport); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java index 2e69816218..bd22f40616 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java @@ -1,10 +1,8 @@ package io.swagger.codegen; -import com.sun.org.apache.xpath.internal.operations.Mod; import io.swagger.models.*; import io.swagger.models.parameters.BodyParameter; import io.swagger.models.parameters.Parameter; -import io.swagger.models.parameters.RefParameter; import io.swagger.models.properties.*; import io.swagger.util.Json; @@ -174,9 +172,7 @@ public class InlineModelResolver { m.setItems(new RefProperty(existing)); } } - } else if (model instanceof ComposedModel) { - ComposedModel m = (ComposedModel) model; - } + } } } } @@ -199,7 +195,7 @@ public class InlineModelResolver { public String uniqueName(String key) { int count = 0; boolean done = false; - key = key.replaceAll("[^a-z_\\.A-Z0-9 ]", ""); + key = key.replaceAll("[^a-z_\\.A-Z0-9 ]", ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. while (!done) { String name = key; if (count > 0) { @@ -295,53 +291,26 @@ public class InlineModelResolver { } } - public Model modelFromProperty(ArrayProperty object, String path) { - String access = object.getAccess(); + @SuppressWarnings("static-method") + public Model modelFromProperty(ArrayProperty object, @SuppressWarnings("unused") String path) { String description = object.getDescription(); String example = object.getExample(); - String name = object.getName(); - Integer position = object.getPosition(); - Boolean readOnly = object.getReadOnly(); - Boolean required = object.getRequired(); - String title = object.getTitle(); - Map extensions = object.getVendorExtensions(); - Xml xml = object.getXml(); - -// object.getItems() -// Map properties = object.getProperties(); - Property inner = object.getItems(); if (inner instanceof ObjectProperty) { ArrayModel model = new ArrayModel(); model.setDescription(description); model.setExample(example); -// model.setName(name); -// model.setXml(xml); - model.setItems(object.getItems()); return model; } - -// if(properties != null) { -// flattenProperties(properties, path); -// model.setProperties(properties); -// } - return null; } public Model modelFromProperty(ObjectProperty object, String path) { - String access = object.getAccess(); String description = object.getDescription(); String example = object.getExample(); String name = object.getName(); - Integer position = object.getPosition(); - Boolean readOnly = object.getReadOnly(); - Boolean required = object.getRequired(); - String title = object.getTitle(); - Map extensions = object.getVendorExtensions(); Xml xml = object.getXml(); - Map properties = object.getProperties(); ModelImpl model = new ModelImpl(); @@ -358,17 +327,10 @@ public class InlineModelResolver { return model; } - public Model modelFromProperty(MapProperty object, String path) { - String access = object.getAccess(); + @SuppressWarnings("static-method") + public Model modelFromProperty(MapProperty object, @SuppressWarnings("unused") String path) { String description = object.getDescription(); String example = object.getExample(); - String name = object.getName(); - Integer position = object.getPosition(); - Boolean readOnly = object.getReadOnly(); - Boolean required = object.getRequired(); - String title = object.getTitle(); - Map extensions = object.getVendorExtensions(); - Xml xml = object.getXml(); ArrayModel model = new ArrayModel(); model.setDescription(description); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java index 818edab021..6bbc02130c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java @@ -2,15 +2,17 @@ package io.swagger.codegen; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; -import io.swagger.models.Swagger; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.io.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.File; +import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; @@ -25,6 +27,9 @@ import java.util.ServiceLoader; */ @Deprecated public class MetaGenerator extends AbstractGenerator { + + private static final Logger LOGGER = LoggerFactory.getLogger(MetaGenerator.class); + static Map configs = new HashMap(); static String configString; @@ -57,8 +62,6 @@ public class MetaGenerator extends AbstractGenerator { } protected void generate(String[] args) { - StringBuilder sb = new StringBuilder(); - String targetLanguage = null; String outputFolder = null; String name = null; String targetPackage = "io.swagger.codegen"; @@ -71,12 +74,9 @@ public class MetaGenerator extends AbstractGenerator { options.addOption("n", "name", true, "the human-readable name of the generator"); options.addOption("p", "package", true, "the package to put the main class into (defaults to io.swagger.codegen"); - ClientOptInput clientOptInput = new ClientOptInput(); - Swagger swagger = null; CommandLine cmd = null; try { CommandLineParser parser = new BasicParser(); - cmd = parser.parse(options, args); if (cmd.hasOption("h")) { usage(options); @@ -85,12 +85,11 @@ public class MetaGenerator extends AbstractGenerator { if (cmd.hasOption("n")) { name = cmd.getOptionValue("n"); } else { - System.out.println("name is required"); + System.out.println("name is required"); //FIXME replace by LOGGER usage(options); return; } if (cmd.hasOption("l")) { - targetLanguage = cmd.getOptionValue("l"); } if (cmd.hasOption("p")) { targetPackage = cmd.getOptionValue("p"); @@ -98,7 +97,7 @@ public class MetaGenerator extends AbstractGenerator { if (cmd.hasOption("o")) { outputFolder = cmd.getOptionValue("o"); } else { - System.out.println("output folder is required"); + System.out.println("output folder is required"); // FIXME replace by LOGGER usage(options); return; } @@ -106,7 +105,7 @@ public class MetaGenerator extends AbstractGenerator { usage(options); return; } - System.out.println("writing to folder " + outputFolder); + LOGGER.info("writing to folder " + outputFolder); File outputFolderLocation = new File(outputFolder); if (!outputFolderLocation.exists()) { outputFolderLocation.mkdirs(); @@ -161,8 +160,6 @@ public class MetaGenerator extends AbstractGenerator { public Reader getTemplate(String name) { return getTemplateReader(templateDir + File.separator + name + ".mustache"); } - - ; }) .defaultValue("") .compile(template); @@ -172,11 +169,11 @@ public class MetaGenerator extends AbstractGenerator { } else { String template = readTemplate(templateDir + File.separator + support.templateFile); FileUtils.writeStringToFile(new File(outputFilename), template); - System.out.println("copying file to " + outputFilename); + LOGGER.info("copying file to " + outputFilename); files.add(new File(outputFilename)); } - } catch (java.io.IOException e) { - e.printStackTrace(); + } catch (IOException e) { + LOGGER.error(e.getMessage(), e); } } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java index 53c6ca5ab9..976376bae6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java @@ -11,6 +11,7 @@ public class SupportingFile { this.destinationFilename = destinationFilename; } + @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("SupportingFile:").append("\n"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthParser.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthParser.java index 5fb4175518..65896dc593 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthParser.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthParser.java @@ -7,9 +7,16 @@ import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import config.ConfigParser; + import static org.apache.commons.lang3.StringUtils.isNotEmpty; public class AuthParser { + + private static final Logger LOGGER = LoggerFactory.getLogger(AuthParser.class); public static List parse(String urlEncodedAuthStr) { List auths = new ArrayList(); @@ -18,7 +25,7 @@ public class AuthParser { for (String part : parts) { String[] kvPair = part.split(":"); if (kvPair.length == 2) { - auths.add(new AuthorizationValue(URLDecoder.decode(kvPair[0]), URLDecoder.decode(kvPair[1]), "header")); + auths.add(new AuthorizationValue(URLDecoder.decode(kvPair[0]), URLDecoder.decode(kvPair[1]), "header")); // FIXME replace the deprecated method by decode(string, encoding). Which encoding is used ? Default UTF-8 ? } } } @@ -38,7 +45,7 @@ public class AuthParser { .append(URLEncoder.encode(v.getValue(), "UTF-8")); } catch (Exception e) { // continue - e.printStackTrace(); + LOGGER.error(e.getMessage(), e); } } return b.toString(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java index cc9b0ab5d8..c4b275e8ee 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java @@ -36,7 +36,7 @@ import static org.apache.commons.lang3.StringUtils.isNotEmpty; */ public class CodegenConfigurator { - public static final Logger LOG = LoggerFactory.getLogger(CodegenConfigurator.class); + public static final Logger LOGGER = LoggerFactory.getLogger(CodegenConfigurator.class); private String lang; private String inputSpec; @@ -349,7 +349,7 @@ public class CodegenConfigurator { if (!verbose) { return; } - LOG.info("\nVERBOSE MODE: ON. Additional debug options are injected" + + LOGGER.info("\nVERBOSE MODE: ON. Additional debug options are injected" + "\n - [debugSwagger] prints the swagger specification as interpreted by the codegen" + "\n - [debugModels] prints models passed to the template engine" + "\n - [debugOperations] prints operations passed to the template engine" + @@ -392,7 +392,7 @@ public class CodegenConfigurator { try { return Json.mapper().readValue(new File(configFile), CodegenConfigurator.class); } catch (IOException e) { - LOG.error("Unable to deserialize config file: " + configFile, e); + LOGGER.error("Unable to deserialize config file: " + configFile, e); } } return null; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java index 6d6062e93c..1115a4b709 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java @@ -42,7 +42,7 @@ public class ExampleGenerator { if (examples == null) { if (mediaTypes == null) { // assume application/json for this - mediaTypes = Arrays.asList("application/json"); + mediaTypes = Arrays.asList("application/json"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. } for (String mediaType : mediaTypes) { Map kv = new HashMap(); @@ -127,7 +127,7 @@ public class ExampleGenerator { return resolveModelToExample(simpleName, mediaType, model, processedModels); } } else if (property instanceof UUIDProperty) { - return "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; + return "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; } return ""; @@ -142,16 +142,14 @@ public class ExampleGenerator { ModelImpl impl = (ModelImpl) model; Map values = new HashMap(); - if (impl != null && impl.getProperties() != null) { + if (impl.getProperties() != null) { for (String propertyName : impl.getProperties().keySet()) { Property property = impl.getProperties().get(propertyName); values.put(propertyName, resolvePropertyToExample(mediaType, property, processedModels)); } } - return values; } - return ""; } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java index 15f22dfe8f..ec77888ec2 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 @@ -39,7 +39,7 @@ public class XmlExampleGenerator { public XmlExampleGenerator(Map examples) { this.examples = examples; if (examples == null) { - examples = new HashMap(); + this.examples = new HashMap(); } } @@ -74,10 +74,6 @@ public class XmlExampleGenerator { Map elements = new LinkedHashMap(); String name = modelName; - String namespace; - String prefix; - Boolean wrapped; - Xml xml = model.getXml(); if (xml != null) { if (xml.getName() != null) { @@ -117,6 +113,7 @@ public class XmlExampleGenerator { return sb.toString(); } + @SuppressWarnings("static-method") protected String quote(String string) { return "\"" + string + "\""; } @@ -211,14 +208,17 @@ public class XmlExampleGenerator { return "not implemented " + property; } + @SuppressWarnings("static-method") protected String openTag(String name) { return "<" + name + ">"; } + @SuppressWarnings("static-method") protected String closeTag(String name) { return ""; } + @SuppressWarnings("static-method") protected String indent(int indent) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < indent; i++) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java new file mode 100644 index 0000000000..3efca234a7 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java @@ -0,0 +1,183 @@ +package io.swagger.codegen.languages; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenResponse; +import io.swagger.codegen.CodegenType; +import io.swagger.models.Operation; +import io.swagger.models.Path; +import io.swagger.models.Swagger; + +public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen +{ + /** + * Name of the sub-directory in "src/main/resource" where to find the + * Mustache template for the JAX-RS Codegen. + */ + protected static final String JAXRS_TEMPLATE_DIRECTORY_NAME = "JavaJaxRS"; + protected String implFolder = "src/main/java"; + protected String title = "Swagger Server"; + + public AbstractJavaJAXRSServerCodegen() + { + super(); + } + + // ================ + // ABSTRACT METHODS + // ================ + + @Override + public abstract String getHelp(); + + @Override + public abstract String getName(); + + // =============== + // COMMONS METHODS + // =============== + + @Override + public CodegenType getTag() + { + return CodegenType.SERVER; + } + + @Override + public void preprocessSwagger(Swagger swagger) + { + if ( "/".equals(swagger.getBasePath()) ) { + swagger.setBasePath(""); + } + + String host = swagger.getHost(); + String port = "8080"; // Default value for a JEE Server + if ( host != null ) { + String[] parts = host.split(":"); + if ( parts.length > 1 ) { + port = parts[1]; + } + } + this.additionalProperties.put("serverPort", port); + if ( swagger.getPaths() != null ) { + for ( String pathname : swagger.getPaths().keySet() ) { + Path path = swagger.getPath(pathname); + if ( path.getOperations() != null ) { + for ( Operation operation : path.getOperations() ) { + if ( operation.getTags() != null ) { + List> tags = new ArrayList>(); + for ( String tag : operation.getTags() ) { + Map value = new HashMap(); + value.put("tag", tag); + value.put("hasMore", "true"); + tags.add(value); + } + if ( tags.size() > 0 ) { + tags.get(tags.size() - 1).remove("hasMore"); + } + if ( operation.getTags().size() > 0 ) { + String tag = operation.getTags().get(0); + operation.setTags(Arrays.asList(tag)); + } + operation.setVendorExtension("x-tags", tags); + } + } + } + } + } + } + + @Override + public Map postProcessOperations(Map objs) + { + @SuppressWarnings("unchecked") + Map operations = (Map) objs.get("operations"); + if ( operations != null ) { + @SuppressWarnings("unchecked") + 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).trim(); + operation.returnContainer = "List"; + } + } else if ( operation.returnType.startsWith("Map") ) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if ( end > 0 ) { + operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim(); + operation.returnContainer = "Map"; + } + } else if ( operation.returnType.startsWith("Set") ) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if ( end > 0 ) { + operation.returnType = rt.substring("Set<".length(), end).trim(); + operation.returnContainer = "Set"; + } + } + } + } + return objs; + } + + @Override + public String toApiName(final String name) + { + String computed = name; + if ( computed.length() == 0 ) { + return "DefaultApi"; + } + computed = sanitizeName(computed); + return camelize(computed) + "Api"; + } + + @Override + public String apiFilename(String templateName, String tag) + { + String result = super.apiFilename(templateName, tag); + + if ( templateName.endsWith("Impl.mustache") ) { + int ix = result.lastIndexOf('/'); + result = result.substring(0, ix) + "/impl" + result.substring(ix, result.length() - 5) + "ServiceImpl.java"; + result = result.replace(apiFileFolder(), implFileFolder(implFolder)); + } else if ( templateName.endsWith("Factory.mustache") ) { + int ix = result.lastIndexOf('/'); + result = result.substring(0, ix) + "/factories" + result.substring(ix, result.length() - 5) + "ServiceFactory.java"; + result = result.replace(apiFileFolder(), implFileFolder(implFolder)); + } else if ( templateName.endsWith("Service.mustache") ) { + int ix = result.lastIndexOf('.'); + result = result.substring(0, ix) + "Service.java"; + } + return result; + } + + private String implFileFolder(String output) + { + return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/'); + } + + @Override + public boolean shouldOverwrite(String filename) + { + return super.shouldOverwrite(filename) && !filename.endsWith("ServiceImpl.java") && !filename.endsWith("ServiceFactory.java"); + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java index 4a9c055730..f0fb994dd2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -9,10 +9,8 @@ import java.io.File; import org.apache.commons.lang.StringUtils; public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig { - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; - } + + protected String modelPropertyNaming= "camelCase"; public AbstractTypeScriptClientCodegen() { super(); @@ -54,7 +52,25 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp typeMapping.put("DateTime", "Date"); //TODO binary should be mapped to byte array // mapped to String as a workaround - typeMapping.put("binary", "string"); + typeMapping.put("binary", "string"); + + cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase")); + + + } + + @Override + public void processOpts() { + super.processOpts(); + if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) { + setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); + } + } + + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; } @Override @@ -73,9 +89,9 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp } @Override - public String toVarName(String name) { + public String toParamName(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) @@ -93,9 +109,9 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp } @Override - public String toParamName(String name) { + public String toVarName(String name) { // should be the same as variable name - return toVarName(name); + return getNameUsingModelPropertyNaming(name); } @Override @@ -145,19 +161,47 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp return type; } - @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 - // append _ at the beginning, e.g. _return - if (reservedWords.contains(operationId)) { - return escapeReservedWord(camelize(sanitizeName(operationId), true)); - } - - return camelize(sanitizeName(operationId), true); + @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 + // append _ at the beginning, e.g. _return + if (reservedWords.contains(operationId)) { + return escapeReservedWord(camelize(sanitizeName(operationId), true)); + } + + return camelize(sanitizeName(operationId), true); + } + + public void setModelPropertyNaming(String naming) { + if ("original".equals(naming) || "camelCase".equals(naming) || + "PascalCase".equals(naming) || "snake_case".equals(naming)) { + this.modelPropertyNaming = naming; + } else { + throw new IllegalArgumentException("Invalid model property naming '" + + naming + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); + } + } + + public String getModelPropertyNaming() { + return this.modelPropertyNaming; + } + + public String getNameUsingModelPropertyNaming(String name) { + switch (CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.valueOf(getModelPropertyNaming())) { + case original: return name; + case camelCase: return camelize(name, true); + case PascalCase: return camelize(name); + case snake_case: return underscore(name); + default: throw new IllegalArgumentException("Invalid model property naming '" + + name + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); + } + + } } 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 aa5d314184..69fc845676 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 @@ -63,7 +63,9 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon * unmarshalling problems and any other RuntimeException will be considered as ApiErrors. */ protected boolean onlyOneSuccess = true; - Logger LOGGER = LoggerFactory.getLogger(AkkaScalaClientCodegen.class); + + @SuppressWarnings("hiding") + protected Logger LOGGER = LoggerFactory.getLogger(AkkaScalaClientCodegen.class); public AkkaScalaClientCodegen() { super(); 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 ac84e7c795..ffe1467a7e 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 @@ -7,7 +7,6 @@ import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; @@ -151,7 +150,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi @Override public String toVarName(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) { 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 bac6efe2af..78017feb58 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 @@ -23,8 +23,6 @@ import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; -import org.apache.commons.lang.StringUtils; - public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; 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 23c266e618..7697bd5b02 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 @@ -7,6 +7,7 @@ import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenOperation; import io.swagger.models.properties.*; import io.swagger.codegen.CliOption; @@ -22,10 +23,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig { + @SuppressWarnings({ "unused", "hiding" }) private static final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class); protected boolean optionalAssemblyInfoFlag = true; + protected boolean optionalProjectFileFlag = false; protected boolean optionalMethodArgumentFlag = true; protected boolean useDateTimeOffsetFlag = false; + protected boolean useCollection = false; + protected boolean returnICollection = false; + protected String packageGuid = "{" + java.util.UUID.randomUUID().toString().toUpperCase() + "}"; protected String packageTitle = "Swagger Library"; protected String packageProductName = "SwaggerLibrary"; protected String packageDescription = "A library generated from a Swagger doc"; @@ -74,6 +80,8 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig "long?", "float?", "byte[]", + "ICollection", + "Collection", "List", "Dictionary", "DateTime?", @@ -87,7 +95,9 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig "Stream", // not really a primitive, we include it to avoid model import "Object") ); + instantiationTypes.put("array", "List"); + instantiationTypes.put("list", "List"); instantiationTypes.put("map", "Dictionary"); typeMapping = new HashMap(); @@ -119,6 +129,14 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig CodegenConstants.OPTIONAL_ASSEMBLY_INFO_DESC).defaultValue(Boolean.TRUE.toString())); cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC).defaultValue(sourceFolder)); cliOptions.add(CliOption.newBoolean(CodegenConstants.USE_DATETIME_OFFSET, CodegenConstants.USE_DATETIME_OFFSET_DESC)); + + cliOptions.add( CliOption.newBoolean(CodegenConstants.USE_COLLECTION, CodegenConstants.USE_COLLECTION_DESC) + .defaultValue(Boolean.FALSE.toString()) ); + cliOptions.add( CliOption.newBoolean(CodegenConstants.RETURN_ICOLLECTION, CodegenConstants.RETURN_ICOLLECTION_DESC) + .defaultValue(Boolean.FALSE.toString()) ); + cliOptions.add(CliOption.newBoolean(CodegenConstants.OPTIONAL_PROJECT_FILE, + CodegenConstants.OPTIONAL_PROJECT_FILE_DESC).defaultValue(Boolean.FALSE.toString())); + cliOptions.add(new CliOption(CodegenConstants.OPTIONAL_PROJECT_GUID, CodegenConstants.OPTIONAL_PROJECT_GUID_DESC)); } @Override @@ -163,7 +181,19 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig additionalProperties.put("packageDescription", packageDescription); additionalProperties.put("packageCompany", packageCompany); additionalProperties.put("packageCopyright", packageCopyright); - + + if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_FILE)) + { + setOptionalProjectFileFlag(Boolean.valueOf( + additionalProperties.get(CodegenConstants.OPTIONAL_PROJECT_FILE).toString())); + } + + if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_GUID)) + { + setPackageGuid((String) additionalProperties.get(CodegenConstants.OPTIONAL_PROJECT_GUID)); + } + additionalProperties.put("packageGuid", packageGuid); + if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_METHOD_ARGUMENT)) { setOptionalMethodArgumentFlag(Boolean.valueOf(additionalProperties .get(CodegenConstants.OPTIONAL_METHOD_ARGUMENT).toString())); @@ -175,14 +205,36 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig .get(CodegenConstants.OPTIONAL_ASSEMBLY_INFO).toString())); } + if (additionalProperties.containsKey(CodegenConstants.USE_COLLECTION)){ + setUseCollection(Boolean.valueOf(additionalProperties.get(CodegenConstants.USE_COLLECTION).toString())); + } + + if (additionalProperties.containsKey(CodegenConstants.RETURN_ICOLLECTION)){ + setReturnICollection(Boolean.valueOf(additionalProperties.get(CodegenConstants.RETURN_ICOLLECTION).toString())); + } + + + String packageFolder = sourceFolder + File.separator + packageName.replace(".", java.io.File.separator); + String clientPackageDir = sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator); + + //Compute the relative path to the bin directory where the external assemblies live + //This is necessary to properly generate the project file + int packageDepth = packageFolder.length() - packageFolder.replace(java.io.File.separator, "").length(); + String binRelativePath = "..\\"; + for (int i=0; i < packageDepth; i = i+1) + binRelativePath += "..\\"; + binRelativePath += "bin\\"; + additionalProperties.put("binRelativePath", binRelativePath); + supportingFiles.add(new SupportingFile("Configuration.mustache", - sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs")); + clientPackageDir, "Configuration.cs")); supportingFiles.add(new SupportingFile("ApiClient.mustache", - sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiClient.cs")); + clientPackageDir, "ApiClient.cs")); supportingFiles.add(new SupportingFile("ApiException.mustache", - sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiException.cs")); + clientPackageDir, "ApiException.cs")); supportingFiles.add(new SupportingFile("ApiResponse.mustache", - sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiResponse.cs")); + clientPackageDir, "ApiResponse.cs")); + supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll")); supportingFiles.add(new SupportingFile("RestSharp.dll", "bin", "RestSharp.dll")); supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat")); @@ -191,9 +243,11 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("README.md", "", "README.md")); if (optionalAssemblyInfoFlag) { - supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", "src" + File.separator + "Properties", "AssemblyInfo.cs")); + supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", packageFolder + File.separator + "Properties", "AssemblyInfo.cs")); + } + if (optionalProjectFileFlag) { + supportingFiles.add(new SupportingFile("Project.mustache", packageFolder, clientPackage + ".csproj")); } - } @Override @@ -229,7 +283,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String toVarName(String name) { // sanitize name - name = sanitizeName(name); + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) { @@ -288,6 +342,32 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig return toModelName(name); } + @Override + public Map postProcessOperations(Map objs) { + super.postProcessOperations(objs); + if(objs != null) { + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (CodegenOperation operation : ops) { + if (operation.returnType != null) { + operation.returnContainer = operation.returnType; + if( this.returnICollection && ( + operation.returnType.startsWith("List")|| + operation.returnType.startsWith("Collection")) ) { + // NOTE: ICollection works for both List and Collection + int genericStart = operation.returnType.indexOf("<"); + if(genericStart > 0) { + operation.returnType = "ICollection" + operation.returnType.substring(genericStart); + } + } + } + } + } + } + + return objs; + } @Override public String getTypeDeclaration(Property p) { @@ -338,10 +418,29 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig this.optionalAssemblyInfoFlag = flag; } + public void setOptionalProjectFileFlag(boolean flag) { + this.optionalProjectFileFlag = flag; + } + public void setOptionalMethodArgumentFlag(boolean flag) { this.optionalMethodArgumentFlag = flag; } + public void setReturnICollection(boolean returnICollection) { + this.returnICollection = returnICollection; + } + + public void setUseCollection(boolean useCollection) { + this.useCollection = useCollection; + if(useCollection){ + typeMapping.put("array", "Collection"); + typeMapping.put("list", "Collection"); + + instantiationTypes.put("array", "Collection"); + instantiationTypes.put("list", "Collection"); + } + } + public void useDateTimeOffset(boolean flag) { this.useDateTimeOffsetFlag = flag; if (flag) @@ -350,7 +449,10 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig typeMapping.put("datetime", "DateTime?"); } - + public void setPackageGuid(String packageGuid) { + this.packageGuid = packageGuid; + } + public void setPackageName(String packageName) { this.packageName = packageName; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java index d4a8ada06b..5228c86457 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java @@ -172,7 +172,7 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi @Override public String toVarName(String name) { - name = name.replaceAll("[^a-zA-Z0-9_-]+", ""); + name = name.replaceAll("[^a-zA-Z0-9_-]+", ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. name = dashize(name); return name; } @@ -196,6 +196,7 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi return operations; } + @SuppressWarnings("static-method") protected String namespaceToFolder(String ns) { return ns.replace(".", File.separator).replace("-", "_"); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java index 3ad108e2e6..d3d249bfcd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java @@ -172,7 +172,7 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege @Override public String toVarName(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java index e936a37f3c..edd3c2ee27 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java @@ -171,7 +171,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toVarName(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) { @@ -221,15 +221,10 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toDefaultValue(Property p) { if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); return "{}"; } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); return "[]"; } - return super.toDefaultValue(p); } 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 435e235c68..2184e4013f 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 @@ -193,14 +193,7 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p); - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - + if (p instanceof ArrayProperty || p instanceof MapProperty) { return getSwaggerType(p); } return super.getTypeDeclaration(p); @@ -256,12 +249,8 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig } return "0"; } else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); return "new Dictionary()"; } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); return "new Array()"; } else { return "null"; @@ -271,8 +260,8 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String toVarName(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); - + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + // if it's all uppper case, convert to lower case if (name.matches("^[A-Z_]*$")) { name = name.toLowerCase(); @@ -323,7 +312,7 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String toApiFilename(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // e.g. PhoneNumberApi.rb => phone_number_api.rb return camelize(name) + "Api"; @@ -376,7 +365,4 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig public void setSourceFolder(String sourceFolder) { this.sourceFolder = sourceFolder; } - } - - diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java index 483e841d73..1dd90dada4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java @@ -4,6 +4,8 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; + +import config.ConfigParser; import io.swagger.codegen.*; import io.swagger.models.HttpMethod; import io.swagger.models.Operation; @@ -14,7 +16,13 @@ import io.swagger.util.Yaml; import java.io.File; import java.util.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConfig { + + private static final Logger LOGGER = LoggerFactory.getLogger(FlaskConnexionCodegen.class); + public static final String CONTROLLER_PACKAGE = "controllerPackage"; public static final String DEFAULT_CONTROLLER = "defaultController"; @@ -167,8 +175,8 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf */ @Override public String getHelp() { - return "Generates a python server library using the connexion project. By default, " + - "it will also generate service classes--which you can disable with the `-Dnoservice` environment variable."; + return "Generates a Python server library using the Connexion project. By default, " + + "it will also generate service classes -- which you can disable with the `-Dnoservice` environment variable."; } @Override @@ -249,7 +257,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf } @SuppressWarnings("unchecked") - private List> getOperations(Map objs) { + private static List> getOperations(Map objs) { List> result = new ArrayList>(); Map apiInfo = (Map) objs.get("apiInfo"); List> apis = (List>) apiInfo.get("apis"); @@ -259,7 +267,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf return result; } - private List> sortOperationsByPath(List ops) { + private static List> sortOperationsByPath(List ops) { Multimap opsByPath = ArrayListMultimap.create(); for (CodegenOperation op : ops) { @@ -289,7 +297,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf try { objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); } catch (JsonProcessingException e) { - e.printStackTrace(); + LOGGER.error(e.getMessage(), e); } } for (Map operations : getOperations(objs)) { @@ -304,7 +312,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf @Override public String toOperationId(String operationId) { - operationId = super.toOperationId(operationId); + operationId = super.toOperationId(operationId); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // Use the part after the last dot, e.g. // controllers.defaultController.addPet => addPet operationId = operationId.replaceAll(".*\\.", ""); @@ -312,4 +320,4 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf // addPet => add_pet return underscore(operationId); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java new file mode 100644 index 0000000000..9e1c072cdb --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -0,0 +1,283 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; + +import java.io.File; +import java.util.*; + +import org.apache.commons.lang.StringUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class GoClientCodegen extends DefaultCodegen implements CodegenConfig { + static Logger LOGGER = LoggerFactory.getLogger(GoClientCodegen.class); + + protected String packageName = "swagger"; + protected String packageVersion = "1.0.0"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "go"; + } + + public String getHelp() { + return "Generates a Go client library (beta)."; + } + + public GoClientCodegen() { + super(); + outputFolder = "generated-code/go"; + modelTemplateFiles.put("model.mustache", ".go"); + apiTemplateFiles.put("api.mustache", ".go"); + templateDir = "go"; + + reservedWords = new HashSet ( + Arrays.asList( + "break", "default", "func", "interface", "select", + "case", "defer", "go", "map", "struct", + "chan", "else", "goto", "package", "switch", + "const", "fallthrough", "if", "range", "type", + "continue", "for", "import", "return", "var") + ); + + defaultIncludes = new HashSet( + Arrays.asList( + "map", + "array") + ); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "string", + "bool", + "uint", + "uint32", + "uint64", + "int", + "int32", + "int64", + "float32", + "float64", + "complex64", + "complex128", + "rune", + "byte") + ); + + instantiationTypes.clear(); + /*instantiationTypes.put("array", "GoArray"); + instantiationTypes.put("map", "GoMap");*/ + + typeMapping.clear(); + typeMapping.put("integer", "int32"); + typeMapping.put("long", "int64"); + typeMapping.put("float", "float32"); + typeMapping.put("double", "float64"); + typeMapping.put("boolean", "bool"); + typeMapping.put("string", "string"); + typeMapping.put("Date", "time.Time"); + typeMapping.put("DateTime", "time.Time"); + typeMapping.put("password", "string"); + typeMapping.put("File", "*os.File"); + typeMapping.put("file", "*os.File"); + // map binary to string as a workaround + // the correct solution is to use []byte + typeMapping.put("binary", "string"); + + importMapping = new HashMap(); + importMapping.put("time.Time", "time"); + importMapping.put("*os.File", "os"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Go package name (convention: lowercase).") + .defaultValue("swagger")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Go package version.") + .defaultValue("1.0.0")); + + } + + @Override + public void processOpts() { + //super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } + else { + setPackageName("swagger"); + } + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); + } + else { + setPackageVersion("1.0.0"); + } + + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); + + modelPackage = packageName; + apiPackage = packageName; + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + packageName; + } + + public String modelFileFolder() { + return outputFolder + File.separator + packageName; + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) + return name; + + // camelize (lower first character) the variable name + // pet_id => PetId + name = camelize(name); + + // for reserved word or word starting with number, append _ + if(reservedWords.contains(name) || name.matches("^\\d.*")) + name = escapeReservedWord(name); + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // 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"); + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return "[]" + getTypeDeclaration(inner); + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[string]" + getTypeDeclaration(inner); + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) + return (type); + } + else + type = swaggerType; + return type; + } + + @Override + public String toOperationId(String operationId) { + // 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(operationId); + } + + @Override + public Map postProcessOperations(Map objs) { + @SuppressWarnings("unchecked") + Map objectMap = (Map) objs.get("operations"); + @SuppressWarnings("unchecked") + List operations = (List) objectMap.get("operation"); + for (CodegenOperation operation : operations) { + // http method verb conversion (e.g. PUT => Put) + operation.httpMethod = camelize(operation.httpMethod.toLowerCase()); + } + + // remove model imports to avoid error + List> imports = (List>) objs.get("imports"); + if (imports == null) + return objs; + + Iterator> iterator = imports.iterator(); + while (iterator.hasNext()) { + String _import = iterator.next().get("import"); + if (_import.startsWith(apiPackage())) + iterator.remove(); + } + + return objs; + } + + @Override + public Map postProcessModels(Map objs) { + // remove model imports to avoid error + List> imports = (List>) objs.get("imports"); + final String prefix = modelPackage(); + Iterator> iterator = imports.iterator(); + while (iterator.hasNext()) { + String _import = iterator.next().get("import"); + if (_import.startsWith(prefix)) + iterator.remove(); + } + return objs; + } + + @Override + protected boolean needToImport(String type) { + return !defaultIncludes.contains(type) + && !languageSpecificPrimitives.contains(type); + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java index 429d992b7e..903cb7ba76 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java @@ -5,8 +5,6 @@ import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; import io.swagger.models.properties.*; -import org.apache.commons.lang.StringUtils; - import java.util.*; import java.io.File; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java new file mode 100644 index 0000000000..692168c1a4 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -0,0 +1,73 @@ + +package io.swagger.codegen.languages; + +import java.io.File; +import java.util.List; +import java.util.Map; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenOperation; +import io.swagger.models.Operation; + +public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen +{ + public JavaCXFServerCodegen() + { + super(); + + sourceFolder = "src/gen/java"; + invokerPackage = "io.swagger.api"; + artifactId = "swagger-jaxrs-server"; + outputFolder = "generated-code/JavaJaxRS-CXF"; + + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put("api.mustache", ".java"); + apiPackage = "io.swagger.api"; + modelPackage = "io.swagger.model"; + + additionalProperties.put("title", title); + + super.embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf"; + + for ( int i = 0; i < cliOptions.size(); i++ ) { + if ( CodegenConstants.LIBRARY.equals(cliOptions.get(i).getOpt()) ) { + cliOptions.remove(i); + break; + } + } + + cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC)); + } + + @Override + public void processOpts() + { + super.processOpts(); + sourceFolder = "gen" + File.separator + "java"; + + modelTemplateFiles.clear(); + modelTemplateFiles.put("entityModel.mustache", ".java"); + + supportingFiles.clear(); + } + + @Override + public String getName() + { + return "jaxrs-cxf"; + } + + + @Override + public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + super.addOperationToGroup(tag, resourcePath, operation, co, operations); + co.subresourceOperation = !co.path.isEmpty(); + } + + @Override + public String getHelp() + { + return "Generates a Java JAXRS Server application based on Apache CXF framework."; + } +} 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 d2228fb0bc..154246f237 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,57 @@ package io.swagger.codegen.languages; import com.google.common.base.Strings; -import io.swagger.codegen.*; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +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 java.util.regex.Pattern; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; import io.swagger.models.Model; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; import io.swagger.models.parameters.FormParameter; import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.*; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.util.*; -import java.util.regex.Pattern; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.BooleanProperty; +import io.swagger.models.properties.DoubleProperty; +import io.swagger.models.properties.FloatProperty; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.StringProperty; public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { + @SuppressWarnings("hiding") private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class); public static final String FULL_JAVA_UTIL = "fullJavaUtil"; public static final String DEFAULT_LIBRARY = ""; public static final String DATE_LIBRARY = "dateLibrary"; + public static final String USE_RX_JAVA = "useRxJava"; + + public static final String RETROFIT_1 = "retrofit"; + public static final String RETROFIT_2 = "retrofit2"; protected String dateLibrary = "default"; protected String invokerPackage = "io.swagger.client"; @@ -35,6 +65,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { protected String javaUtilPrefix = ""; protected Boolean serializableModel = false; protected boolean serializeBigDecimalAsString = false; + protected boolean useRxJava = false; public JavaClientCodegen() { super(); @@ -88,13 +119,15 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, CodegenConstants .SERIALIZE_BIG_DECIMAL_AS_STRING_DESC)); cliOptions.add(CliOption.newBoolean(FULL_JAVA_UTIL, "whether to use fully qualified name for classes under java.util")); + cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library.")); supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.1.1"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1"); - supportedLibraries.put("retrofit", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); - supportedLibraries.put("retrofit2", "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2)"); + supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); + supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2). Enable the RxJava adapter using '-DuseRxJava=true'."); + CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); library.setDefault(DEFAULT_LIBRARY); library.setEnum(supportedLibraries); @@ -183,6 +216,10 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { if (additionalProperties.containsKey(FULL_JAVA_UTIL)) { this.setFullJavaUtil(Boolean.valueOf(additionalProperties.get(FULL_JAVA_UTIL).toString())); } + + if (additionalProperties.containsKey(USE_RX_JAVA)) { + this.setUseRxJava(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA).toString())); + } if (fullJavaUtil) { javaUtilPrefix = "java.util."; } @@ -242,7 +279,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); - if (!("feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary()))) { + if (!("feign".equals(getLibrary()) || usesAnyRetrofitLibrary())) { supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); @@ -259,7 +296,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java")); // "build.sbt" is for development with SBT supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); - } else if ("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) { + } else if (usesAnyRetrofitLibrary()) { supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java")); } else if("jersey2".equals(getLibrary())) { @@ -287,6 +324,14 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { } } + private boolean usesAnyRetrofitLibrary() { + return getLibrary() != null && getLibrary().contains(RETROFIT_1); + } + + private boolean usesRetrofit2Library() { + return getLibrary() != null && getLibrary().contains(RETROFIT_2); + } + 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 @@ -325,7 +370,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toVarName(String name) { // sanitize name - name = sanitizeName(name); + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. if("_".equals(name)) { name = "_u"; @@ -356,7 +401,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toModelName(String name) { - name = sanitizeName(name); + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // model name cannot use reserved keyword, e.g. return if (reservedWords.contains(name)) { @@ -495,7 +540,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { if (allDefinitions != null && codegenModel != null && codegenModel.parentSchema != null && codegenModel.hasEnums) { final Model parentModel = allDefinitions.get(codegenModel.parentSchema); final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); - codegenModel = this.reconcileInlineEnums(codegenModel, parentCodegenModel); + codegenModel = JavaClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); } return codegenModel; @@ -617,7 +662,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { } } - if("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) { + if(usesAnyRetrofitLibrary()) { Map operations = (Map) objs.get("operations"); if (operations != null) { List ops = (List) operations.get("operation"); @@ -633,7 +678,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { if (operation.returnType == null) { operation.returnType = "Void"; } - if ("retrofit2".equals(getLibrary()) && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) + if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) operation.path = operation.path.substring(1); } } @@ -667,7 +712,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { } } - private String getAccept(Operation operation) { + private static String getAccept(Operation operation) { String accepts = null; String defaultContentType = "application/json"; if (operation.getProduces() != null && !operation.getProduces().isEmpty()) { @@ -698,14 +743,14 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { return super.needToImport(type) && type.indexOf(".") < 0; } - private String findCommonPrefixOfVars(List vars) { + private static String findCommonPrefixOfVars(List vars) { String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()])); // exclude trailing characters that should be part of a valid variable // e.g. ["status-on", "status-off"] => "status-" (not "status-o") return prefix.replaceAll("[a-zA-Z0-9]+\\z", ""); } - private String toEnumVarName(String value) { + private static String toEnumVarName(String value) { String var = value.replaceAll("\\W+", "_").toUpperCase(); if (var.matches("\\d.*")) { return "_" + var; @@ -714,7 +759,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { } } - private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { + private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { // This generator uses inline classes to define enums, which breaks when // dealing with models that have subTypes. To clean this up, we will analyze // the parent and child models, look for enums that match, and remove @@ -798,8 +843,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { this.serializableModel = serializableModel; } - private String sanitizePackageName(String packageName) { - packageName = packageName.trim(); + private static String sanitizePackageName(String packageName) { + packageName = packageName.trim(); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_"); if(Strings.isNullOrEmpty(packageName)) { return "invalidPackageName"; @@ -811,6 +856,10 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { this.fullJavaUtil = fullJavaUtil; } + public void setUseRxJava(boolean useRxJava) { + this.useRxJava = useRxJava; + } + public void setDateLibrary(String library) { this.dateLibrary = library; } 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 0904629d48..c21859d7d6 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 @@ -11,7 +11,13 @@ import io.swagger.util.Yaml; import java.util.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class JavaInflectorServerCodegen extends JavaClientCodegen implements CodegenConfig { + + private static final Logger LOGGER = LoggerFactory.getLogger(JavaInflectorServerCodegen.class); + protected String title = "Swagger Inflector"; public JavaInflectorServerCodegen() { @@ -164,7 +170,7 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen implements Cod try { objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); } catch (JsonProcessingException e) { - e.printStackTrace(); + LOGGER.error(e.getMessage(), e); } } return super.postProcessSupportingFileData(objs); @@ -175,12 +181,15 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen implements Cod if (name.length() == 0) { return "DefaultController"; } - name = name.replaceAll("[^a-zA-Z0-9]+", "_"); + name = name.replaceAll("[^a-zA-Z0-9]+", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. return camelize(name)+ "Controller"; } @Override public boolean shouldOverwrite(String filename) { - return super.shouldOverwrite(filename); + return super.shouldOverwrite(filename) && + !filename.endsWith("pom.xml") && + !filename.endsWith("README.md") && + !filename.endsWith("inflector.yaml"); } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java new file mode 100644 index 0000000000..61d14d692f --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java @@ -0,0 +1,124 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.Operation; + +import java.io.File; +import java.util.*; + +public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen +{ + + public JavaJerseyServerCodegen() + { + super(); + + sourceFolder = "src/gen/java"; + invokerPackage = "io.swagger.api"; + artifactId = "swagger-jaxrs-server"; + outputFolder = "generated-code/JavaJaxRS-Jersey"; + + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put("api.mustache", ".java"); + apiTemplateFiles.put("apiService.mustache", ".java"); + apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); + apiTemplateFiles.put("apiServiceFactory.mustache", ".java"); + apiPackage = "io.swagger.api"; + modelPackage = "io.swagger.model"; + + additionalProperties.put("title", title); + + embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "jersey1_18"; + + for ( int i = 0; i < cliOptions.size(); i++ ) { + if ( CodegenConstants.LIBRARY.equals(cliOptions.get(i).getOpt()) ) { + cliOptions.remove(i); + break; + } + } + + CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); + library.setDefault(DEFAULT_LIBRARY); + + Map supportedLibraries = new LinkedHashMap(); + + supportedLibraries.put(DEFAULT_LIBRARY, "Jersey core 1.18.1"); + library.setEnum(supportedLibraries); + + cliOptions.add(library); + cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC)); + } + + @Override + public String getName() + { + return "jaxrs"; // TODO should be renamed as "jaxrs-jersey" + } + + @Override + public String getHelp() + { + return "Generates a Java JAXRS Server application based on Jersey framework."; + } + + @Override + public void processOpts() + { + super.processOpts(); + + if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER) ) { + implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); + } + + supportingFiles.clear(); + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("ApiException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiException.java")); + supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiOriginFilter.java")); + supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiResponseMessage.java")); + supportingFiles.add(new SupportingFile("NotFoundException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java")); + supportingFiles.add(new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml")); + supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java")); + + if ( additionalProperties.containsKey("dateLibrary") ) { + setDateLibrary(additionalProperties.get("dateLibrary").toString()); + additionalProperties.put(dateLibrary, "true"); + } + + if ( "joda".equals(dateLibrary) ) { + supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java")); + supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java")); + } else if ( "java8".equals(dateLibrary) ) { + supportingFiles.add(new SupportingFile("LocalDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateTimeProvider.java")); + supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java")); + } + } + + @Override + public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + String basePath = resourcePath; + if (basePath.startsWith("/")) { + basePath = basePath.substring(1); + } + int pos = basePath.indexOf("/"); + if (pos > 0) { + basePath = basePath.substring(0, pos); + } + + if (basePath == "") { + basePath = "default"; + } else { + if (co.path.startsWith("/" + basePath)) { + co.path = co.path.substring(("/" + basePath).length()); + } + co.subresourceOperation = !co.path.isEmpty(); + } + List opList = operations.get(basePath); + if (opList == null) { + opList = new ArrayList(); + operations.put(basePath, opList); + } + opList.add(co); + co.baseName = basePath; + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java index ac680d5946..f3d61872c0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java @@ -13,7 +13,6 @@ import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; import io.swagger.models.*; import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; import io.swagger.models.properties.RefProperty; @@ -32,6 +31,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JavascriptClientCodegen extends DefaultCodegen implements CodegenConfig { + @SuppressWarnings("hiding") private static final Logger LOGGER = LoggerFactory.getLogger(JavascriptClientCodegen.class); private static final String PROJECT_NAME = "projectName"; @@ -133,6 +133,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo typeMapping.put("double", "Number"); typeMapping.put("number", "Number"); typeMapping.put("DateTime", "Date"); + // binary not supported in JavaScript client right now, using String as a workaround + typeMapping.put("binary", "String"); importMapping.clear(); } @@ -205,6 +207,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", sourceFolder, "ApiClient.js")); } @Override @@ -225,7 +228,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo @Override public String toVarName(String name) { // sanitize name - name = sanitizeName(name); + name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as "final" if("_".equals(name)) { name = "_u"; @@ -256,7 +259,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo @Override public String toModelName(String name) { - name = sanitizeName(name); + name = sanitizeName(name); // FIXME parameter should not be assigned. Also declare it as "final" // model name cannot use reserved keyword, e.g. return if (reservedWords.contains(name)) { @@ -276,7 +279,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo @Override public String toModelImport(String name) { - return name; + return toModelName(name); } @Override @@ -287,8 +290,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo @Override public String getTypeDeclaration(Property p) { if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); + // ArrayProperty ap = (ArrayProperty) p; + // Property inner = ap.getItems(); return getSwaggerType(p); // TODO: + "/* <" + getTypeDeclaration(inner) + "> */"; } else if (p instanceof MapProperty) { MapProperty mp = (MapProperty) p; @@ -305,43 +308,22 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo return "[]"; } else if (p instanceof MapProperty) { return "{}"; - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if (dp.getDefault() != null) { - return dp.getDefault().toString()+"l"; - } - return "null"; - - // added for Javascript } else if (p instanceof RefProperty) { - RefProperty rp = (RefProperty)p; - return "new " +rp.getSimpleRef() + "()"; + return "new " + getTypeDeclaration(p) + "()"; } return super.toDefaultValue(p); } - @Override public String toDefaultValueWithParam(String name, Property p) { - if (p instanceof ArrayProperty) { - return " = new Array();"; - } else if (p instanceof MapProperty) { - return " = {}"; - } else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - return " = data." + name + ";"; - - // added for Javascript - } else if (p instanceof RefProperty) { - RefProperty rp = (RefProperty)p; + if (p instanceof RefProperty) { return ".constructFromObject(data." + name + ");"; } return super.toDefaultValueWithParam(name, p); } - @Override public String getSwaggerType(Property p) { String swaggerType = super.getSwaggerType(p); @@ -382,7 +364,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo 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); + codegenModel = JavascriptClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); } return codegenModel; @@ -437,25 +419,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo @Override public Map postProcessOperations(Map objs) { - if("retrofit".equals(getLibrary())) { - Map operations = (Map) objs.get("operations"); - if (operations != null) { - List ops = (List) operations.get("operation"); - for (CodegenOperation operation : ops) { - if (operation.hasConsumes == Boolean.TRUE) { - Map firstType = operation.consumes.get(0); - if (firstType != null) { - if ("multipart/form-data".equals(firstType.get("mediaType"))) { - operation.isMultipart = Boolean.TRUE; - } - } - } - if (operation.returnType == null) { - operation.returnType = "Void"; - } - } - } - } return objs; } @@ -465,14 +428,14 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo && !languageSpecificPrimitives.contains(type); } - private String findCommonPrefixOfVars(List vars) { + private static String findCommonPrefixOfVars(List vars) { String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()])); // exclude trailing characters that should be part of a valid variable // e.g. ["status-on", "status-off"] => "status-" (not "status-o") return prefix.replaceAll("[a-zA-Z0-9]+\\z", ""); } - private String toEnumVarName(String value) { + private static String toEnumVarName(String value) { String var = value.replaceAll("\\W+", "_").toUpperCase(); if (var.matches("\\d.*")) { return "_" + var; @@ -481,7 +444,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo } } - private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { + private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { // This generator uses inline classes to define enums, which breaks when // dealing with models that have subTypes. To clean this up, we will analyze // the parent and child models, look for enums that match, and remove @@ -529,7 +492,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo return codegenModel; } - private String sanitizePackageName(String packageName) { + private static String sanitizePackageName(String packageName) { // FIXME parameter should not be assigned. Also declare it as "final" packageName = packageName.trim(); packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_"); if(Strings.isNullOrEmpty(packageName)) { 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 deleted file mode 100644 index 089022ecd3..0000000000 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java +++ /dev/null @@ -1,271 +0,0 @@ -package io.swagger.codegen.languages; - -import io.swagger.codegen.*; -import io.swagger.models.Operation; -import io.swagger.models.Path; -import io.swagger.models.Swagger; - -import java.io.File; -import java.util.*; - -public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConfig { - protected String title = "Swagger Server"; - protected String implFolder = "src/main/java"; - - public JaxRSServerCodegen() { - super(); - - sourceFolder = "src/gen/java"; - invokerPackage = "io.swagger.api"; - artifactId = "swagger-jaxrs-server"; - - outputFolder = "generated-code/javaJaxRS"; - modelTemplateFiles.put("model.mustache", ".java"); - apiTemplateFiles.put("api.mustache", ".java"); - apiTemplateFiles.put("apiService.mustache", ".java"); - apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); - apiTemplateFiles.put("apiServiceFactory.mustache", ".java"); - apiPackage = "io.swagger.api"; - modelPackage = "io.swagger.model"; - - additionalProperties.put("title", title); - - embeddedTemplateDir = templateDir = "JavaJaxRS" + File.separator + "jersey1_18"; - - for(int i = 0; i < cliOptions.size(); i++) { - if(CodegenConstants.LIBRARY.equals(cliOptions.get(i).getOpt())) { - cliOptions.remove(i); - break; - } - } - - CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); - library.setDefault(DEFAULT_LIBRARY); - - Map supportedLibraries = new LinkedHashMap(); - - supportedLibraries.put(DEFAULT_LIBRARY, "Jersey core 1.18.1"); -// supportedLibraries.put("jersey2", "Jersey2 core library 2.x"); - library.setEnum(supportedLibraries); - - cliOptions.add(library); - cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC)); - } - - @Override - public CodegenType getTag() { - return CodegenType.SERVER; - } - - @Override - public String getName() { - return "jaxrs"; - } - - @Override - public String getHelp() { - return "Generates a Java JAXRS Server application."; - } - - @Override - public void processOpts() { - super.processOpts(); - - if(additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { - implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); - } - -// if("jersey2".equals(getLibrary())) { -// embeddedTemplateDir = templateDir = "JavaJaxRS" + File.separator + "jersey2"; -// } - - supportingFiles.clear(); - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("ApiException.mustache", - (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiException.java")); - supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache", - (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiOriginFilter.java")); - supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache", - (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiResponseMessage.java")); - supportingFiles.add(new SupportingFile("NotFoundException.mustache", - (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java")); - supportingFiles.add(new SupportingFile("web.mustache", - ("src/main/webapp/WEB-INF"), "web.xml")); - supportingFiles.add(new SupportingFile("StringUtil.mustache", - (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java")); - - if (additionalProperties.containsKey("dateLibrary")) { - setDateLibrary(additionalProperties.get("dateLibrary").toString()); - additionalProperties.put(dateLibrary, "true"); - } - - if("joda".equals(dateLibrary)) { - supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", - (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java")); - supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", - (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java")); - } - else if ("java8".equals(dateLibrary)) { - supportingFiles.add(new SupportingFile("LocalDateTimeProvider.mustache", - (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateTimeProvider.java")); - supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", - (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java")); - } - } - - @Override - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { - String basePath = resourcePath; - if (basePath.startsWith("/")) { - basePath = basePath.substring(1); - } - int pos = basePath.indexOf("/"); - if (pos > 0) { - basePath = basePath.substring(0, pos); - } - - if (basePath == "") { - basePath = "default"; - } else { - if (co.path.startsWith("/" + basePath)) { - co.path = co.path.substring(("/" + basePath).length()); - } - co.subresourceOperation = !co.path.isEmpty(); - } - List opList = operations.get(basePath); - if (opList == null) { - opList = new ArrayList(); - operations.put(basePath, opList); - } - opList.add(co); - co.baseName = basePath; - } - - @Override - public void preprocessSwagger(Swagger swagger) { - if("/".equals(swagger.getBasePath())) { - swagger.setBasePath(""); - } - - String host = swagger.getHost(); - String port = "8080"; - if(host != null) { - String[] parts = host.split(":"); - if(parts.length > 1) { - port = parts[1]; - } - } - this.additionalProperties.put("serverPort", port); - if(swagger != null && swagger.getPaths() != null) { - for(String pathname : swagger.getPaths().keySet()) { - Path path = swagger.getPath(pathname); - if(path.getOperations() != null) { - for(Operation operation : path.getOperations()) { - if(operation.getTags() != null) { - List> tags = new ArrayList>(); - for(String tag : operation.getTags()) { - Map value = new HashMap(); - value.put("tag", tag); - value.put("hasMore", "true"); - tags.add(value); - } - if(tags.size() > 0) { - tags.get(tags.size() - 1).remove("hasMore"); - } - if(operation.getTags().size() > 0) { - String tag = operation.getTags().get(0); - operation.setTags(Arrays.asList(tag)); - } - operation.setVendorExtension("x-tags", tags); - } - } - } - } - } - } - - @Override - public Map postProcessOperations(Map objs) { - Map operations = (Map) objs.get("operations"); - 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).trim(); - operation.returnContainer = "List"; - } - } else if (operation.returnType.startsWith("Map")) { - String rt = operation.returnType; - int end = rt.lastIndexOf(">"); - if (end > 0) { - operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim(); - operation.returnContainer = "Map"; - } - } else if (operation.returnType.startsWith("Set")) { - String rt = operation.returnType; - int end = rt.lastIndexOf(">"); - if (end > 0) { - operation.returnType = rt.substring("Set<".length(), end).trim(); - operation.returnContainer = "Set"; - } - } - } - } - return objs; - } - - @Override - public String toApiName(String name) { - if (name.length() == 0) { - return "DefaultApi"; - } - name = sanitizeName(name); - return camelize(name) + "Api"; - } - - @Override - public String apiFilename(String templateName, String tag) { - - String result = super.apiFilename(templateName, tag); - - if (templateName.endsWith("Impl.mustache")) { - int ix = result.lastIndexOf('/'); - result = result.substring(0, ix) + "/impl" + result.substring(ix, result.length() - 5) + "ServiceImpl.java"; - - result = result.replace(apiFileFolder(), implFileFolder(implFolder)); - } else if (templateName.endsWith("Factory.mustache")) { - int ix = result.lastIndexOf('/'); - result = result.substring(0, ix) + "/factories" + result.substring(ix, result.length() - 5) + "ServiceFactory.java"; - - result = result.replace(apiFileFolder(), implFileFolder(implFolder)); - } else if (templateName.endsWith("Service.mustache")) { - int ix = result.lastIndexOf('.'); - result = result.substring(0, ix) + "Service.java"; - } - - return result; - } - - private String implFileFolder(String output) { - return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/'); - } - - @Override - public boolean shouldOverwrite(String filename) { - return super.shouldOverwrite(filename) && !filename.endsWith("ServiceImpl.java") && !filename.endsWith("ServiceFactory.java"); - } -} 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 f463fbc473..cd2f8980c1 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 @@ -20,7 +20,13 @@ import java.math.BigDecimal; import java.util.*; import java.util.Map.Entry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig { + + private static final Logger LOGGER = LoggerFactory.getLogger(NodeJSServerCodegen.class); + protected String apiVersion = "1.0.0"; protected int serverPort = 8080; protected String projectName = "swagger-server"; @@ -212,7 +218,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig } @SuppressWarnings("unchecked") - private List> getOperations(Map objs) { + private static List> getOperations(Map objs) { List> result = new ArrayList>(); Map apiInfo = (Map) objs.get("apiInfo"); List> apis = (List>) apiInfo.get("apis"); @@ -222,7 +228,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig return result; } - private List> sortOperationsByPath(List ops) { + private static List> sortOperationsByPath(List ops) { Multimap opsByPath = ArrayListMultimap.create(); for (CodegenOperation op : ops) { @@ -284,7 +290,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig }); objs.put("swagger-yaml", Yaml.mapper().registerModule(module).writeValueAsString(swagger)); } catch (JsonProcessingException e) { - e.printStackTrace(); + LOGGER.error(e.getMessage(), e); } } for (Map operations : getOperations(objs)) { 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 dd002a12b1..76739f5ab3 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 @@ -219,12 +219,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toInstantiationType(Property p) { if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); return instantiationTypes.get("map"); } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); return instantiationTypes.get("array"); } else { return null; @@ -312,7 +308,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toModelName(String type) { - type = type.replaceAll("[^0-9a-zA-Z_]", "_"); + type = type.replaceAll("[^0-9a-zA-Z_]", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // language build-in classes if (typeMapping.keySet().contains(type) || @@ -372,7 +368,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toVarName(String name) { // sanitize name - name = sanitizeName(name); + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // if it's all upper case, do noting if (name.matches("^[A-Z_]$")) { @@ -409,6 +405,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { return "_" + name; } + @SuppressWarnings("static-method") public String escapeSpecialWord(String name) { return "var_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java index 9f287ea089..4948d3cf7f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java @@ -7,7 +7,6 @@ import io.swagger.codegen.SupportingFile; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CliOption; import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; @@ -185,14 +184,13 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { public String toVarName(String name) { // return the name in underscore style // PhoneNumber => phone_number - name = underscore(name); + name = underscore(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // parameter name starting with number won't compile // need to escape it by appending _ at the beginning if (name.matches("^\\d.*")) { name = "_" + name; } - return name; } @@ -223,7 +221,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toApiFilename(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // e.g. phone_number_api.rb => PhoneNumberApi.rb return camelize(name) + "Api"; 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 fa5451372c..1046add66e 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 @@ -20,6 +20,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { + @SuppressWarnings("hiding") static Logger LOGGER = LoggerFactory.getLogger(PhpClientCodegen.class); public static final String VARIABLE_NAMING_CONVENTION = "variableNamingConvention"; @@ -119,9 +120,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { } public String toPackagePath(String packageName, String basePath) { - packageName = packageName.replace(invokerPackage, ""); + packageName = packageName.replace(invokerPackage, ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. if (basePath != null && basePath.length() > 0) { - basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar; + basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar; // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. } String regFirstPathSeparator; @@ -326,7 +327,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toVarName(String name) { // sanitize name - name = sanitizeName(name); + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. if ("camelCase".equals(variableNamingConvention)) { // return the name in camelCase style @@ -356,7 +357,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toModelName(String name) { // Note: backslash ("\\") is allowed for e.g. "\\DateTime" - name = name.replaceAll("[^\\w\\\\]+", "_"); + name = name.replaceAll("[^\\w\\\\]+", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // remove dollar sign name = name.replaceAll("$", ""); 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 6bcb9c5d55..dd99a7035f 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 @@ -179,7 +179,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String toVarName(String name) { // sanitize name - name = sanitizeName(name); + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // remove dollar sign name = name.replaceAll("$", ""); @@ -212,7 +212,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String toModelName(String name) { - name = sanitizeName(name); + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // remove dollar sign name = name.replaceAll("$", ""); @@ -294,6 +294,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig * (PEP 0008) Python packages should also have short, all-lowercase names, * although the use of underscores is discouraged. */ + @SuppressWarnings("static-method") public String generatePackageName(String packageName) { return underscore(packageName.replaceAll("[^\\w]+", "")); } 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 ddc4f35346..362af93086 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 @@ -29,6 +29,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { protected String gemName; protected String moduleName; protected String gemVersion = "1.0.0"; + protected String specFolder = "spec"; protected String libFolder = "lib"; protected String gemLicense = "Apache-2.0"; protected String gemHomepage = "http://swagger.io"; @@ -47,6 +48,9 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { apiTemplateFiles.put("api.mustache", ".rb"); embeddedTemplateDir = templateDir = "ruby"; + modelTestTemplateFiles.put("model_test.mustache", ".rb"); + apiTestTemplateFiles.put("api_test.mustache", ".rb"); + typeMapping.clear(); languageSpecificPrimitives.clear(); @@ -186,7 +190,6 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("api_error.mustache", gemFolder, "api_error.rb")); supportingFiles.add(new SupportingFile("configuration.mustache", gemFolder, "configuration.rb")); supportingFiles.add(new SupportingFile("version.mustache", gemFolder, "version.rb")); - String modelFolder = gemFolder + File.separator + modelPackage.replace("/", File.separator); } @@ -208,6 +211,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { /** * Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client". */ + @SuppressWarnings("static-method") public String generateModuleName(String gemName) { return camelize(gemName.replaceAll("[^\\w]+", "_")); } @@ -215,6 +219,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { /** * Generate Ruby gem name from the module name, e.g. use "swagger_client" for "SwaggerClient". */ + @SuppressWarnings("static-method") public String generateGemName(String moduleName) { return underscore(moduleName.replaceAll("[^\\w]+", "")); } @@ -234,6 +239,16 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { return outputFolder + File.separator + libFolder + File.separator + gemName + File.separator + modelPackage.replace("/", File.separator); } + @Override + public String apiTestFileFolder() { + return outputFolder + File.separator + specFolder + File.separator + apiPackage.replace("/", File.separator); + } + + @Override + public String modelTestFileFolder() { + return outputFolder + File.separator + specFolder + File.separator + modelPackage.replace("/", File.separator); + } + @Override public String getTypeDeclaration(Property p) { if (p instanceof ArrayProperty) { @@ -306,7 +321,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toVarName(String name) { // sanitize name - name = sanitizeName(name); + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // if it's all uppper case, convert to lower case if (name.matches("^[A-Z_]*$")) { @@ -333,7 +348,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toModelName(String name) { - name = sanitizeName(name); + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // model name cannot use reserved keyword, e.g. return if (reservedWords.contains(name)) { @@ -360,12 +375,22 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toApiFilename(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // e.g. PhoneNumberApi.rb => phone_number_api.rb return underscore(name) + "_api"; } + @Override + public String toApiTestFilename(String name) { + return toApiName(name) + "_spec"; + } + + @Override + public String toModelTestFilename(String name) { + return toModelName(name) + "_spec"; + } + @Override public String toApiName(String name) { if (name.length() == 0) { 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 40dedb0aea..873d08bce5 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 @@ -165,7 +165,7 @@ public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig public String toVarName(String name) { // return the name in underscore style // PhoneNumber => phone_number - name = underscore(name); + name = underscore(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // parameter name starting with number won't compile // need to escape it by appending _ at the beginning diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java index d512f7deb9..ace38574b5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java @@ -2,7 +2,6 @@ package io.swagger.codegen.languages; import com.fasterxml.jackson.core.JsonProcessingException; -import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; @@ -19,8 +18,13 @@ import java.util.HashSet; import java.util.Map; import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfig { + + private static final Logger LOGGER = LoggerFactory.getLogger(SinatraServerCodegen.class); + protected String gemName; protected String moduleName; protected String gemVersion = "1.0.0"; @@ -149,7 +153,7 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi @Override public String toVarName(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // if it's all uppper case, convert to lower case if (name.matches("^[A-Z_]*$")) { @@ -201,7 +205,7 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi @Override public String toApiFilename(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // e.g. PhoneNumberApi.rb => phone_number_api.rb return underscore(name) + "_api"; @@ -233,7 +237,7 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi try { objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); } catch (JsonProcessingException e) { - e.printStackTrace(); + LOGGER.error(e.getMessage(), e); } } return super.postProcessSupportingFileData(objs); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java index 3810c6895e..8b78bb72a0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java @@ -180,8 +180,7 @@ public class SlimFrameworkServerCodegen extends DefaultCodegen implements Codege @Override public String toVarName(String name) { - // sanitize name - name = sanitizeName(name); + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. if ("camelCase".equals(variableNamingConvention)) { // return the name in camelCase style 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 4d2070a214..848b6f4cae 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 @@ -6,7 +6,7 @@ import io.swagger.models.Operation; import java.io.File; import java.util.*; -public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig { +public class SpringMVCServerCodegen extends JavaClientCodegen { public static final String CONFIG_PACKAGE = "configPackage"; protected String title = "Petstore Server"; protected String configPackage = ""; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java index a98d5fc5b1..b34e6bba5a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java @@ -1,16 +1,22 @@ package io.swagger.codegen.languages; +import java.io.File; + +import org.apache.commons.io.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; import io.swagger.models.Swagger; import io.swagger.util.Json; -import org.apache.commons.io.FileUtils; - -import java.io.File; public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig { + + private static final Logger LOGGER = LoggerFactory.getLogger(SwaggerGenerator.class); + public SwaggerGenerator() { super(); embeddedTemplateDir = templateDir = "swagger"; @@ -41,9 +47,9 @@ public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig { try { String outputFile = outputFolder + File.separator + "swagger.json"; FileUtils.writeStringToFile(new File(outputFile), swaggerString); - System.out.println("wrote file to " + outputFile); + LOGGER.debug("wrote file to " + outputFile); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e.getMessage(), e); } } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java index 9c4680112e..5442000280 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java @@ -1,16 +1,22 @@ package io.swagger.codegen.languages; +import java.io.File; + +import org.apache.commons.io.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; import io.swagger.models.Swagger; import io.swagger.util.Yaml; -import org.apache.commons.io.FileUtils; - -import java.io.File; public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfig { + + private static final Logger LOGGER = LoggerFactory.getLogger(SwaggerYamlGenerator.class); + public SwaggerYamlGenerator() { super(); embeddedTemplateDir = templateDir = "swagger"; @@ -40,9 +46,9 @@ public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfi String swaggerString = Yaml.mapper().writeValueAsString(swagger); String outputFile = outputFolder + File.separator + "swagger.yaml"; FileUtils.writeStringToFile(new File(outputFile), swaggerString); - System.out.println("wrote file to " + outputFile); + LOGGER.debug("wrote file to " + outputFile); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e.getMessage(), e); } } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 1beb9a3b23..4359905acf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -270,6 +270,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { return codegenProperty; } + @SuppressWarnings("static-method") public String toSwiftyEnumName(String value) { // Prevent from breaking properly cased identifier if (value.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) { @@ -289,7 +290,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { @Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { - path = normalizePath(path); + path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. List parameters = operation.getParameters(); parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate() { @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java index d7b7d13f63..208461710f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java @@ -131,12 +131,8 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String toInstantiationType(Property p) { if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); return instantiationTypes.get("map"); } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); return instantiationTypes.get("array"); } else { return null; @@ -220,12 +216,8 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig } else if (p instanceof DecimalProperty) { return "new Long()"; } else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); return "new HashMap()"; } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); return "new ArrayList()"; } // else diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/utils/OptionUtils.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/utils/OptionUtils.java similarity index 96% rename from modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/utils/OptionUtils.java rename to modules/swagger-codegen/src/main/java/io/swagger/codegen/utils/OptionUtils.java index 34d5672741..52afb51c89 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/utils/OptionUtils.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/utils/OptionUtils.java @@ -1,4 +1,4 @@ -package io.swagger.codegen.cmd.utils; +package io.swagger.codegen.utils; import org.apache.commons.lang3.tuple.Pair; diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 9f55d5a14d..0ac7e31d38 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -452,34 +452,51 @@ public class ApiClient { } } - private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + private String buildUrl(String path, List queryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); - if (body != null && !formParams.isEmpty()){ + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + return url.toString(); + } + + private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + if (body != null && !formParams.isEmpty()) { throw new ApiException(500, "Cannot have body and form params"); } updateParamsForAuth(authNames, queryParams, headerParams); - 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); - + final String url = buildUrl(path, queryParams); Builder builder; - if (accept == null) - builder = httpClient.resource(basePath + path + querystring).getRequestBuilder(); - else - builder = httpClient.resource(basePath + path + querystring).accept(accept); + if (accept == null) { + builder = httpClient.resource(url).getRequestBuilder(); + } else { + builder = httpClient.resource(url).accept(accept); + } for (String key : headerParams.keySet()) { builder = builder.header(key, headerParams.get(key)); 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 index 83e92921a8..ec3c7a7f7c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -495,7 +495,9 @@ public class ApiClient { public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); - WebTarget target = httpClient.target(this.basePath).path(path); + // Not using `.target(this.basePath).path(path)` below, + // to support (constant) query string in `path`, e.g. "/posts?draft=1" + WebTarget target = httpClient.target(this.basePath + path); if (queryParams != null) { for (Pair queryParam : queryParams) { diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index 651a77ca23..34b0e4b33b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -657,8 +657,8 @@ public class ApiClient { } /** - * Deserialize response body to Java object, according to the Content-Type - * response header. + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. * * @param response HTTP response * @param returnType The type of the Java object @@ -667,12 +667,21 @@ public class ApiClient { * or the Content-Type of the response is not supported. */ public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) + if (response == null || returnType == null) { return null; + } - // Handle file downloading. - if (returnType.equals(File.class)) + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. return (T) downloadFileFromResponse(response); + } String respBody; try { @@ -684,8 +693,9 @@ public class ApiClient { throw new ApiException(e); } - if (respBody == null || "".equals(respBody)) + if (respBody == null || "".equals(respBody)) { return null; + } String contentType = response.headers().get("Content-Type"); if (contentType == null) { @@ -707,20 +717,29 @@ public class ApiClient { } /** - * Serialize the given Java object into request body string, according to the - * request Content-Type. + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. * * @param obj The Java object * @param contentType The request Content-Type - * @return The serialized string + * @return The serialized request body * @throws ApiException If fail to serialize the given object */ - public String serialize(Object obj, String contentType) throws ApiException { - if (isJsonMime(contentType)) { - if (obj != null) - return json.serialize(obj); - else - return null; + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create(MediaType.parse(contentType), (File) obj); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = json.serialize(obj); + } else { + content = null; + } + return RequestBody.create(MediaType.parse(contentType), content); } else { throw new ApiException("Content type \"" + contentType + "\" is not supported"); } @@ -909,7 +928,7 @@ public class ApiClient { reqBody = RequestBody.create(MediaType.parse(contentType), ""); } } else { - reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType)); + reqBody = serialize(body, contentType); } Request request = null; @@ -932,20 +951,27 @@ public class ApiClient { * @return The full URL */ public String buildUrl(String path, List queryParams) { - StringBuilder query = new StringBuilder(); - if (queryParams != null) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; for (Pair param : queryParams) { if (param.getValue() != null) { - if (query.toString().length() == 0) - query.append("?"); - else - query.append("&"); + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } String value = parameterToString(param.getValue()); - query.append(escapeString(param.getName())).append("=").append(escapeString(value)); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); } } } - return basePath + path + query.toString(); + + return url.toString(); } /** diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache index 56e83f7d91..6cd8aa399f 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache @@ -13,6 +13,7 @@ import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuil import retrofit.Converter; import retrofit.Retrofit; import retrofit.GsonConverterFactory; +{{#useRxJava}}import retrofit.RxJavaCallAdapterFactory;{{/useRxJava}} import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -22,6 +23,7 @@ import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.ResponseBody; + import {{invokerPackage}}.auth.HttpBasicAuth; import {{invokerPackage}}.auth.ApiKeyAuth; import {{invokerPackage}}.auth.OAuth; @@ -117,6 +119,7 @@ public class ApiClient { .Builder() .baseUrl(baseUrl) .client(okClient) + {{#useRxJava}}.addCallAdapterFactory(RxJavaCallAdapterFactory.create()){{/useRxJava}} .addConverterFactory(GsonCustomConverterFactory.create(gson)); } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache index e358dc5f02..7786ba0f88 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache @@ -2,8 +2,10 @@ package {{package}}; import {{invokerPackage}}.CollectionFormats.*; -import retrofit.Call; +{{#useRxJava}}import rx.Observable;{{/useRxJava}} +{{^useRxJava}}import retrofit.Call;{{/useRxJava}} import retrofit.http.*; + import com.squareup.okhttp.RequestBody; {{#imports}}import {{import}}; @@ -28,7 +30,7 @@ public interface {{classname}} { {{#formParams}}{{#-first}} {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") - Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}} + {{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}} {{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} );{{/hasMore}}{{/allParams}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache index cf0047cf28..b4f843603e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache @@ -20,7 +20,7 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' - + android { compileSdkVersion 22 buildToolsVersion '22.0.0' @@ -32,7 +32,7 @@ if(hasProperty('target') && target == 'android') { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } - + // Rename the aar correctly libraryVariants.all { variant -> variant.outputs.each { output -> @@ -44,7 +44,7 @@ if(hasProperty('target') && target == 'android') { } } } - + afterEvaluate { android.libraryVariants.all { variant -> def task = project.tasks.create "jar${variant.name.capitalize()}", Jar @@ -56,12 +56,12 @@ if(hasProperty('target') && target == 'android') { artifacts.add('archives', task); } } - + task sourcesJar(type: Jar) { from android.sourceSets.main.java.srcDirs classifier = 'sources' } - + artifacts { archives sourcesJar } @@ -70,16 +70,16 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 - + +sourceCompatibility = JavaVersion.VERSION_1_7 +targetCompatibility = JavaVersion.VERSION_1_7 + install { repositories.mavenInstaller { pom.artifactId = '{{artifactId}}' } } - + task execute(type:JavaExec) { main = System.getProperty('mainClass') classpath = sourceSets.main.runtimeClasspath @@ -93,14 +93,26 @@ ext { gson_version = "2.4" swagger_annotations_version = "1.5.0" junit_version = "4.12" +{{#useRxJava}} + rx_java_version = "1.0.15" +{{/useRxJava}} +{{^useRxJava}}{{/useRxJava}} } dependencies { compile "com.squareup.okhttp:okhttp:$okhttp_version" + compile "com.squareup.retrofit:retrofit:$retrofit_version" - compile "com.google.code.gson:gson:$gson_version" compile "com.squareup.retrofit:converter-gson:$retrofit_version" +{{#useRxJava}} + compile "com.squareup.retrofit:adapter-rxjava:$retrofit_version" + compile "io.reactivex:rxjava:$rx_java_version" +{{/useRxJava}} +{{^useRxJava}}{{/useRxJava}} + + compile "com.google.code.gson:gson:$gson_version" compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + testCompile "junit:junit:$junit_version" } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache index a155d04ef8..ef322cccb0 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache @@ -100,8 +100,9 @@ maven-compiler-plugin 2.3.2 - 1.6 - 1.6 + + 1.7 + 1.7 @@ -137,6 +138,18 @@ okhttp ${okhttp-version} + {{#useRxJava}} + + io.reactivex + rxjava + ${rxjava-version} + + + com.squareup.retrofit + adapter-rxjava + ${retrofit-version} + + {{/useRxJava}} @@ -149,6 +162,7 @@ 1.5.0 2.0.0-beta2 + {{#useRxJava}}1.0.15{{/useRxJava}} 2.5.0 2.4 1.0.0 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/allowableValues.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/allowableValues.mustache new file mode 100644 index 0000000000..a48256d027 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/allowableValues.mustache @@ -0,0 +1 @@ +{{#allowableValues}}allowableValues="{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}{{^values}}range=[{{#min}}{{.}}{{/min}}{{^min}}-infinity{{/min}}, {{#max}}{{.}}{{/max}}{{^max}}infinity{{/max}}]{{/values}}"{{/allowableValues}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache new file mode 100644 index 0000000000..869d1aa63d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache @@ -0,0 +1,22 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import javax.ws.rs.*; +import javax.ws.rs.core.Response; + +@Path("{{contextPath}}") +public interface {{classname}} { +{{#operations}} +{{#operation}} + @{{httpMethod}} + {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} + {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} + {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} + public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}); +{{/operation}} +} +{{/operations}} + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/bodyParams.mustache new file mode 100644 index 0000000000..c7d1abfe52 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}{{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/entityModel.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/entityModel.mustache new file mode 100644 index 0000000000..9aea77c5bf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/entityModel.mustache @@ -0,0 +1,51 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import javax.xml.bind.annotation.XmlRootElement; + +{{#models}} + +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +@XmlRootElement(name="{{classname}}") +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { + {{#vars}} + {{#isEnum}} + public enum {{datatypeWithEnum}} { + {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} + }; + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} + private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} + + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @JsonProperty("{{name}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + {{/vars}} + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); + {{/vars}}sb.append("}\n"); + return sb.toString(); + } +} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumOuterClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumOuterClass.mustache new file mode 100644 index 0000000000..7aea7b92f2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumOuterClass.mustache @@ -0,0 +1,3 @@ +public enum {{classname}} { + {{#allowableValues}}{{.}}{{^-last}}, {{/-last}}{{/allowableValues}} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/formParams.mustache new file mode 100644 index 0000000000..c129a925e9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/formParams.mustache @@ -0,0 +1,2 @@ +{{#isFormParam}}{{#notFile}}@Multipart(value = "{{paramName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @Multipart(value = "{{paramName}}"{{^required}}, required = false{{/required}}) InputStream {{paramName}}InputStream, + @Multipart(value = "{{paramName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/generatedAnnotation.mustache new file mode 100644 index 0000000000..49110fc1ad --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/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/cxf/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/headerParams.mustache new file mode 100644 index 0000000000..25d690c90e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}@HeaderParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache new file mode 100644 index 0000000000..578cd064df --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache @@ -0,0 +1,15 @@ +package {{package}}; + +{{#imports}}import{{import}}; +{{/imports}} + +{{#serializableModel}}import java.io.Serializable;{{/serializableModel}} +{{#models}} +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +{{#isEnum}}{{>enumOuterClass}}{{/isEnum}} +{{^isEnum}}{{>pojo}}{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pathParams.mustache new file mode 100644 index 0000000000..ba153467a6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}@PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/project/build.properties b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/project/build.properties new file mode 100644 index 0000000000..a8c2f849be --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/project/build.properties @@ -0,0 +1 @@ +sbt.version=0.12.0 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/queryParams.mustache new file mode 100644 index 0000000000..be8cee8dfe --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}@QueryParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} \ 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 a882c00697..7560d5c083 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache @@ -8,7 +8,6 @@ import {{modelPackage}}.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.Authorization; import io.swagger.annotations.AuthorizationScope; @@ -44,8 +43,8 @@ public class {{classname}} { }{{/isOAuth}}){{#hasMore}}, {{/hasMore}}{{/authMethods}} }{{/hasAuthMethods}}) - @ApiResponses(value = { {{#responses}} - @ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},{{/hasMore}}{{/responses}} }) + @io.swagger.annotations.ApiResponses(value = { {{#responses}} + @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},{{/hasMore}}{{/responses}} }) @RequestMapping(value = "{{path}}", {{#hasProduces}}produces = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}} {{#hasConsumes}}consumes = { {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache index c4a71c199c..60933fa47f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache @@ -75,31 +75,6 @@ slf4j-log4j12 ${slf4j-version} - - com.sun.jersey - jersey-core - ${jersey-version} - - - com.sun.jersey - jersey-json - ${jersey-version} - - - com.sun.jersey - jersey-servlet - ${jersey-version} - - - com.sun.jersey.contribs - jersey-multipart - ${jersey-version} - - - com.sun.jersey - jersey-server - ${jersey-version} - @@ -142,22 +117,14 @@ ${servlet-api-version} - - - jcenter-snapshots - jcenter - http://oss.jfrog.org/artifactory/oss-snapshot-local/ - - - 1.5.4 + 1.5.6 9.2.9.v20150224 1.13 1.6.3 - 1.6.1 4.8.1 2.5 - 2.0.4-SNAPSHOT - 4.0.9.RELEASE + 2.3.1 + 4.1.8.RELEASE \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache new file mode 100644 index 0000000000..006d8d50eb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache @@ -0,0 +1,183 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['superagent'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('superagent')); + } else { + // Browser globals (root is window) + if (!root.{{moduleName}}) { + root.{{moduleName}} = {}; + } + root.{{moduleName}}.ApiClient = factory(root.superagent); + } +}(this, function(superagent) { + 'use strict'; + + var ApiClient = function ApiClient() { + /** + * The base path to put in front of every API call's (relative) path. + */ + this.basePath = '{{basePath}}'.replace(/\/+$/, ''); + + /** + * The default HTTP headers to be included for all API calls. + */ + this.defaultHeaders = {}; + }; + + ApiClient.prototype.paramToString = function paramToString(param) { + if (param == null) { + // return empty string for null and undefined + return ''; + } else { + return param.toString(); + } + }; + + /** + * Build full URL by appending the given path to base path and replacing + * path parameter placeholders with parameter values. + * NOTE: query parameters are not handled here. + */ + ApiClient.prototype.buildUrl = function buildUrl(path, pathParams) { + if (!path.match(/^\//)) { + path = '/' + path; + } + var url = this.basePath + path; + var _this = this; + url = url.replace(/\{([\w-]+)\}/g, function(fullMatch, key) { + var value; + if (pathParams.hasOwnProperty(key)) { + value = _this.paramToString(pathParams[key]); + } else { + value = fullMatch; + } + return encodeURIComponent(value); + }); + return url; + }; + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + ApiClient.prototype.isJsonMime = function isJsonMime(mime) { + return Boolean(mime != null && mime.match(/^application\/json(;.*)?$/i)); + }; + + /** + * Choose a MIME from the given MIMEs with JSON preferred, + * i.e. return JSON if included, otherwise return the first one. + */ + ApiClient.prototype.jsonPreferredMime = function jsonPreferredMime(mimes) { + var len = mimes.length; + for (var i = 0; i < len; i++) { + if (this.isJsonMime(mimes[i])) { + return mimes[i]; + } + } + return mimes[0]; + }; + + /** + * Check if the given parameter value is like file content. + */ + ApiClient.prototype.isFileParam = function isFileParam(param) { + // Buffer or fs.ReadStream in Node.js + if (typeof module === 'object' && module.exports && + (param instanceof Buffer || param instanceof require('fs').ReadStream)) { + return true; + } + // Blob in browser + if (typeof Blob === 'function' && param instanceof Blob) { + return true; + } + // File in browser (it seems File object is also instance of Blob, but keep this for safe) + if (typeof File === 'function' && param instanceof File) { + return true; + } + return false; + }; + + /** + * Normalize parameters values: + * remove nils, + * keep files and arrays, + * format to string with `paramToString` for other cases. + */ + ApiClient.prototype.normalizeParams = function normalizeParams(params) { + var newParams = {}; + for (var key in params) { + if (params.hasOwnProperty(key) && params[key] != null) { + var value = params[key]; + if (this.isFileParam(value) || Array.isArray(value)) { + newParams[key] = value; + } else { + newParams[key] = this.paramToString(value); + } + } + } + return newParams; + }; + + ApiClient.prototype.callApi = function callApi(path, httpMethod, pathParams, + queryParams, headerParams, formParams, bodyParam, contentTypes, accepts, + callback) { + var url = this.buildUrl(path, pathParams); + var request = superagent(httpMethod, url); + + // set query parameters + request.query(this.normalizeParams(queryParams)); + + // set header parameters + request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); + + var contentType = this.jsonPreferredMime(contentTypes); + if (contentType) { + request.type(contentType); + } else if (!request.header['Content-Type']) { + request.type('application/json'); + } + + if (contentType === 'application/x-www-form-urlencoded') { + request.send(this.normalizeParams(formParams)); + } else if (contentType == 'multipart/form-data') { + var _formParams = this.normalizeParams(formParams); + for (var key in _formParams) { + if (_formParams.hasOwnProperty(key)) { + if (this.isFileParam(_formParams[key])) { + // file field + request.attach(key, _formParams[key]); + } else { + request.field(key, _formParams[key]); + } + } + } + } else if (bodyParam) { + request.send(bodyParam); + } + + var accept = this.jsonPreferredMime(accepts); + if (accept) { + request.accept(accept); + } + + request.end(function(error, response) { + if (callback) { + var data = response && response.body; + callback(error, data, response); + } + }); + + return request; + }; + + ApiClient.default = new ApiClient(); + + return ApiClient; +})); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache index 9957fc4e2c..a0ac34c48d 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache @@ -1,125 +1,86 @@ -// require files in Node.js environment -var ${{#imports}}, {{import}}{{/imports}}; -if (typeof module === 'object' && module.exports) { - $ = require('jquery');{{#imports}} - {{import}} = require('../model/{{import}}.js');{{/imports}} -} - -// export module for AMD -if ( typeof define === "function" && define.amd ) { - define(['jquery'{{#imports}}, '{{import}}'{{/imports}}], function(${{#imports}}, {{import}}{{/imports}}) { - return {{classname}}; - }); -} - -var {{classname}} = function {{classname}}() { - var self = this; - {{#operations}} - {{#operation}} - /** - * {{summary}} - * {{notes}} -{{#allParams}} * @param {{=<% %>=}}{<% dataType %>} <%={{ }}=%> {{paramName}} {{description}} -{{/allParams}} * @param {function} callback the callback function - * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} - */ - self.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}callback) { - var {{localVariablePrefix}}postBody = {{#bodyParam}}{{^isBinary}}JSON.stringify({{paramName}}){{/isBinary}}{{#isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; - var {{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}}"); - var errorRequiredMsg = "Missing the required parameter '{{paramName}}' when calling {{nickname}}"; - throw errorRequiredMsg; - } - {{/required}}{{/allParams}} - // create path and map variables - var basePath = '{{basePath}}'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient'{{#imports}}, '../model/{{import}}'{{/imports}}], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient'){{#imports}}, require('../model/{{import}}'){{/imports}}); + } else { + // Browser globals (root is window) + if (!root.{{moduleName}}) { + root.{{moduleName}} = {}; } - - var {{localVariablePrefix}}path = basePath + replaceAll(replaceAll("{{{path}}}", "\\{format\\}","json"){{#pathParams}} -, "\\{" + "{{baseName}}" + "\\}", encodeURIComponent({{{paramName}}}.toString()){{/pathParams}}); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - {{#queryParams}} - queryParams.{{baseName}} = {{paramName}}; - {{/queryParams}} - {{#headerParams}}if ({{paramName}} != null) - {{localVariablePrefix}}headerParams.put("{{baseName}}", {{paramName}}); - {{/headerParams}} - {{#formParams}}if ({{paramName}} != null) - {{localVariablePrefix}}formParams.put("{{baseName}}", {{paramName}}); - {{/formParams}} - - path += createQueryString(queryParams); - - var options = {type: "{{httpMethod}}", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ - {{#returnType}} - /** - * @returns {{{returnType}}} - */ - {{#returnTypeIsPrimitive}}var myResponse = response;{{/returnTypeIsPrimitive}} - {{^returnTypeIsPrimitive}}var myResponse = new {{{returnType}}}(); - myResponse.constructFromObject(response);{{/returnTypeIsPrimitive}} - if (callback) { - callback(myResponse, textStatus, jqXHR); - } - {{/returnType}}{{^returnType}} - if (callback) { - callback(response, textStatus, jqXHR); - } - {{/returnType}} - }); - - return request; + root.{{moduleName}}.{{classname}} = factory(root.{{moduleName}}.ApiClient{{#imports}}, root.{{moduleName}}.{{import}}{{/imports}}); } - {{/operation}} - {{/operations}} +}(this, function(ApiClient{{#imports}}, {{import}}{{/imports}}) { + 'use strict'; - function replaceAll (haystack, needle, replace) { - var result= haystack; - if (needle !=null && replace!=null) { - result= haystack.replace(new RegExp(needle, 'g'), replace); - } - return result; - } + var {{classname}} = function {{classname}}(apiClient) { + this.apiClient = apiClient || ApiClient.default; - function createQueryString (queryParams) { - var queryString =''; - var i = 0; - for (var queryParamName in queryParams) { - if (i==0) { - queryString += '?' ; - } else { - queryString += '&' ; - } - - queryString += queryParamName + '=' + encodeURIComponent(queryParams[queryParamName]); - i++; - } - - return queryString; - } -} + var self = this; + {{#operations}} + {{#operation}} + /** + * {{summary}} + * {{notes}} + {{#allParams}} * @param {{=<% %>=}}{<% dataType %>} <%={{ }}=%> {{paramName}} {{description}} + {{/allParams}} * @param {function} callback the callback function, accepting three arguments: error, data, response{{#returnType}} + * data is of type: {{{returnType}}}{{/returnType}} + */ + self.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}callback) { + var postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw "Missing the required parameter '{{paramName}}' when calling {{nickname}}"; + } + {{/required}}{{/allParams}} -// export module for Node.js -if (typeof module === 'object' && module.exports) { - module.exports = {{classname}}; -} + {{=< >=}} + var pathParams = {<#pathParams> + '': <#hasMore>, + }; + var queryParams = {<#queryParams> + '': <#hasMore>, + }; + var headerParams = {<#headerParams> + '': <#hasMore>, + }; + var formParams = {<#formParams> + '': <#hasMore>, + }; + + var contentTypes = [<#consumes>''<#hasMore>, ]; + var accepts = [<#produces>''<#hasMore>, ]; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) {<#returnType><#returnTypeIsPrimitive> + callback(error, data, response);<^returnTypeIsPrimitive><#isListContainer> + // TODO: support deserializing array of models + callback(error, data, response);<^isListContainer> + if (!error && data) { + var result = new <&returnType>(); + result.constructFromObject(data); + callback(error, result, response); + } else { + callback(error, data, response); + }<^returnType> + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '<&path>', '', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + <={{ }}=> + } + {{/operation}} + {{/operations}} + }; + + return {{classname}}; +})); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/index.mustache b/modules/swagger-codegen/src/main/resources/Javascript/index.mustache index a0207a6cc9..5d03b68aed 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/index.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/index.mustache @@ -1,10 +1,17 @@ -if (typeof module === 'object' && module.exports) { - var {{moduleName}} = {}; - {{#models}} - {{moduleName}}.{{importPath}} = require('./model/{{importPath}}.js'); - {{/models}} - {{#apiInfo}}{{#apis}} - {{moduleName}}.{{importPath}} = require('./api/{{importPath}}.js'); - {{/apis}}{{/apiInfo}} - module.exports = {{moduleName}}; -} \ No newline at end of file +(function(factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['./ApiClient'{{#models}}, './model/{{importPath}}'{{/models}}{{#apiInfo}}{{#apis}}, './api/{{importPath}}'{{/apis}}{{/apiInfo}}], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('./ApiClient'){{#models}}, require('./model/{{importPath}}'){{/models}}{{#apiInfo}}{{#apis}}, require('./api/{{importPath}}'){{/apis}}{{/apiInfo}}); + } +}(function(ApiClient{{#models}}, {{importPath}}{{/models}}{{#apiInfo}}{{#apis}}, {{importPath}}{{/apis}}{{/apiInfo}}) { + 'use strict'; + + return { + ApiClient: ApiClient{{#models}}, + {{importPath}}: {{importPath}}{{/models}}{{#apiInfo}}{{#apis}}, + {{importPath}}: {{importPath}}{{/apis}}{{/apiInfo}} + }; +})); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/model.mustache b/modules/swagger-codegen/src/main/resources/Javascript/model.mustache index 0588d03a8c..a5778003c9 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/model.mustache @@ -1,75 +1,79 @@ -// require files in Node.js environment -{{#imports}} -var {{import}};{{/imports}} -if (typeof module === 'object' && module.exports) { - {{#imports}} - {{import}} = require('./{{import}}.js');{{/imports}} -} - -{{#models}}{{#model}} -{{#vars}}{{#isEnum}}{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} -{{>enumClass}}{{/items}}*/{{/items.isEnum}}{{/vars}} - -//export module -if ( typeof define === "function" && define.amd ) { - define('{{classname}}', ['jquery'{{#vars}}{{^isPrimitiveType}}{{^-last}}, {{/-last}}'{{datatypeWithEnum}}'{{/isPrimitiveType}}{{/vars}}], - function(${{#vars}}{{^isPrimitiveType}}{{^-last}}, {{/-last}}{{datatypeWithEnum}}{{/isPrimitiveType}}{{/vars}}) { - return {{classname}}; - }); -} - -{{#description}}/** - * {{description}} - **/{{/description}} -var {{classname}} = function {{classname}}({{#mandatory}}{{this}}{{^-last}}, {{/-last}}{{/mandatory}}) { {{#parent}}/* extends {{{parent}}}*/{{/parent}} - var self = this; - {{#vars}} - /**{{#description}} - * {{{description}}}{{/description}} - * datatype: {{{datatypeWithEnum}}}{{#required}} - * required{{/required}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ - self.{{name}} = {{#required}}{{name}}{{/required}}{{^required}}{{{defaultValue}}}{{/required}}; - {{/vars}} - - self.constructFromObject = function(data) { - if (!data) { - return; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([undefined{{#imports}}, './{{import}}'{{/imports}}], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(undefined{{#imports}}, require('./{{import}}'){{/imports}}); + } else { + // Browser globals (root is window) + if (!root.{{moduleName}}) { + root.{{moduleName}} = {}; } + factory(root.{{moduleName}}{{#imports}}, root.{{moduleName}}.{{import}}{{/imports}}); + } +}(this, function(module{{#imports}}, {{import}}{{/imports}}) { + 'use strict'; + + {{#models}}{{#model}} + {{#vars}}{{#isEnum}}{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} + {{>enumClass}}{{/items}}*/{{/items.isEnum}}{{/vars}} + + {{#description}}/** + * {{description}} + **/{{/description}} + var {{classname}} = function {{classname}}({{#mandatory}}{{this}}{{^-last}}, {{/-last}}{{/mandatory}}) { {{#parent}}/* extends {{{parent}}}*/{{/parent}} + var self = this; {{#vars}} - self.{{name}}{{{defaultValueWithParam}}} + /**{{#description}} + * {{{description}}}{{/description}} + * datatype: {{{datatypeWithEnum}}}{{#required}} + * required{{/required}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + self.{{name}} = {{#required}}{{name}}{{/required}}{{^required}}{{{defaultValue}}}{{/required}}; {{/vars}} + + self.constructFromObject = function(data) { + if (!data) { + return; + } + {{#vars}} + self.{{name}}{{{defaultValueWithParam}}} + {{/vars}} + } + + {{#vars}} + /**{{#description}} + * get {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + * @return {{=<% %>=}}{<% datatypeWithEnum %>}<%={{ }}=%> + **/ + self.{{getter}} = function() { + return self.{{name}}; + } + + /**{{#description}} + * set {{{description}}}{{/description}} + * @param {{=<% %>=}}{<% datatypeWithEnum %>}<%={{ }}=%> {{name}} + **/ + self.{{setter}} = function ({{name}}) { + self.{{name}} = {{name}}; + } + {{/vars}} + + self.toJson = function () { + return JSON.stringify(self); + } + }; + + if (module) { + module.{{classname}} = {{classname}}; } - {{#vars}} - /**{{#description}} - * get {{{description}}}{{/description}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - * @return {{=<% %>=}}{<% datatypeWithEnum %>}<%={{ }}=%> - **/ - self.{{getter}} = function() { - return self.{{name}}; - } - - /**{{#description}} - * set {{{description}}}{{/description}} - * @param {{=<% %>=}}{<% datatypeWithEnum %>}<%={{ }}=%> {{name}} - **/ - self.{{setter}} = function ({{name}}) { - self.{{name}} = {{name}}; - } - {{/vars}} - - self.toJson = function () { - return JSON.stringify(self); - } -} - -if (typeof module === 'object' && module.exports) { - module.exports = {{classname}}; -} -{{/model}} -{{/models}} + return {{classname}}; + {{/model}} + {{/models}} +})); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/package.mustache b/modules/swagger-codegen/src/main/resources/Javascript/package.mustache index c77ee83570..8710d9d2be 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/package.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/package.mustache @@ -8,13 +8,10 @@ "test": "./node_modules/mocha/bin/mocha --recursive" }, "dependencies": { - "jquery": "~2.1.4" + "superagent": "1.7.1" }, "devDependencies": { "mocha": "~2.3.4", - "expect.js": "~0.3.1", - "mockrequire": "~0.0.5", - "domino": "~1.0.20", - "xmlhttprequest": "~1.8.0" + "expect.js": "~0.3.1" } } diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index 5d8a4f0fc6..18015a9328 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -4,10 +4,12 @@ io.swagger.codegen.languages.CSharpClientCodegen io.swagger.codegen.languages.DartClientCodegen io.swagger.codegen.languages.FlashClientCodegen io.swagger.codegen.languages.FlaskConnexionCodegen +io.swagger.codegen.languages.GoClientCodegen io.swagger.codegen.languages.JavaClientCodegen -io.swagger.codegen.languages.JavascriptClientCodegen -io.swagger.codegen.languages.JaxRSServerCodegen +io.swagger.codegen.languages.JavaJerseyServerCodegen +io.swagger.codegen.languages.JavaCXFServerCodegen io.swagger.codegen.languages.JavaInflectorServerCodegen +io.swagger.codegen.languages.JavascriptClientCodegen io.swagger.codegen.languages.JMeterCodegen io.swagger.codegen.languages.NodeJSServerCodegen io.swagger.codegen.languages.ObjcClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache index c533c6739a..b7d9296215 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache @@ -18,7 +18,7 @@ namespace {{package}} { * {{{description}}} */ {{/description}} - {{name}}{{^required}}?{{/required}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; + "{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; {{/vars}} } diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index a80aa388d2..a4f2bf6202 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -22,7 +22,7 @@ export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ * {{{description}}} */ {{/description}} - {{name}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; + "{{name}}": {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; {{/vars}} } diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache index 1d70000c1d..d98ef59be1 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache @@ -17,9 +17,12 @@ import com.android.volley.VolleyError; import org.apache.http.HttpEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; -import java.util.Map; +import java.util.ArrayList; import java.util.HashMap; -import java.io.File; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; {{#operations}} public class {{classname}} { @@ -44,11 +47,93 @@ public class {{classname}} { {{#operation}} /** - * {{summary}} - * {{notes}} + * {{summary}} + * {{notes}} {{#allParams}} * @param {{paramName}} {{description}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} - */ + */ + public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + VolleyError error = new VolleyError("Missing the required parameter '{{paramName}}' when calling {{nickname}}", + new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}")); + } + {{/required}}{{/allParams}} + + // create path and map variables + String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + {{#queryParams}} + queryParams.addAll(ApiInvoker.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/queryParams}} + + {{#headerParams}} + headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); + {{/headerParams}} + + String[] contentTypes = { + {{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}} + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + {{#formParams}}{{#notFile}} + if ({{paramName}} != null) { + builder.addTextBody("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), ApiInvoker.TEXT_PLAIN_UTF8); + } + {{/notFile}}{{#isFile}} + if ({{paramName}} != null) { + builder.addBinaryBody("{{baseName}}", {{paramName}}); + } + {{/isFile}}{{/formParams}} + + HttpEntity httpEntity = builder.build(); + postBody = httpEntity; + } else { + // normal form params + {{#formParams}}{{#notFile}}formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}} + {{/formParams}} + } + + String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + + try { + String response = apiInvoker.invokeAPI (basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType, authNames); + if(response != null){ + return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}}; + } else { + return {{#returnType}}null{{/returnType}}; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if(ex.getCause() instanceof VolleyError) { + throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * {{summary}} + * {{notes}} +{{#allParams}} * @param {{paramName}} {{description}}{{/allParams}} + */ public void {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}, {{/hasMore}}{{/allParams}}final Response.Listener<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}String{{/returnType}}> responseListener, final Response.ErrorListener errorListener) { Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache index 04e6fdbc05..2a04c1c86b 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache @@ -1,10 +1,16 @@ package {{invokerPackage}}; -import android.content.Context; - +import com.android.volley.Cache; +import com.android.volley.Network; +import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; -import com.android.volley.toolbox.Volley; +import com.android.volley.ResponseDelivery; +import com.android.volley.toolbox.BasicNetwork; +import com.android.volley.toolbox.HttpStack; +import com.android.volley.toolbox.HurlStack; +import com.android.volley.toolbox.NoCache; +import com.android.volley.toolbox.RequestFuture; import com.google.gson.JsonParseException; import org.apache.http.Consts; @@ -22,6 +28,9 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import {{invokerPackage}}.auth.Authentication; import {{invokerPackage}}.auth.ApiKeyAuth; @@ -36,11 +45,12 @@ public class ApiInvoker { private static ApiInvoker INSTANCE; private Map defaultHeaderMap = new HashMap(); - private Context context; private RequestQueue mRequestQueue; private Map authentications; + private int connectionTimeout; + /** Content type "text/plain" with UTF-8 encoding. */ public static final ContentType TEXT_PLAIN_UTF8 = ContentType.create("text/plain", Consts.UTF_8); @@ -165,8 +175,16 @@ public class ApiInvoker { return params; } - public static void initializeInstance(Context context) { - INSTANCE = new ApiInvoker(context); + public static void initializeInstance() { + initializeInstance(null); + } + + public static void initializeInstance(Cache cache) { + initializeInstance(cache, null, 0, null, 30); + } + + public static void initializeInstance(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) { + INSTANCE = new ApiInvoker(cache, network, threadPoolSize, delivery, connectionTimeout); setUserAgent("Android-Volley-Swagger"); // Setup authentications (key: authentication name, value: authentication). @@ -178,17 +196,27 @@ public class ApiInvoker { {{#isBasic}} INSTANCE.authentications.put("{{name}}", new HttpBasicAuth()); {{/isBasic}} + {{#isOAuth}} + INSTANCE.authentications.put("{{name}}", new OAuth()); + {{/isOAuth}} {{/authMethods}} // Prevent the authentications from being modified. INSTANCE.authentications = Collections.unmodifiableMap(INSTANCE.authentications); } - private ApiInvoker(Context context) { - this.context = context; - initConnectionManager(); - } - public ApiInvoker() { - initConnectionManager(); + private ApiInvoker(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) { + if(cache == null) cache = new NoCache(); + if(network == null) { + HttpStack stack = new HurlStack(); + network = new BasicNetwork(stack); + } + + if(delivery == null) { + initConnectionRequest(cache, network); + } else { + initConnectionRequest(cache, network, threadPoolSize, delivery); + } + this.connectionTimeout = connectionTimeout; } public static ApiInvoker getInstance() { @@ -304,6 +332,14 @@ public class ApiInvoker { throw new RuntimeException("No API key authentication configured!"); } + public void setConnectionTimeout(int connectionTimeout){ + this.connectionTimeout = connectionTimeout; + } + + public int getConnectionTimeout() { + return connectionTimeout; + } + /** * Update query and header parameters based on authentication settings. * @@ -317,7 +353,21 @@ public class ApiInvoker { } } + public String invokeAPI(String host, String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String contentType, String[] authNames) throws ApiException, InterruptedException, ExecutionException, TimeoutException { + RequestFuture future = RequestFuture.newFuture(); + Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, future, future); + if(request != null) { + mRequestQueue.add(request); + return future.get(connectionTimeout, TimeUnit.SECONDS); + } else return "no data"; + } + public void invokeAPI(String host, String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String contentType, String[] authNames, Response.Listener stringRequest, Response.ErrorListener errorListener) throws ApiException { + Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, stringRequest, errorListener); + if (request != null) mRequestQueue.add(request); + } + + public Request createRequest(String host, String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String contentType, String[] authNames, Response.Listener stringRequest, Response.ErrorListener errorListener) throws ApiException { StringBuilder b = new StringBuilder(); b.append("?"); @@ -374,13 +424,13 @@ public class ApiInvoker { } formParamStr = formParamBuilder.toString(); } + Request request = null; if ("GET".equals(method)) { - GetRequest request = new GetRequest(url, headers, null, stringRequest, errorListener); - mRequestQueue.add(request); + request = new GetRequest(url, headers, null, stringRequest, errorListener); } else if ("POST".equals(method)) { - PostRequest request = null; + request = null; if (formParamStr != null) { request = new PostRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener); } else if (body != null) { @@ -389,11 +439,12 @@ public class ApiInvoker { } else { request = new PostRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener); } + } else { + request = new PostRequest(url, headers, null, null, stringRequest, errorListener); } - if(request != null) mRequestQueue.add(request); } else if ("PUT".equals(method)) { - PutRequest request = null; + request = null; if (formParamStr != null) { request = new PutRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener); } else if (body != null) { @@ -402,11 +453,12 @@ public class ApiInvoker { } else { request = new PutRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener); } + } else { + request = new PutRequest(url, headers, null, null, stringRequest, errorListener); } - if(request != null) mRequestQueue.add(request); } else if ("DELETE".equals(method)) { - DeleteRequest request = null; + request = null; if (formParamStr != null) { request = new DeleteRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener); } else if (body != null) { @@ -415,11 +467,12 @@ public class ApiInvoker { } else { request = new DeleteRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener); } + } else { + request = new DeleteRequest(url, headers, null, null, stringRequest, errorListener); } - if(request != null) mRequestQueue.add(request); } else if ("PATCH".equals(method)) { - PatchRequest request = null; + request = null; if (formParamStr != null) { request = new PatchRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener); } else if (body != null) { @@ -428,12 +481,24 @@ public class ApiInvoker { } else { request = new PatchRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener); } - } - if(request != null) mRequestQueue.add(request); + } else { + request = new PatchRequest(url, headers, null, null, stringRequest, errorListener); + } } + return request; } - private void initConnectionManager() { - mRequestQueue = Volley.newRequestQueue(context); + private void initConnectionRequest(Cache cache, Network network) { + mRequestQueue = new RequestQueue(cache, network); + mRequestQueue.start(); + } + + private void initConnectionRequest(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) { + mRequestQueue = new RequestQueue(cache, network, threadPoolSize, delivery); + mRequestQueue.start(); + } + + public void stopQueue() { + mRequestQueue.stop(); } } diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache index a1824b551c..44c5ed96ec 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache @@ -44,6 +44,9 @@ public class ApiKeyAuth implements Authentication { @Override public void applyToParams(List queryParams, Map headerParams) { String value; + if (apiKey == null) { + return; + } if (apiKeyPrefix != null) { value = apiKeyPrefix + " " + apiKey; } else { diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/oauth.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/oauth.mustache new file mode 100644 index 0000000000..7eb4fe4aab --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/oauth.mustache @@ -0,0 +1,13 @@ +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; + +import java.util.Map; +import java.util.List; + +public class OAuth implements Authentication { + @Override + public void applyToParams(List queryParams, Map headerParams) { + // TODO stub + } +} diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/build.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/build.mustache index 87d7f4a882..f3cf1c21da 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/build.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/build.mustache @@ -49,6 +49,10 @@ android { } } } + + testOptions { + unitTests.returnDefaultValues = true + } } @@ -58,6 +62,8 @@ ext { httpclient_version = "4.3.3" volley_version = "1.0.19" junit_version = "4.8.1" + robolectric_version = "3.0" + concurrent_unit_version = "0.4.2" } dependencies { @@ -67,6 +73,8 @@ dependencies { compile "org.apache.httpcomponents:httpmime:$httpclient_version" compile "com.mcxiaoke.volley:library:${volley_version}@aar" testCompile "junit:junit:$junit_version" + testCompile "org.robolectric:robolectric:${robolectric_version}" + testCompile "net.jodah:concurrentunit:${concurrentunitVersion}" } afterEvaluate { diff --git a/modules/swagger-codegen/src/main/resources/csharp/Project.mustache b/modules/swagger-codegen/src/main/resources/csharp/Project.mustache new file mode 100644 index 0000000000..333cb5088f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/Project.mustache @@ -0,0 +1,58 @@ + + + + Debug + AnyCPU + {{packageGuid}} + Library + Properties + {{packageTitle}} + {{packageTitle}} + v4.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + False + {{binRelativePath}}Newtonsoft.Json.dll + + + {{binRelativePath}}RestSharp.dll + + + + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 28919d6be4..e4e1ba7aa9 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -1,6 +1,7 @@ using System; using System.IO; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Linq; using RestSharp; using {{packageName}}.Client; @@ -239,7 +240,7 @@ namespace {{packageName}}.Api {{#returnType}}return new ApiResponse<{{{returnType}}}>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), - ({{{returnType}}}) Configuration.ApiClient.Deserialize(response, typeof({{{returnType}}})));{{/returnType}} + ({{{returnType}}}) Configuration.ApiClient.Deserialize(response, typeof({{#returnContainer}}{{{returnContainer}}}{{/returnContainer}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}})));{{/returnType}} {{^returnType}}return new ApiResponse(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null);{{/returnType}} @@ -344,7 +345,7 @@ namespace {{packageName}}.Api {{#returnType}}return new ApiResponse<{{{returnType}}}>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), - ({{{returnType}}}) Configuration.ApiClient.Deserialize(response, typeof({{{returnType}}})));{{/returnType}} + ({{{returnType}}}) Configuration.ApiClient.Deserialize(response, typeof({{#returnContainer}}{{{returnContainer}}}{{/returnContainer}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}})));{{/returnType}} {{^returnType}}return new ApiResponse(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null);{{/returnType}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache b/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache index 9472dcc8d3..b84363cae3 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache @@ -1,3 +1,4 @@ +#!/usr/bin/env bash wget -nc https://nuget.org/nuget.exe; mozroots --import --sync mono nuget.exe install vendor/packages.config -o vendor; diff --git a/modules/swagger-codegen/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache index 96e17d8d1d..be02f983be 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -4,6 +4,7 @@ using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache index 7e80a2086e..cc7805c9b9 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache @@ -3,25 +3,26 @@ ## Overview This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a swagger-enabled flask server. +is an example of building a swagger-enabled Flask server. -This example uses the [connexion](https://github.com/zalando/connexion) library on top of Flask. +This example uses the [Connexion](https://github.com/zalando/connexion) library on top of Flask. To run the server, please execute the following: ``` +sudo pip3 install -U connexion # install Connexion from PyPI python3 app.py ``` and open your browser to here: ``` -http://localhost:{{serverPort}}/ui +http://localhost:{{serverPort}}{{contextPath}}/ui/ ``` -Your swagger definition lives here: +Your Swagger definition lives here: ``` -http://localhost:{{serverPort}}{{basePathWithoutHost}}/swagger.json +http://localhost:{{serverPort}}{{contextPath}}/swagger.json ``` diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache index 14af64be6f..ded223fb36 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache @@ -3,7 +3,6 @@ import connexion if __name__ == '__main__': - app = connexion.App(__name__, {{serverPort}}, - specification_dir='./swagger/') + app = connexion.App(__name__, specification_dir='./swagger/') app.add_api('swagger.yaml', arguments={'title': '{{appDescription}}'}) - app.run() + app.run(port={{serverPort}}) diff --git a/modules/swagger-codegen/src/main/resources/go/README.mustache b/modules/swagger-codegen/src/main/resources/go/README.mustache new file mode 100644 index 0000000000..586b35ed3f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go/README.mustache @@ -0,0 +1,12 @@ +# Go API client for {{packageName}} + +## Overview +This API client was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate an API client. + + +## Installation +Put the package under your project folder and add the following in import: +``` + "./{{packageName}}" +``` + diff --git a/modules/swagger-codegen/src/main/resources/go/api.mustache b/modules/swagger-codegen/src/main/resources/go/api.mustache new file mode 100644 index 0000000000..ae7fb8412b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go/api.mustache @@ -0,0 +1,83 @@ +package {{packageName}} + +{{#operations}} +import ( + "strings" + "fmt" + "github.com/dghubble/sling" +{{#imports}} "{{import}}" +{{/imports}} +) + +type {{classname}} struct { + basePath string +} + +func New{{classname}}() *{{classname}}{ + return &{{classname}} { + basePath: "{{basePath}}", + } +} + +func New{{classname}}WithBasePath(basePath string) *{{classname}}{ + return &{{classname}} { + basePath: basePath, + } +} + +{{#operation}} +/** + * {{summary}} + * {{notes}} +{{#allParams}} * @param {{paramName}} {{description}} +{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + */ +//func (a {{classname}}) {{nickname}} ({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}error) { +func (a {{classname}}) {{nickname}} ({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}error) { + + _sling := sling.New().{{httpMethod}}(a.basePath) + + // create path and map variables + path := "{{basePathWithoutHost}}{{path}}" +{{#pathParams}} path = strings.Replace(path, "{" + "{{baseName}}" + "}", fmt.Sprintf("%v", {{paramName}}), -1) +{{/pathParams}} + + _sling = _sling.Path(path) + +{{#hasQueryParams}} type QueryParams struct { + {{#queryParams}}{{paramName}} {{dataType}} `url:"{{baseName}},omitempty"` + {{/queryParams}} +} + _sling = _sling.QueryStruct(&QueryParams{ {{#queryParams}}{{paramName}}: {{paramName}}{{#hasMore}},{{/hasMore}}{{/queryParams}} }) +{{/hasQueryParams}} + // accept header + accepts := []string { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } +{{#hasHeaderParams}}{{#headerParams}} // header params "{{baseName}}" + _sling = _sling.Set("{{baseName}}", {{paramName}}) +{{/headerParams}}{{/hasHeaderParams}} +{{#hasFormParams}} type FormParams struct { +{{#formParams}} {{paramName}} {{dataType}} `url:"{{baseName}},omitempty"` +{{/formParams}} + } + _sling = _sling.BodyForm(&FormParams{ {{#formParams}}{{paramName}}: {{paramName}}{{#hasMore}},{{/hasMore}}{{/formParams}} }) +{{/hasFormParams}} +{{#hasBodyParam}}{{#bodyParams}}// body params + _sling = _sling.BodyJSON({{paramName}}) +{{/bodyParams}}{{/hasBodyParam}} + +{{#returnType}} response := new({{returnType}}) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("{{operationId}} response: ", response, resp, err) + return *response, err +{{/returnType}}{{^returnType}} + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("{{operationId}} response: void, ", resp, err) + return err +{{/returnType}} +} +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/go/model.mustache b/modules/swagger-codegen/src/main/resources/go/model.mustache new file mode 100644 index 0000000000..83ba416883 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go/model.mustache @@ -0,0 +1,15 @@ +package {{packageName}} + +{{#models}} +import ( +{{#imports}} "{{import}}" +{{/imports}} +) + +{{#model}} +type {{classname}} struct { + {{#vars}}{{name}} {{{datatype}}} `json:"{{baseName}},omitempty"` + {{/vars}} +} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/bodyParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/bodyParam.mustache index 2fd81183a5..45b0373e9c 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/bodyParam.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/bodyParam.mustache @@ -1,3 +1,3 @@ -{{#isBodyParam}}
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
+{{#isBodyParam}}
{{baseName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
Body Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/formParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/formParam.mustache index 97f342e60d..33b4610141 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/formParam.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/formParam.mustache @@ -1,3 +1,3 @@ -{{#isFormParam}}
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
+{{#isFormParam}}
{{baseName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
Form Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/headerParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/headerParam.mustache index 903713493b..f5390e7aea 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/headerParam.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/headerParam.mustache @@ -1,3 +1,3 @@ -{{#isHeaderParam}}
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
+{{#isHeaderParam}}
{{baseName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
Header Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/pathParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/pathParam.mustache index b47805a4f0..b3590871cf 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/pathParam.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/pathParam.mustache @@ -1,3 +1,3 @@ -{{#isPathParam}}
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
+{{#isPathParam}}
{{baseName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
Path Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/queryParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/queryParam.mustache index 52147fbd71..27f02a23d8 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/queryParam.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/queryParam.mustache @@ -1,3 +1,3 @@ -{{#isQueryParam}}
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
+{{#isQueryParam}}
{{baseName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
Query Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 414e40650f..f961f5cd60 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -153,7 +153,7 @@ class ObjectSerializer */ public function toFormValue($value) { - if ($value instanceof SplFileObject) { + if ($value instanceof \SplFileObject) { return $value->getRealPath(); } else { return $this->toString($value); diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_test.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_test.mustache new file mode 100644 index 0000000000..d6528ee931 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/api_test.mustache @@ -0,0 +1,43 @@ +require 'spec_helper' +require 'json' + +# Unit tests for {{moduleName}}::{{classname}} +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +{{#operations}}describe '{{classname}}' do + before do + # run before each test + @instance = {{moduleName}}::{{classname}}.new + end + + after do + # run after each test + end + + describe 'test an instance of {{classname}}' do + it 'should create an instact of {{classname}}' do + @instance.should be_a({{moduleName}}::{{classname}}) + end + end + +{{#operation}} + # unit tests for {{operationId}} + # {{summary}} + # {{notes}} +{{#allParams}}{{#required}} # @param {{paramName}} {{description}} +{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters +{{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}} +{{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] + describe '{{operationId}} test' do + it "should work" do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + +{{/operation}} +end +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/ruby/model_test.mustache b/modules/swagger-codegen/src/main/resources/ruby/model_test.mustache new file mode 100644 index 0000000000..53860a2494 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/model_test.mustache @@ -0,0 +1,36 @@ +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for {{moduleName}}::{{classname}} +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +{{#models}}{{#model}}describe '{{classname}}' do + before do + # run before each test + @instance = {{moduleName}}::{{classname}}.new + end + + after do + # run after each test + end + + describe 'test an instance of {{classname}}' do + it 'should create an instact of {{classname}}' do + @instance.should be_a({{moduleName}}::{{classname}}) + end + end +{{#vars}} + describe 'test attribute "{{{name}}}"' do + it 'should work' do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + +{{/vars}} +end +{{/model}}{{/models}} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractOptionsTest.java index 002e4ba8f2..ede3feb50b 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractOptionsTest.java @@ -22,6 +22,7 @@ public abstract class AbstractOptionsTest { this.optionsProvider = optionsProvider; } + @SuppressWarnings("unused") @Test public void checkOptionsProcessing() { getCodegenConfig().additionalProperties().putAll(optionsProvider.createOptions()); @@ -49,7 +50,7 @@ public abstract class AbstractOptionsTest { } } - private Function getCliOptionTransformer() { + private static Function getCliOptionTransformer() { return new Function() { @Override public String apply(CliOption option) { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ClientAuthInputTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ClientAuthInputTest.java index 59552bba14..490affe076 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ClientAuthInputTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ClientAuthInputTest.java @@ -7,6 +7,7 @@ import org.testng.annotations.Test; import java.util.List; +@SuppressWarnings("static-method") public class ClientAuthInputTest { @Test(description = "read a file upload param from a 2.0 spec") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenConfigLoaderTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenConfigLoaderTest.java index b91e506a4f..cf4e4a201f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenConfigLoaderTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenConfigLoaderTest.java @@ -11,6 +11,7 @@ import java.util.Set; import static org.testng.Assert.assertEquals; +@SuppressWarnings("static-method") public class CodegenConfigLoaderTest { @DataProvider(name = "codegenConfig") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java index 68c2b4b170..91a1240ced 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java @@ -189,7 +189,7 @@ public class CodegenTest { } - private Swagger parseAndPrepareSwagger(String path) { + private static Swagger parseAndPrepareSwagger(String path) { Swagger swagger = new SwaggerParser().read(path); // resolve inline models new InlineModelResolver().flatten(swagger); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java index ed83c89c8f..8cd04c932f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java @@ -200,13 +200,13 @@ public class DefaultGeneratorTest { } } - private void changeContent(File file) throws IOException { + private static void changeContent(File file) throws IOException { Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), UTF_8)); out.write(TEST_SKIP_OVERWRITE); out.close(); } - private CodegenOperation findCodegenOperationByOperationId(Map> paths, String operationId) { + private static CodegenOperation findCodegenOperationByOperationId(Map> paths, String operationId) { for (List ops : paths.values()) { for (CodegenOperation co : ops) { if (operationId.equals(co.operationId)) { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java index 339b77badb..d4c22b88aa 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java @@ -18,6 +18,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +@SuppressWarnings("static-method") public class ExampleGeneratorTest { @Test(description = "check handling of recursive models") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java index f972711138..9102f06908 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java @@ -12,6 +12,7 @@ import java.util.Map; import static org.testng.AssertJUnit.*; +@SuppressWarnings("static-method") public class InlineModelResolverTest { @Test public void resolveInlineModelTest() throws Exception { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/SwaggerMigratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/SwaggerMigratorTest.java index 2a7e9ec532..cf19c2058c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/SwaggerMigratorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/SwaggerMigratorTest.java @@ -5,6 +5,7 @@ import io.swagger.parser.SwaggerParser; import org.testng.annotations.Test; +@SuppressWarnings("static-method") public class SwaggerMigratorTest { @Test(description = "read a 1.2 spec") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java index 1b6f878b51..7ad1ff07e2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java @@ -22,6 +22,7 @@ public class AkkaScalaClientOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java index 26d55d7e9b..538614436f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java @@ -22,6 +22,7 @@ public class AndroidClientOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java index b6b90ae7a7..8ea0280434 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java @@ -22,6 +22,7 @@ public class AsyncScalaClientOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java index 2245f2f587..6f39eb1af9 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java @@ -25,6 +25,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; +@SuppressWarnings("static-method") public class CodegenConfiguratorTest { @Mocked @@ -45,6 +46,7 @@ public class CodegenConfiguratorTest { @Tested CodegenConfigurator configurator; + @SuppressWarnings("unused") @Test public void testVerbose() throws Exception { @@ -75,6 +77,7 @@ public class CodegenConfiguratorTest { assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.TEMPLATE_DIR, toAbsolutePathDir(templateDir)); } + @SuppressWarnings("unused") @Test public void testSystemProperties() throws Exception { @@ -286,6 +289,7 @@ public class CodegenConfiguratorTest { assertValueInMap(configurator.getDynamicProperties(), CodegenConstants.LOCAL_VARIABLE_PREFIX, "_"); } + @SuppressWarnings("unused") private ClientOptInput setupAndRunGenericTest(CodegenConfigurator configurator) { final String spec = "swagger.yaml"; @@ -315,10 +319,11 @@ public class CodegenConfiguratorTest { return result; } - private String toAbsolutePathDir(String outputDir) { + private static String toAbsolutePathDir(String outputDir) { return Paths.get(outputDir).toAbsolutePath().toAbsolutePath().toString(); } + @SuppressWarnings("unused") private void setupStandardExpectations(final String spec, final String languageName, final String auth, final CodegenConfig config) { new StrictExpectations() {{ @@ -339,7 +344,7 @@ public class CodegenConfiguratorTest { }}; } - private void assertValueInMap(Map map, String propertyKey, String expectedPropertyValue) { + private static void assertValueInMap(Map map, String propertyKey, String expectedPropertyValue) { assertTrue(map.containsKey(propertyKey)); assertEquals(map.get(propertyKey), expectedPropertyValue); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java index 367977e2b0..da1b7ef7ea 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java @@ -22,6 +22,7 @@ public class CSharpClientOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ @@ -37,6 +38,14 @@ public class CSharpClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.useDateTimeOffset(true); times = 1; + clientCodegen.setOptionalProjectFileFlag(true); + times = 1; + clientCodegen.setPackageGuid(CSharpClientOptionsProvider.PACKAGE_GUID_VALUE); + times = 1; + clientCodegen.setUseCollection(false); + times = 1; + clientCodegen.setReturnICollection(false); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpModelTest.java new file mode 100644 index 0000000000..16ae2ef5b3 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpModelTest.java @@ -0,0 +1,99 @@ +package io.swagger.codegen.csharp; + +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.languages.CSharpClientCodegen; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.StringProperty; +import org.testng.Assert; +import org.testng.annotations.Test; + +@SuppressWarnings("static-method") +public class CSharpModelTest { + + @Test(description = "convert a model with array property to default List") + public void arrayPropertyTest() { + final Model model = getArrayTestModel(); + + final DefaultCodegen codegen = new CSharpClientCodegen(); + final CodegenModel generated = codegen.fromModel("sample", model); + + Assert.assertEquals(generated.name, "sample"); + Assert.assertEquals(generated.classname, "Sample"); + Assert.assertEquals(generated.description, "a sample model"); + Assert.assertEquals(generated.vars.size(), 2); + + final CodegenProperty property = generated.vars.get(1); + Assert.assertEquals(property.baseName, "examples"); + Assert.assertEquals(property.getter, "getExamples"); + Assert.assertEquals(property.setter, "setExamples"); + Assert.assertEquals(property.datatype, "List"); + Assert.assertEquals(property.name, "Examples"); + Assert.assertEquals(property.defaultValue, null); + Assert.assertEquals(property.baseType, "List"); + Assert.assertEquals(property.containerType, "array"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isContainer); + } + + @Test(description = "convert a model with array property to Collection") + public void arrayPropertyCollectionOptionTest() { + final Model model = getArrayTestModel(); + + final CSharpClientCodegen codegen = new CSharpClientCodegen(); + codegen.setUseCollection(true); + + final CodegenModel generated = codegen.fromModel("sample", model); + + Assert.assertEquals(generated.name, "sample"); + Assert.assertEquals(generated.vars.size(), 2); + + final CodegenProperty property = generated.vars.get(1); + Assert.assertEquals(property.baseName, "examples"); + Assert.assertEquals(property.name, "Examples"); + Assert.assertEquals(property.defaultValue, null); + Assert.assertEquals(property.datatype, "Collection"); + Assert.assertEquals(property.baseType, "Collection"); + Assert.assertEquals(property.containerType, "array"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isContainer); + } + + @Test(description = "convert a model with array property to Collection") + public void arrayPropertyICollectionOptionTest() { + final Model model = getArrayTestModel(); + + final CSharpClientCodegen codegen = new CSharpClientCodegen(); + codegen.setUseCollection(true); + codegen.setReturnICollection(true); + + final CodegenModel generated = codegen.fromModel("sample", model); + + Assert.assertEquals(generated.name, "sample"); + Assert.assertEquals(generated.vars.size(), 2); + + final CodegenProperty property = generated.vars.get(1); + Assert.assertEquals(property.baseName, "examples"); + Assert.assertEquals(property.name, "Examples"); + Assert.assertEquals(property.datatype, "Collection", + "returnICollection option should not modify property datatype"); + Assert.assertEquals(property.defaultValue, null); + Assert.assertEquals(property.baseType, "Collection", + "returnICollection option should not modify property baseType"); + Assert.assertEquals(property.containerType, "array"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isContainer); + } + + private Model getArrayTestModel() { + return new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("examples", new ArrayProperty().items(new StringProperty())) + .required("id"); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java index 7e30e2b1cd..cb3854e2bd 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java @@ -22,6 +22,7 @@ public class CsharpDotNet2ClientOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java index b002fd9997..519ac4943c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java @@ -22,6 +22,7 @@ public class DartClientOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java index 21a9cb5e03..d3debf2957 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java @@ -8,8 +8,6 @@ import io.swagger.codegen.options.FlashClienOptionsProvider; import mockit.Expectations; import mockit.Tested; -import java.util.Map; - public class FlashClienOptionsTest extends AbstractOptionsTest { @Tested @@ -24,6 +22,7 @@ public class FlashClienOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java index 8c54a38299..0987a0d236 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java @@ -21,6 +21,7 @@ public class JavaInflectorServerOptionsTest extends JavaClientOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ @@ -44,7 +45,7 @@ public class JavaInflectorServerOptionsTest extends JavaClientOptionsTest { times = 1; clientCodegen.setSerializableModel(Boolean.valueOf(JavaInflectorServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); times = 1; - clientCodegen.setLibrary(JavaInflectorServerOptionsProvider.LIBRARY_VALUE); + clientCodegen.setLibrary(JavaInflectorServerOptionsProvider.DEFAULT_LIBRARY_VALUE); times = 1; clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaInflectorServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); times = 1; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java index 29166bc875..701f9586ee 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java @@ -27,6 +27,7 @@ public class JavaClientOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ @@ -50,7 +51,7 @@ public class JavaClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setSerializableModel(Boolean.valueOf(JavaOptionsProvider.SERIALIZABLE_MODEL_VALUE)); times = 1; - clientCodegen.setLibrary(JavaOptionsProvider.LIBRARY_VALUE); + clientCodegen.setLibrary(JavaOptionsProvider.DEFAULT_LIBRARY_VALUE); times = 1; clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaOptionsProvider.FULL_JAVA_UTIL_VALUE)); times = 1; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java index 66b48cd6b8..dcd87b4d70 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java @@ -15,6 +15,7 @@ import org.testng.annotations.Test; public class JavaInheritanceTest { + @SuppressWarnings("static-method") @Test(description = "convert a composed model") public void javaInheritanceTest() { final Model model = new ComposedModel().parent(new RefModel("Base")) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelEnumTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelEnumTest.java index 2babdc189e..5ac5f78859 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelEnumTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelEnumTest.java @@ -18,6 +18,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Map; +@SuppressWarnings("static-method") public class JavaModelEnumTest { @Test(description = "convert a java model with an enum") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java index dc815e351a..f8c8bae612 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java @@ -24,6 +24,7 @@ import org.testng.annotations.Test; import java.util.List; +@SuppressWarnings("static-method") public class JavaModelTest { @Test(description = "convert a simple java model") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java index 9ae5e6dc3e..4a4e6ff918 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java @@ -31,7 +31,7 @@ public class AllowableValuesTest { } @DataProvider(name = PROVIDER_NAME) - private Object[][] resource() { + private static Object[][] resource() { final CodegenParameter param1 = new CodegenParameter(); final CodegenParameter param2 = new CodegenParameter() {{ allowableValues = ImmutableMap.of("values", ImmutableList.of("item1", "item2", "item3")); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java index 055bb721ad..ddc8f2af06 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java @@ -2,7 +2,7 @@ package io.swagger.codegen.jaxrs; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.java.JavaClientOptionsTest; -import io.swagger.codegen.languages.JaxRSServerCodegen; +import io.swagger.codegen.languages.JavaJerseyServerCodegen; import io.swagger.codegen.options.JaxRSServerOptionsProvider; import mockit.Expectations; @@ -11,7 +11,7 @@ import mockit.Tested; public class JaxRSServerOptionsTest extends JavaClientOptionsTest { @Tested - private JaxRSServerCodegen clientCodegen; + private JavaJerseyServerCodegen clientCodegen; public JaxRSServerOptionsTest() { super(new JaxRSServerOptionsProvider()); @@ -22,6 +22,7 @@ public class JaxRSServerOptionsTest extends JavaClientOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ @@ -45,7 +46,7 @@ public class JaxRSServerOptionsTest extends JavaClientOptionsTest { times = 1; clientCodegen.setSerializableModel(Boolean.valueOf(JaxRSServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); times = 1; - clientCodegen.setLibrary(JaxRSServerOptionsProvider.LIBRARY_VALUE); + clientCodegen.setLibrary(JaxRSServerOptionsProvider.DEFAULT_LIBRARY_VALUE); times = 1; clientCodegen.setFullJavaUtil(Boolean.valueOf(JaxRSServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); times = 1; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsJava8ModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsJava8ModelTest.java index 55219787f8..34c91e2833 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsJava8ModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsJava8ModelTest.java @@ -1,7 +1,8 @@ package io.swagger.codegen.jaxrs; import io.swagger.codegen.CodegenModel; -import io.swagger.codegen.languages.JaxRSServerCodegen; + +import io.swagger.codegen.languages.JavaJerseyServerCodegen; import io.swagger.models.Model; import io.swagger.models.ModelImpl; import io.swagger.models.properties.DateProperty; @@ -12,7 +13,9 @@ import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; +@SuppressWarnings("static-method") public class JaxrsJava8ModelTest { + @Test(description = "convert a simple java model with java8 types") public void simpleModelTest() { final Model model = new ModelImpl() @@ -23,7 +26,7 @@ public class JaxrsJava8ModelTest { .required("id") .required("name"); - final JaxRSServerCodegen codegen = new JaxRSServerCodegen(); + final JavaJerseyServerCodegen codegen = new JavaJerseyServerCodegen(); codegen.setDateLibrary("java8"); codegen.processOpts(); final CodegenModel cm = codegen.fromModel("sample", model); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsJodaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsJodaModelTest.java index 3f2ac1a9ec..8c71c51418 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsJodaModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsJodaModelTest.java @@ -1,7 +1,7 @@ package io.swagger.codegen.jaxrs; import io.swagger.codegen.CodegenModel; -import io.swagger.codegen.languages.JaxRSServerCodegen; +import io.swagger.codegen.languages.JavaJerseyServerCodegen; import io.swagger.models.Model; import io.swagger.models.ModelImpl; import io.swagger.models.properties.DateProperty; @@ -12,7 +12,9 @@ import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; +@SuppressWarnings("static-method") public class JaxrsJodaModelTest { + @Test(description = "convert a simple java model with Joda types") public void simpleModelTest() { final Model model = new ModelImpl() @@ -23,7 +25,7 @@ public class JaxrsJodaModelTest { .required("id") .required("name"); - final JaxRSServerCodegen codegen = new JaxRSServerCodegen(); + final JavaJerseyServerCodegen codegen = new JavaJerseyServerCodegen(); codegen.setDateLibrary("joda"); codegen.processOpts(); final CodegenModel cm = codegen.fromModel("sample", model); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/BooleanOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/BooleanOptionsTest.java index da2d5e35e2..3566f2e98e 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/BooleanOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/BooleanOptionsTest.java @@ -13,6 +13,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +@SuppressWarnings("static-method") public class BooleanOptionsTest { private static final String OPTIONS_PROVIDER = "Codegen"; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java index ce905315ae..c1cfa43b08 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java @@ -22,6 +22,7 @@ public class NodeJSServerOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java index 33f20625e1..795c6ee2d9 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java @@ -22,6 +22,7 @@ public class ObjcClientOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java index f48f20ce11..7d3eeaa410 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java @@ -24,6 +24,7 @@ import org.testng.annotations.Test; import java.util.Map; +@SuppressWarnings("static-method") public class ObjcModelTest { @Test(description = "convert a simple java model") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java index 0c2da1f3fa..f7abe83f8f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java @@ -10,6 +10,7 @@ public class CSharpClientOptionsProvider implements OptionsProvider { public static final String PACKAGE_NAME_VALUE = "swagger_client_csharp"; public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String SOURCE_FOLDER_VALUE = "src_csharp"; + public static final String PACKAGE_GUID_VALUE = "{894EAEBB-649A-498C-A735-10D0BD7B73E0}"; @Override public String getLanguage() { @@ -26,6 +27,10 @@ public class CSharpClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.OPTIONAL_ASSEMBLY_INFO, "true") .put(CodegenConstants.USE_DATETIME_OFFSET, "true") .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(CodegenConstants.USE_COLLECTION, "false") + .put(CodegenConstants.RETURN_ICOLLECTION, "false") + .put(CodegenConstants.OPTIONAL_PROJECT_FILE, "true") + .put(CodegenConstants.OPTIONAL_PROJECT_GUID, PACKAGE_GUID_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java index 32490ba659..bf6fd0aba7 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java @@ -1,5 +1,6 @@ package io.swagger.codegen.options; +import io.swagger.codegen.Codegen; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.languages.JavaClientCodegen; @@ -17,15 +18,19 @@ public class JavaOptionsProvider implements OptionsProvider { public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; public static final String LOCAL_PREFIX_VALUE = "tst"; - public static final String LIBRARY_VALUE = "jersey2"; + public static final String DEFAULT_LIBRARY_VALUE = "jersey2"; public static final String SERIALIZABLE_MODEL_VALUE = "false"; public static final String FULL_JAVA_UTIL_VALUE = "true"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; - @Override - public Map createOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + private ImmutableMap options; + + /** + * Create an options provider with the default options. + */ + public JavaOptionsProvider() { + options = new ImmutableMap.Builder() + .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) @@ -37,12 +42,28 @@ public class JavaOptionsProvider implements OptionsProvider { .put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE) .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) .put(JavaClientCodegen.FULL_JAVA_UTIL, FULL_JAVA_UTIL_VALUE) - .put(CodegenConstants.LIBRARY, LIBRARY_VALUE) + .put(CodegenConstants.LIBRARY, DEFAULT_LIBRARY_VALUE) .put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true") + .put(JavaClientCodegen.USE_RX_JAVA, "false") .put(JavaClientCodegen.DATE_LIBRARY, "joda") .build(); } + /** + * Use the default options, but override the ones found in additionalOptions. + */ + public JavaOptionsProvider(Map additionalOptions) { + options = new ImmutableMap.Builder() + .putAll(options) + .putAll(additionalOptions) + .build(); + } + + @Override + public Map createOptions() { + return options; + } + @Override public boolean isServer() { return false; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java index b74623e851..cccac11b7e 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java @@ -25,7 +25,9 @@ public class JaxRSServerOptionsProvider extends JavaOptionsProvider { ImmutableMap.Builder builder = new ImmutableMap.Builder(); builder.putAll(options) - .put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE); + .put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE) + //.put(JavaJaxRSJersey1ServerCodegen.DATE_LIBRARY, "joda") //java.lang.IllegalArgumentException: Multiple entries with same key: dateLibrary=joda and dateLibrary=joda + ; return builder.build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringMVCServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringMVCServerOptionsProvider.java index e52373c3c0..a9d77c4039 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringMVCServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringMVCServerOptionsProvider.java @@ -8,7 +8,7 @@ import java.util.Map; public class SpringMVCServerOptionsProvider extends JavaOptionsProvider { public static final String CONFIG_PACKAGE_VALUE = "configPackage"; - public static final String LIBRARY_VALUE = "j8-async"; + public static final String LIBRARY_VALUE = "j8-async"; //FIXME hidding value from super class @Override public String getLanguage() { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java index d7d4e5392f..3899ed26b2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java @@ -9,6 +9,7 @@ import java.util.Map; public class TypeScriptAngularClientOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; @Override public String getLanguage() { @@ -20,6 +21,7 @@ public class TypeScriptAngularClientOptionsProvider implements OptionsProvider { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java index e1c0259222..01966ff716 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java @@ -9,6 +9,7 @@ import java.util.Map; public class TypeScriptNodeClientOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; @Override public String getLanguage() { @@ -20,6 +21,7 @@ public class TypeScriptNodeClientOptionsProvider implements OptionsProvider { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/perl/PerlClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/perl/PerlClientOptionsTest.java index d85b0c9dbc..b277acbbe5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/perl/PerlClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/perl/PerlClientOptionsTest.java @@ -22,6 +22,7 @@ public class PerlClientOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java index e50185a3e8..fb5e21d1cc 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java @@ -22,6 +22,7 @@ public class PhpClientOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java index 79da2d2ccd..3cad349a88 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java @@ -18,6 +18,7 @@ import com.google.common.collect.Sets; import org.testng.Assert; import org.testng.annotations.Test; +@SuppressWarnings("static-method") public class PhpModelTest { @Test(description = "convert a simple php model") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java index fc68a9e92e..2682200e60 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java @@ -22,6 +22,7 @@ public class PythonClientOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonTest.java index 07c4bc76b0..d57b445b9c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonTest.java @@ -11,6 +11,7 @@ import io.swagger.parser.SwaggerParser; import org.testng.Assert; import org.testng.annotations.Test; +@SuppressWarnings("static-method") public class PythonTest { @Test(description = "convert a python model with dots") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/qtfivecpp/Qt5CPPOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/qtfivecpp/Qt5CPPOptionsTest.java index 389721d384..1bc1147cd0 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/qtfivecpp/Qt5CPPOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/qtfivecpp/Qt5CPPOptionsTest.java @@ -22,6 +22,7 @@ public class Qt5CPPOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java index 4049416197..f61367e822 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java @@ -22,6 +22,7 @@ public class RubyClientOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java index 0e916aebd7..fe0b3b3b54 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java @@ -22,6 +22,7 @@ public class ScalaClientOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java index 81290c4738..e3c12d028f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java @@ -18,6 +18,7 @@ import com.google.common.collect.Sets; import org.testng.Assert; import org.testng.annotations.Test; +@SuppressWarnings("static-method") public class ScalaModelTest { @Test(description = "convert a simple scala model") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java index 49bbe4373b..70c3dd3098 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java @@ -22,6 +22,7 @@ public class ScalatraServerOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/silex/SilexServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/silex/SilexServerOptionsTest.java index 1168123028..c32ef13fd8 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/silex/SilexServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/silex/SilexServerOptionsTest.java @@ -22,6 +22,7 @@ public class SilexServerOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/sinatra/SinatraServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/sinatra/SinatraServerOptionsTest.java index 6691cf27f8..56e81aba25 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/sinatra/SinatraServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/sinatra/SinatraServerOptionsTest.java @@ -22,6 +22,7 @@ public class SinatraServerOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/slim/SlimFrameworkServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/slim/SlimFrameworkServerOptionsTest.java index 51c668bd93..554f4ca0db 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/slim/SlimFrameworkServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/slim/SlimFrameworkServerOptionsTest.java @@ -22,6 +22,7 @@ public class SlimFrameworkServerOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/springmvc/SpringMVCServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/springmvc/SpringMVCServerOptionsTest.java index d4b984ffcd..c24162c1a3 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/springmvc/SpringMVCServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/springmvc/SpringMVCServerOptionsTest.java @@ -22,6 +22,7 @@ public class SpringMVCServerOptionsTest extends JavaClientOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticDocOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticDocOptionsTest.java index bc2da143ef..9f9f6da27a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticDocOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticDocOptionsTest.java @@ -22,6 +22,7 @@ public class StaticDocOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticOperationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticOperationTest.java index f3e08e8054..6b16b3b7f5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticOperationTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticOperationTest.java @@ -10,6 +10,7 @@ import io.swagger.models.properties.StringProperty; import org.testng.Assert; import org.testng.annotations.Test; +@SuppressWarnings("static-method") public class StaticOperationTest { @Test(description = "convert a string parameter") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlOptionsTest.java index befe62e32c..91ba418fb9 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlOptionsTest.java @@ -22,6 +22,7 @@ public class StaticHtmlOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swagger/SwaggerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swagger/SwaggerOptionsTest.java index f2f461f2b7..ba142d314e 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swagger/SwaggerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swagger/SwaggerOptionsTest.java @@ -22,6 +22,7 @@ public class SwaggerOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swaggeryaml/SwaggerYamlOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swaggeryaml/SwaggerYamlOptionsTest.java index a1478a8ba0..0ed24654f0 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swaggeryaml/SwaggerYamlOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swaggeryaml/SwaggerYamlOptionsTest.java @@ -22,6 +22,7 @@ public class SwaggerYamlOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftOptionsTest.java index 7d3504f67d..7b8ccb6163 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftOptionsTest.java @@ -22,6 +22,7 @@ public class SwiftOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/tizen/TizenClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/tizen/TizenClientOptionsTest.java index 83ebb8be15..35262568fa 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/tizen/TizenClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/tizen/TizenClientOptionsTest.java @@ -22,6 +22,7 @@ public class TizenClientOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularClientOptionsTest.java index 3fdf817dc5..17d9c1ed20 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularClientOptionsTest.java @@ -22,11 +22,14 @@ public class TypeScriptAngularClientOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptAngularClientOptionsProvider.SORT_PARAMS_VALUE)); times = 1; + clientCodegen.setModelPropertyNaming(TypeScriptAngularClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularModelTest.java index 55bbbeffdb..78b14f50e8 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularModelTest.java @@ -17,6 +17,7 @@ import com.google.common.collect.Sets; import org.testng.Assert; import org.testng.annotations.Test; +@SuppressWarnings("static-method") public class TypeScriptAngularModelTest { @Test(description = "convert a simple TypeScript Angular model") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeClientOptionsTest.java index 2374011b1b..67b55de138 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeClientOptionsTest.java @@ -22,11 +22,14 @@ public class TypeScriptNodeClientOptionsTest extends AbstractOptionsTest { return clientCodegen; } + @SuppressWarnings("unused") @Override protected void setExpectations() { new Expectations(clientCodegen) {{ clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptNodeClientOptionsProvider.SORT_PARAMS_VALUE)); times = 1; + clientCodegen.setModelPropertyNaming(TypeScriptNodeClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeModelTest.java index a932ac2b5a..95398b155c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeModelTest.java @@ -17,6 +17,7 @@ import com.google.common.collect.Sets; import org.testng.Assert; import org.testng.annotations.Test; +@SuppressWarnings("static-method") public class TypeScriptNodeModelTest { @Test(description = "convert a simple TypeScript Node model") diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java index 995fc8c80e..c0af8dc56c 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 @@ -19,7 +19,6 @@ package io.swagger.generator; import org.apache.commons.io.IOUtils; import javax.servlet.ServletConfig; -import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import java.io.IOException; @@ -30,8 +29,6 @@ public class Bootstrap extends HttpServlet { @Override public void init(ServletConfig config) throws ServletException { - ServletContext context = config.getServletContext(); - DynamicSwaggerConfig bc = new DynamicSwaggerConfig(); bc.setBasePath("/api"); bc.setTitle("Swagger Generator"); 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 4ffc2348c2..11932b2629 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 @@ -24,4 +24,9 @@ public class ApiException extends Exception { super(msg); this.code = code; } + + public int getCode() + { + return code; + } } diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java index 14093f536d..2adf97b8bf 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 @@ -16,12 +16,12 @@ package io.swagger.generator.exception; +import org.apache.http.HttpStatus; + public class BadRequestException extends ApiException { private static final long serialVersionUID = -5540416398447252055L; - private int code; - public BadRequestException(int code, String msg) { - super(code, msg); - this.code = code; + public BadRequestException(String msg) { + super(HttpStatus.SC_BAD_REQUEST, msg); } } 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 cdae50ce9b..d3747be7d9 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 @@ -16,12 +16,12 @@ package io.swagger.generator.exception; +import org.apache.http.HttpStatus; + public class NotFoundException extends ApiException { private static final long serialVersionUID = -1223255119112336573L; - private int code; - public NotFoundException(int code, String msg) { - super(code, msg); - this.code = code; + public NotFoundException(String msg) { + super(HttpStatus.SC_NOT_FOUND, msg); } } diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java b/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java index 9946831640..9b721d36a4 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java @@ -34,7 +34,7 @@ public class Generator { try { config = CodegenConfigLoader.forName(language); } catch (Exception e) { - throw new BadRequestException(400, String.format("Unsupported target %s supplied. %s", language, e)); + throw new BadRequestException(String.format("Unsupported target %s supplied. %s", language, e)); } Map map = new LinkedHashMap(); for (CliOption option : config.cliOptions()) { @@ -69,7 +69,7 @@ public class Generator { private static String generate(String language, GeneratorInput opts, Type type) throws ApiException { LOGGER.debug(String.format("generate %s for %s", type.getTypeName(), language)); if (opts == null) { - throw new BadRequestException(400, "No options were supplied"); + throw new BadRequestException("No options were supplied"); } JsonNode node = opts.getSpec(); if(node != null && "{}".equals(node.toString())) { @@ -81,13 +81,13 @@ public class Generator { if (opts.getSwaggerUrl() != null) { swagger = new SwaggerParser().read(opts.getSwaggerUrl()); } else { - throw new BadRequestException(400, "No swagger specification was supplied"); + throw new BadRequestException("No swagger specification was supplied"); } } else { swagger = new SwaggerParser().read(node, true); } if (swagger == null) { - throw new BadRequestException(400, "The swagger specification supplied was not valid"); + throw new BadRequestException("The swagger specification supplied was not valid"); } ClientOptInput clientOptInput = new ClientOptInput(); @@ -104,7 +104,7 @@ public class Generator { try { codegenConfig = CodegenConfigLoader.forName(language); } catch(RuntimeException e) { - throw new BadRequestException(400, "Unsupported target " + language + " supplied"); + throw new BadRequestException("Unsupported target " + language + " supplied"); } if (opts.getOptions() != null) { @@ -122,12 +122,12 @@ public class Generator { List files = new Codegen().opts(clientOptInput).generate(); if (files.size() > 0) { List filesToAdd = new ArrayList(); - System.out.println("adding to " + outputFolder); + LOGGER.debug("adding to " + outputFolder); filesToAdd.add(new File(outputFolder)); ZipUtil zip = new ZipUtil(); zip.compressFiles(filesToAdd, outputFilename); } else { - throw new BadRequestException(400, "A target generation was attempted, but no files were created!"); + throw new BadRequestException("A target generation was attempted, but no files were created!"); } for(File file: files) { try { @@ -144,16 +144,16 @@ public class Generator { LOGGER.error("unable to delete output folder " + outputFolder); } } catch (Exception e) { - throw new BadRequestException(500, "Unable to build target: " + e.getMessage()); + throw new BadRequestException("Unable to build target: " + e.getMessage()); } return outputFilename; } - public static InputOption clientOptions(String language) { + public static InputOption clientOptions(@SuppressWarnings("unused") String language) { return null; } - public static InputOption serverOptions(String language) { + public static InputOption serverOptions(@SuppressWarnings("unused") String language) { return null; } diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java index 343692f838..53d5d8a72a 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java @@ -24,6 +24,7 @@ import java.util.*; @Path("/gen") @Api(value = "/gen", description = "Resource for generating swagger components") +@SuppressWarnings("static-method") public class SwaggerResource { static List clients = new ArrayList(); static List servers = new ArrayList(); @@ -110,7 +111,7 @@ public class SwaggerResource { responseContainer = "map", tags = "clients") public Response getClientOptions( - @Context HttpServletRequest request, + @SuppressWarnings("unused") @Context HttpServletRequest request, @ApiParam(value = "The target language for the client library", required = true) @PathParam("language") String language) throws Exception { @@ -132,7 +133,7 @@ public class SwaggerResource { responseContainer = "map", tags = "servers") public Response getServerOptions( - @Context HttpServletRequest request, + @SuppressWarnings("unused") @Context HttpServletRequest request, @ApiParam(value = "The target language for the server framework", required = true) @PathParam("framework") String framework) throws Exception { @@ -181,7 +182,7 @@ public class SwaggerResource { @ApiParam(value = "parameters", required = true) GeneratorInput opts) throws Exception { if (framework == null) { - throw new BadRequestException(400, "Framework is required"); + throw new BadRequestException("Framework is required"); } String filename = Generator.generateServer(framework, opts); System.out.println("generated name: " + filename); diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationException.java index 22ed4ada87..631541f6c0 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationException.java @@ -1,12 +1,9 @@ package io.swagger.generator.util; -import java.util.List; - public class ValidationException extends Exception { private static final long serialVersionUID = 6861195361018260380L; private int code; private String msg; - private List errors; public ValidationException(String msg) { super(msg); 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 c63f161b70..3295be5d89 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 @@ -103,20 +103,18 @@ public class ZipUtil { * @throws FileNotFoundException * @throws IOException */ - private void addFileToZip(File file, ZipOutputStream zos) + private static void addFileToZip(File file, ZipOutputStream zos) throws FileNotFoundException, IOException { zos.putNextEntry(new ZipEntry(file.getName())); BufferedInputStream bis = new BufferedInputStream(new FileInputStream( file)); - long bytesRead = 0; byte[] bytesIn = new byte[BUFFER_SIZE]; int read = 0; while ((read = bis.read(bytesIn)) != -1) { zos.write(bytesIn, 0, read); - bytesRead += read; } zos.closeEntry(); diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/GeneratorInputTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/GeneratorInputTest.java index c5cc99461f..6b6b22fd67 100644 --- a/modules/swagger-generator/src/test/java/io/swagger/generator/GeneratorInputTest.java +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/GeneratorInputTest.java @@ -4,6 +4,7 @@ import io.swagger.generator.model.GeneratorInput; import org.testng.annotations.Test; +@SuppressWarnings("static-method") public class GeneratorInputTest { @Test(description = "write an object") diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java index 55161327b1..2ae76374ad 100644 --- a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java @@ -1,78 +1,51 @@ package io.swagger.generator.online; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertNotNull; - -import io.swagger.codegen.CliOption; -import io.swagger.codegen.CodegenConfigLoader; -import io.swagger.codegen.options.AkkaScalaClientOptionsProvider; -import io.swagger.codegen.options.AndroidClientOptionsProvider; -import io.swagger.codegen.options.AsyncScalaClientOptionsProvider; -import io.swagger.codegen.options.CSharpClientOptionsProvider; -import io.swagger.codegen.options.CsharpDotNet2ClientOptionsProvider; -import io.swagger.codegen.options.DartClientOptionsProvider; -import io.swagger.codegen.options.FlashClienOptionsProvider; -import io.swagger.codegen.options.JavaInflectorServerOptionsProvider; -import io.swagger.codegen.options.JavaOptionsProvider; -import io.swagger.codegen.options.JaxRSServerOptionsProvider; -import io.swagger.codegen.options.NodeJSServerOptionsProvider; -import io.swagger.codegen.options.ObjcClientOptionsProvider; -import io.swagger.codegen.options.OptionsProvider; -import io.swagger.codegen.options.PerlClientOptionsProvider; -import io.swagger.codegen.options.PhpClientOptionsProvider; -import io.swagger.codegen.options.PythonClientOptionsProvider; -import io.swagger.codegen.options.Qt5CPPOptionsProvider; -import io.swagger.codegen.options.RubyClientOptionsProvider; -import io.swagger.codegen.options.ScalaClientOptionsProvider; -import io.swagger.codegen.options.ScalatraServerOptionsProvider; -import io.swagger.codegen.options.SilexServerOptionsProvider; -import io.swagger.codegen.options.SinatraServerOptionsProvider; -import io.swagger.codegen.options.SlimFrameworkServerOptionsProvider; -import io.swagger.codegen.options.SpringMVCServerOptionsProvider; -import io.swagger.codegen.options.StaticDocOptionsProvider; -import io.swagger.codegen.options.StaticHtmlOptionsProvider; -import io.swagger.codegen.options.SwaggerOptionsProvider; -import io.swagger.codegen.options.SwaggerYamlOptionsProvider; -import io.swagger.codegen.options.SwiftOptionsProvider; -import io.swagger.codegen.options.TizenClientOptionsProvider; -import io.swagger.codegen.options.TypeScriptAngularClientOptionsProvider; -import io.swagger.codegen.options.TypeScriptNodeClientOptionsProvider; -import io.swagger.generator.exception.ApiException; -import io.swagger.generator.model.GeneratorInput; - import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Function; -import com.google.common.collect.Iterables; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfigLoader; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.JavaClientCodegen; +import io.swagger.codegen.options.*; +import io.swagger.generator.exception.ApiException; +import io.swagger.generator.model.GeneratorInput; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; +import java.util.*; -import javax.annotation.Nullable; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotEquals; public class OnlineGeneratorOptionsTest { private static final String OPTIONS_PROVIDER = "optionsProvider"; @DataProvider(name = OPTIONS_PROVIDER) - private Object[][] listOptions() { + private static Object[][] listOptions() { return new Object[][]{{new AkkaScalaClientOptionsProvider()}, {new AndroidClientOptionsProvider()}, {new AsyncScalaClientOptionsProvider()}, {new CSharpClientOptionsProvider()}, {new CsharpDotNet2ClientOptionsProvider()}, {new DartClientOptionsProvider()}, {new FlashClienOptionsProvider()}, {new JavaInflectorServerOptionsProvider()}, - {new JavaOptionsProvider()}, {new JaxRSServerOptionsProvider()}, + { + new JavaOptionsProvider(), + new JavaOptionsProvider(ImmutableMap.of(CodegenConstants.LIBRARY, JavaClientCodegen.RETROFIT_2) + ), + new JavaOptionsProvider(ImmutableMap.of( + CodegenConstants.LIBRARY, JavaClientCodegen.RETROFIT_2, + JavaClientCodegen.USE_RX_JAVA, "true") + ) + }, + {new JaxRSServerOptionsProvider()}, {new NodeJSServerOptionsProvider()}, {new ObjcClientOptionsProvider()}, {new PerlClientOptionsProvider()}, {new PhpClientOptionsProvider()}, {new PythonClientOptionsProvider()}, {new Qt5CPPOptionsProvider()}, @@ -122,7 +95,7 @@ public class OnlineGeneratorOptionsTest { } } - private HashMap convertOptions(OptionsProvider provider) { + private static HashMap convertOptions(OptionsProvider provider) { HashMap options = new HashMap(); for (Map.Entry entry : provider.createOptions().entrySet()) { options.put(entry.getKey(), new InvocationCounter(entry.getValue())); @@ -159,10 +132,10 @@ public class OnlineGeneratorOptionsTest { } @Test(dataProvider = OPTIONS_PROVIDER) - public void getOptionsTest(OptionsProvider provider) throws ApiException { + public static void getOptionsTest(OptionsProvider provider) throws ApiException { final Map opts = Generator.getOptions(provider.getLanguage()); - final Function cliOptionWrapper = new Function() { + final Function cliOptionWrapper = new Function() { @Nullable @Override public CliOptionProxy apply(@Nullable CliOption option) { @@ -170,13 +143,13 @@ public class OnlineGeneratorOptionsTest { } }; - final List actual = Lists.transform(new ArrayList(opts.values()), cliOptionWrapper); + final List actual = Lists.transform(new ArrayList(opts.values()), cliOptionWrapper); final List expected = Lists.transform( CodegenConfigLoader.forName(provider.getLanguage()).cliOptions(), cliOptionWrapper); assertEquals(actual, expected); } - private static class CliOptionProxy { + protected static class CliOptionProxy { private final CliOption wrapped; public CliOptionProxy(CliOption wrapped){ diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java index 93277a6a2f..bca63e37ee 100644 --- a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java @@ -13,6 +13,7 @@ import org.testng.annotations.Test; import java.util.Map; +@SuppressWarnings("static-method") public class OnlineJavaClientOptionsTest { @Test diff --git a/pom.xml b/pom.xml index a47757a359..c9bee1d02a 100644 --- a/pom.xml +++ b/pom.xml @@ -342,6 +342,18 @@ samples/client/petstore/java/retrofit2 + + java-client-retrofit2-rx + + + env + java + + + + samples/client/petstore/java/retrofit2rx + + java-client-feign @@ -438,10 +450,12 @@ samples/client/petstore/android/default samples/client/petstore/clojure samples/client/petstore/java/default + samples/client/petstore/java/feign samples/client/petstore/java/jersey2 samples/client/petstore/java/okhttp-gson samples/client/petstore/java/retrofit samples/client/petstore/java/retrofit2 + samples/client/petstore/java/retrofit2rx samples/client/petstore/javascript samples/client/petstore/scala samples/server/petstore/spring-mvc diff --git a/samples/client/petstore/android/volley/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/android/volley/src/test/java/io/swagger/petstore/test/PetApiTest.java new file mode 100644 index 0000000000..92812f8050 --- /dev/null +++ b/samples/client/petstore/android/volley/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -0,0 +1,394 @@ +package es.shyri.swagger.android.volley.petstore.full; + +import com.android.volley.ExecutorDelivery; +import com.android.volley.Network; +import com.android.volley.Response; +import com.android.volley.VolleyError; +import com.android.volley.toolbox.BasicNetwork; +import com.android.volley.toolbox.HttpStack; +import com.android.volley.toolbox.HurlStack; +import com.android.volley.toolbox.NoCache; + +import net.jodah.concurrentunit.Waiter; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Executors; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiInvoker; +import io.swagger.client.api.PetApi; +import io.swagger.client.model.Category; +import io.swagger.client.model.Pet; + +import static com.ibm.icu.impl.Assert.fail; +import static junit.framework.Assert.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + + +@RunWith(RobolectricTestRunner.class) +public class PetApiTest { + PetApi api = null; + + @Before + public void setup() { + HttpStack stack = new HurlStack(); + Network network = new BasicNetwork(stack); + ApiInvoker.initializeInstance(new NoCache(), network, 4, new ExecutorDelivery(Executors.newSingleThreadExecutor()), 30); + api = new PetApi(); + } + + @Test + public void testCreateAndGetPet() throws Exception { + final Waiter waiter = new Waiter(); + final Pet pet = createRandomPet(); + api.addPet(pet, new Response.Listener() { + @Override + public void onResponse(String response) { + waiter.resume(); + } + }, createErrorListener(waiter)); + + waiter.await(); + + api.getPetById(pet.getId(), new Response.Listener() { + @Override + public void onResponse(Pet response) { + Pet fetched = response; + waiter.assertNotNull(fetched); + waiter.assertEquals(pet.getId(), fetched.getId()); + waiter.assertNotNull(fetched.getCategory()); + waiter.assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + waiter.resume(); + } + }, createErrorListener(waiter)); + + waiter.await(); + } + + @Test + public void testUpdatePet() throws Exception { + final Waiter waiter = new Waiter(); + + final Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet, new Response.Listener() { + @Override + public void onResponse(String response) { + waiter.resume(); + } + }, createErrorListener(waiter)); + + waiter.await(); + + api.getPetById(pet.getId(), new Response.Listener() { + @Override + public void onResponse(Pet fetched) { + waiter.assertNotNull(fetched); + waiter.assertEquals(pet.getId(), fetched.getId()); + waiter.assertNotNull(fetched.getCategory()); + waiter.assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + waiter.resume(); + } + }, createErrorListener(waiter)); + + waiter.await(); + } + + @Test + public void testFindPetsByStatus() throws Exception { + final Waiter waiter = new Waiter(); + final Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.available); + + api.updatePet(pet, new Response.Listener() { + @Override + public void onResponse(String response) { + waiter.resume(); + } + }, createErrorListener(waiter)); + + waiter.await(); + + api.findPetsByStatus(Arrays.asList(new String[]{"available"}), new Response.Listener>() { + @Override + public void onResponse(List pets) { + waiter.assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + waiter.assertTrue(found); + waiter.resume(); + } + }, createErrorListener(waiter)); + + waiter.await(); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + final Waiter waiter = new Waiter(); + final Pet pet = createRandomPet(); + pet.setName("frank"); + + api.addPet(pet, new Response.Listener() { + @Override + public void onResponse(String response) { + waiter.resume(); + } + }, createErrorListener(waiter)); + + waiter.await(); + + final Pet[] fetched = new Pet[1]; + + api.getPetById(pet.getId(), new Response.Listener() { + @Override + public void onResponse(Pet petResponse) { + fetched[0] = petResponse; + waiter.assertEquals("frank", fetched[0].getName()); + waiter.resume(); + } + }, createErrorListener(waiter)); + + waiter.await(); + + api.updatePetWithForm(String.valueOf(fetched[0].getId()), "furt", null, new Response.Listener() { + @Override + public void onResponse(String response) { + waiter.resume(); + } + }, createErrorListener(waiter)); + + waiter.await(); + + api.getPetById(fetched[0].getId(), new Response.Listener() { + @Override + public void onResponse(Pet updated) { + waiter.assertEquals("furt", updated.getName()); + waiter.resume(); + } + }, createErrorListener(waiter)); + + waiter.await(); + + } + + @Test + public void testDeletePet() throws Exception { + final Waiter waiter = new Waiter(); + + Pet pet = createRandomPet(); + api.addPet(pet, new Response.Listener() { + @Override + public void onResponse(String response) { + waiter.resume(); + } + }, createErrorListener(waiter)); + + waiter.await(); + + final Pet[] fetched = new Pet[1]; + + api.getPetById(pet.getId(), new Response.Listener() { + @Override + public void onResponse(Pet response) { + fetched[0] = response; + waiter.resume(); + } + }, createErrorListener(waiter)); + + waiter.await(); + + api.deletePet(fetched[0].getId(), "special-key", new Response.Listener() { + @Override + public void onResponse(String response) { + waiter.resume(); + } + }, createErrorListener(waiter)); + + waiter.await(); + + + api.getPetById(fetched[0].getId(), new Response.Listener() { + @Override + public void onResponse(Pet response) { + waiter.fail("expected an error"); + waiter.resume(); + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + waiter.assertEquals(404, error.networkResponse.statusCode); + waiter.resume(); + } + }); + waiter.await(); + } + + + + @Test + public void testUploadFile() throws Exception { + final Waiter waiter = new Waiter(); + + Pet pet = createRandomPet(); + api.addPet(pet, new Response.Listener() { + @Override + public void onResponse(String response) { + waiter.resume(); + } + }, createErrorListener(waiter)); + + waiter.await(); + + 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()), new Response.Listener() { + @Override + public void onResponse(String response) { + waiter.resume(); + } + }, createErrorListener(waiter)); + + waiter.await(); + } + + @Test + public void testCreateAndGetPetSync() 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 testUpdatePetSync() 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 testFindPetsByStatusSync() 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 testUpdatePetWithFormSync() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertEquals("frank", fetched.getName()); + + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + assertEquals("furt", updated.getName()); + } + + @Test + public void testDeletePetSync() 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 testUploadFileSync() 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; + } + + private Response.ErrorListener createErrorListener(final Waiter waiter) { + return new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + error.printStackTrace(); + waiter.fail(error.getMessage()); + waiter.resume(); + } + }; + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh new file mode 100644 index 0000000000..67bc67e57a --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +wget -nc https://nuget.org/nuget.exe; +mozroots --import --sync +mono nuget.exe install vendor/packages.config -o vendor; +mkdir -p bin; +mcs -sdk:45 -r:vendor/Newtonsoft.Json.8.0.2/lib/net45/Newtonsoft.Json.dll,\ +vendor/RestSharp.105.2.3/lib/net45/RestSharp.dll,\ +System.Runtime.Serialization.dll \ +-target:library \ +-out:bin/IO.Swagger.dll \ +-recurse:'src/*.cs' \ +-doc:bin/IO.Swagger.xml \ +-platform:anycpu diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs index 892412e5b3..fa1479f509 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Linq; using RestSharp; using IO.Swagger.Client; diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs index a92876f1a5..69499f4fd9 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Linq; using RestSharp; using IO.Swagger.Client; diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs index 0b9e633c5f..0c178a5637 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Linq; using RestSharp; using IO.Swagger.Client; diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/vendor/packages.config b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/vendor/packages.config new file mode 100644 index 0000000000..c87bbb79fa --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/vendor/packages.config @@ -0,0 +1,5 @@ + + + + + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs index 001b052bf7..3ee63f1e92 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs @@ -221,7 +221,7 @@ namespace SwaggerClientTest.TestPet { Assembly _assembly = Assembly.GetExecutingAssembly(); Stream _imageStream = _assembly.GetManifestResourceStream("SwaggerClientTest.swagger-logo.png"); - PetApi petApi = new PetApi (); + PetApi petApi = new PetApi (); // test file upload with form parameters petApi.UploadFile(petId, "new form name", _imageStream); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll deleted file mode 100644 index ae725c4b59..0000000000 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll and /dev/null differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll deleted file mode 100644 index a7331ed6e2..0000000000 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll and /dev/null differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll deleted file mode 100755 index ad3f04827d..0000000000 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll and /dev/null 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 deleted file mode 100644 index 9fd5b3c6f7..0000000000 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb and /dev/null differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll deleted file mode 100644 index ed6550bb05..0000000000 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll and /dev/null differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs deleted file mode 100644 index fdcb678cdd..0000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs +++ /dev/null @@ -1,2 +0,0 @@ -// -[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.5", FrameworkDisplayName = "")] diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll deleted file mode 100755 index ad3f04827d..0000000000 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll and /dev/null differ diff --git a/samples/client/petstore/go/README.md b/samples/client/petstore/go/README.md new file mode 100644 index 0000000000..7ce753fba9 --- /dev/null +++ b/samples/client/petstore/go/README.md @@ -0,0 +1,12 @@ +# Go API client for swagger + +## Overview +This API client was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate an API client. + + +## Installation +Put the package under your project folder and add the following in import: +``` + "./swagger" +``` + diff --git a/samples/client/petstore/go/swagger/Category.go b/samples/client/petstore/go/swagger/Category.go new file mode 100644 index 0000000000..0268f62488 --- /dev/null +++ b/samples/client/petstore/go/swagger/Category.go @@ -0,0 +1,10 @@ +package swagger + +import ( +) + +type Category struct { + Id int64 `json:"id,omitempty"` + Name string `json:"name,omitempty"` + +} diff --git a/samples/client/petstore/go/swagger/Order.go b/samples/client/petstore/go/swagger/Order.go new file mode 100644 index 0000000000..9db0f94511 --- /dev/null +++ b/samples/client/petstore/go/swagger/Order.go @@ -0,0 +1,15 @@ +package swagger + +import ( + "time" +) + +type Order struct { + Id int64 `json:"id,omitempty"` + PetId int64 `json:"petId,omitempty"` + Quantity int32 `json:"quantity,omitempty"` + ShipDate time.Time `json:"shipDate,omitempty"` + Status string `json:"status,omitempty"` + Complete bool `json:"complete,omitempty"` + +} diff --git a/samples/client/petstore/go/swagger/Pet.go b/samples/client/petstore/go/swagger/Pet.go new file mode 100644 index 0000000000..7544eed638 --- /dev/null +++ b/samples/client/petstore/go/swagger/Pet.go @@ -0,0 +1,14 @@ +package swagger + +import ( +) + +type Pet struct { + Id int64 `json:"id,omitempty"` + Category Category `json:"category,omitempty"` + Name string `json:"name,omitempty"` + PhotoUrls []string `json:"photoUrls,omitempty"` + Tags []Tag `json:"tags,omitempty"` + Status string `json:"status,omitempty"` + +} diff --git a/samples/client/petstore/go/swagger/PetApi.go b/samples/client/petstore/go/swagger/PetApi.go new file mode 100644 index 0000000000..51b32061e0 --- /dev/null +++ b/samples/client/petstore/go/swagger/PetApi.go @@ -0,0 +1,329 @@ +package swagger + +import ( + "strings" + "fmt" + "github.com/dghubble/sling" + "os" +) + +type PetApi struct { + basePath string +} + +func NewPetApi() *PetApi{ + return &PetApi { + basePath: "http://petstore.swagger.io/v2", + } +} + +func NewPetApiWithBasePath(basePath string) *PetApi{ + return &PetApi { + basePath: basePath, + } +} + +/** + * Update an existing pet + * + * @param Body Pet object that needs to be added to the store + * @return void + */ +//func (a PetApi) UpdatePet (Body Pet) (error) { +func (a PetApi) UpdatePet (Body Pet) (error) { + + _sling := sling.New().Put(a.basePath) + + // create path and map variables + path := "/v2/pet" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + +// body params + _sling = _sling.BodyJSON(Body) + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("UpdatePet response: void, ", resp, err) + return err +} +/** + * Add a new pet to the store + * + * @param Body Pet object that needs to be added to the store + * @return void + */ +//func (a PetApi) AddPet (Body Pet) (error) { +func (a PetApi) AddPet (Body Pet) (error) { + + _sling := sling.New().Post(a.basePath) + + // create path and map variables + path := "/v2/pet" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + +// body params + _sling = _sling.BodyJSON(Body) + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("AddPet response: void, ", resp, err) + return err +} +/** + * 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 []Pet + */ +//func (a PetApi) FindPetsByStatus (Status []string) ([]Pet, error) { +func (a PetApi) FindPetsByStatus (Status []string) ([]Pet, error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/pet/findByStatus" + + _sling = _sling.Path(path) + + type QueryParams struct { + Status []string `url:"status,omitempty"` + +} + _sling = _sling.QueryStruct(&QueryParams{ Status: Status }) + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + response := new([]Pet) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("FindPetsByStatus response: ", response, resp, err) + return *response, err +} +/** + * 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 []Pet + */ +//func (a PetApi) FindPetsByTags (Tags []string) ([]Pet, error) { +func (a PetApi) FindPetsByTags (Tags []string) ([]Pet, error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/pet/findByTags" + + _sling = _sling.Path(path) + + type QueryParams struct { + Tags []string `url:"tags,omitempty"` + +} + _sling = _sling.QueryStruct(&QueryParams{ Tags: Tags }) + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + response := new([]Pet) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("FindPetsByTags response: ", response, resp, err) + return *response, err +} +/** + * 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 + */ +//func (a PetApi) GetPetById (PetId int64) (Pet, error) { +func (a PetApi) GetPetById (PetId int64) (Pet, error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/pet/{petId}" + path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", PetId), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + response := new(Pet) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("GetPetById response: ", response, resp, err) + return *response, err +} +/** + * 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 + */ +//func (a PetApi) UpdatePetWithForm (PetId string, Name string, Status string) (error) { +func (a PetApi) UpdatePetWithForm (PetId string, Name string, Status string) (error) { + + _sling := sling.New().Post(a.basePath) + + // create path and map variables + path := "/v2/pet/{petId}" + path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", PetId), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + type FormParams struct { + Name string `url:"name,omitempty"` + Status string `url:"status,omitempty"` + } + _sling = _sling.BodyForm(&FormParams{ Name: Name,Status: Status }) + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("UpdatePetWithForm response: void, ", resp, err) + return err +} +/** + * Deletes a pet + * + * @param PetId Pet id to delete + * @param ApiKey + * @return void + */ +//func (a PetApi) DeletePet (PetId int64, ApiKey string) (error) { +func (a PetApi) DeletePet (PetId int64, ApiKey string) (error) { + + _sling := sling.New().Delete(a.basePath) + + // create path and map variables + path := "/v2/pet/{petId}" + path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", PetId), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + // header params "api_key" + _sling = _sling.Set("api_key", ApiKey) + + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("DeletePet response: void, ", resp, err) + return err +} +/** + * downloads an image + * + * @return *os.File + */ +//func (a PetApi) DownloadFile () (*os.File, error) { +func (a PetApi) DownloadFile () (*os.File, error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/pet/{petId}/downloadImage" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/octet-stream" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + response := new(*os.File) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("DownloadFile response: ", response, resp, err) + return *response, err +} +/** + * 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 + */ +//func (a PetApi) UploadFile (PetId int64, AdditionalMetadata string, File *os.File) (error) { +func (a PetApi) UploadFile (PetId int64, AdditionalMetadata string, File *os.File) (error) { + + _sling := sling.New().Post(a.basePath) + + // create path and map variables + path := "/v2/pet/{petId}/uploadImage" + path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", PetId), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + type FormParams struct { + AdditionalMetadata string `url:"additionalMetadata,omitempty"` + File *os.File `url:"file,omitempty"` + } + _sling = _sling.BodyForm(&FormParams{ AdditionalMetadata: AdditionalMetadata,File: File }) + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("UploadFile response: void, ", resp, err) + return err +} diff --git a/samples/client/petstore/go/swagger/StoreApi.go b/samples/client/petstore/go/swagger/StoreApi.go new file mode 100644 index 0000000000..c43d320077 --- /dev/null +++ b/samples/client/petstore/go/swagger/StoreApi.go @@ -0,0 +1,147 @@ +package swagger + +import ( + "strings" + "fmt" + "github.com/dghubble/sling" +) + +type StoreApi struct { + basePath string +} + +func NewStoreApi() *StoreApi{ + return &StoreApi { + basePath: "http://petstore.swagger.io/v2", + } +} + +func NewStoreApiWithBasePath(basePath string) *StoreApi{ + return &StoreApi { + basePath: basePath, + } +} + +/** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return map[string]int32 + */ +//func (a StoreApi) GetInventory () (map[string]int32, error) { +func (a StoreApi) GetInventory () (map[string]int32, error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/store/inventory" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + response := new(map[string]int32) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("GetInventory response: ", response, resp, err) + return *response, err +} +/** + * Place an order for a pet + * + * @param Body order placed for purchasing the pet + * @return Order + */ +//func (a StoreApi) PlaceOrder (Body Order) (Order, error) { +func (a StoreApi) PlaceOrder (Body Order) (Order, error) { + + _sling := sling.New().Post(a.basePath) + + // create path and map variables + path := "/v2/store/order" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + +// body params + _sling = _sling.BodyJSON(Body) + + + response := new(Order) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("PlaceOrder response: ", response, resp, err) + return *response, err +} +/** + * 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 + */ +//func (a StoreApi) GetOrderById (OrderId string) (Order, error) { +func (a StoreApi) GetOrderById (OrderId string) (Order, error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/store/order/{orderId}" + path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", OrderId), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + response := new(Order) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("GetOrderById response: ", response, resp, err) + return *response, err +} +/** + * 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 + */ +//func (a StoreApi) DeleteOrder (OrderId string) (error) { +func (a StoreApi) DeleteOrder (OrderId string) (error) { + + _sling := sling.New().Delete(a.basePath) + + // create path and map variables + path := "/v2/store/order/{orderId}" + path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", OrderId), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("DeleteOrder response: void, ", resp, err) + return err +} diff --git a/samples/client/petstore/go/swagger/Tag.go b/samples/client/petstore/go/swagger/Tag.go new file mode 100644 index 0000000000..6b505272a1 --- /dev/null +++ b/samples/client/petstore/go/swagger/Tag.go @@ -0,0 +1,10 @@ +package swagger + +import ( +) + +type Tag struct { + Id int64 `json:"id,omitempty"` + Name string `json:"name,omitempty"` + +} diff --git a/samples/client/petstore/go/swagger/User.go b/samples/client/petstore/go/swagger/User.go new file mode 100644 index 0000000000..e7f26d1d10 --- /dev/null +++ b/samples/client/petstore/go/swagger/User.go @@ -0,0 +1,16 @@ +package swagger + +import ( +) + +type User struct { + Id int64 `json:"id,omitempty"` + Username string `json:"username,omitempty"` + FirstName string `json:"firstName,omitempty"` + LastName string `json:"lastName,omitempty"` + Email string `json:"email,omitempty"` + Password string `json:"password,omitempty"` + Phone string `json:"phone,omitempty"` + UserStatus int32 `json:"userStatus,omitempty"` + +} diff --git a/samples/client/petstore/go/swagger/UserApi.go b/samples/client/petstore/go/swagger/UserApi.go new file mode 100644 index 0000000000..9907453bd3 --- /dev/null +++ b/samples/client/petstore/go/swagger/UserApi.go @@ -0,0 +1,282 @@ +package swagger + +import ( + "strings" + "fmt" + "github.com/dghubble/sling" +) + +type UserApi struct { + basePath string +} + +func NewUserApi() *UserApi{ + return &UserApi { + basePath: "http://petstore.swagger.io/v2", + } +} + +func NewUserApiWithBasePath(basePath string) *UserApi{ + return &UserApi { + basePath: basePath, + } +} + +/** + * Create user + * This can only be done by the logged in user. + * @param Body Created user object + * @return void + */ +//func (a UserApi) CreateUser (Body User) (error) { +func (a UserApi) CreateUser (Body User) (error) { + + _sling := sling.New().Post(a.basePath) + + // create path and map variables + path := "/v2/user" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + +// body params + _sling = _sling.BodyJSON(Body) + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("CreateUser response: void, ", resp, err) + return err +} +/** + * Creates list of users with given input array + * + * @param Body List of user object + * @return void + */ +//func (a UserApi) CreateUsersWithArrayInput (Body []User) (error) { +func (a UserApi) CreateUsersWithArrayInput (Body []User) (error) { + + _sling := sling.New().Post(a.basePath) + + // create path and map variables + path := "/v2/user/createWithArray" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + +// body params + _sling = _sling.BodyJSON(Body) + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("CreateUsersWithArrayInput response: void, ", resp, err) + return err +} +/** + * Creates list of users with given input array + * + * @param Body List of user object + * @return void + */ +//func (a UserApi) CreateUsersWithListInput (Body []User) (error) { +func (a UserApi) CreateUsersWithListInput (Body []User) (error) { + + _sling := sling.New().Post(a.basePath) + + // create path and map variables + path := "/v2/user/createWithList" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + +// body params + _sling = _sling.BodyJSON(Body) + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("CreateUsersWithListInput response: void, ", resp, err) + return err +} +/** + * Logs user into the system + * + * @param Username The user name for login + * @param Password The password for login in clear text + * @return string + */ +//func (a UserApi) LoginUser (Username string, Password string) (string, error) { +func (a UserApi) LoginUser (Username string, Password string) (string, error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/user/login" + + _sling = _sling.Path(path) + + type QueryParams struct { + Username string `url:"username,omitempty"` + Password string `url:"password,omitempty"` + +} + _sling = _sling.QueryStruct(&QueryParams{ Username: Username,Password: Password }) + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + response := new(string) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("LoginUser response: ", response, resp, err) + return *response, err +} +/** + * Logs out current logged in user session + * + * @return void + */ +//func (a UserApi) LogoutUser () (error) { +func (a UserApi) LogoutUser () (error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/user/logout" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("LogoutUser response: void, ", resp, err) + return err +} +/** + * Get user by user name + * + * @param Username The name that needs to be fetched. Use user1 for testing. + * @return User + */ +//func (a UserApi) GetUserByName (Username string) (User, error) { +func (a UserApi) GetUserByName (Username string) (User, error) { + + _sling := sling.New().Get(a.basePath) + + // create path and map variables + path := "/v2/user/{username}" + path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%v", Username), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + response := new(User) + _, err := _sling.ReceiveSuccess(response) + //fmt.Println("GetUserByName response: ", response, resp, err) + return *response, err +} +/** + * 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 + */ +//func (a UserApi) UpdateUser (Username string, Body User) (error) { +func (a UserApi) UpdateUser (Username string, Body User) (error) { + + _sling := sling.New().Put(a.basePath) + + // create path and map variables + path := "/v2/user/{username}" + path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%v", Username), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + +// body params + _sling = _sling.BodyJSON(Body) + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("UpdateUser response: void, ", resp, err) + return err +} +/** + * Delete user + * This can only be done by the logged in user. + * @param Username The name that needs to be deleted + * @return void + */ +//func (a UserApi) DeleteUser (Username string) (error) { +func (a UserApi) DeleteUser (Username string) (error) { + + _sling := sling.New().Delete(a.basePath) + + // create path and map variables + path := "/v2/user/{username}" + path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%v", Username), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/json", "application/xml" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + + _, err := _sling.ReceiveSuccess(nil) + //fmt.Println("DeleteUser response: void, ", resp, err) + return err +} diff --git a/samples/client/petstore/go/test.go b/samples/client/petstore/go/test.go new file mode 100644 index 0000000000..d65e70575f --- /dev/null +++ b/samples/client/petstore/go/test.go @@ -0,0 +1,28 @@ +package main + +import ( + sw "./swagger" + "encoding/json" + "fmt" +) + +func main() { + + s := sw.NewPetApi() + + // test POST(body) + newPet := (sw.Pet{Id: 12830, Name: "gopher", + PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending"}) + + jsonNewPet, _ := json.Marshal(newPet) + fmt.Println("newPet:", string(jsonNewPet)) + s.AddPet(newPet) + + // test POST(form) + s.UpdatePetWithForm("12830", "golang", "available") + + // test GET + resp, err := s.GetPetById(12830) + fmt.Println("GetPetById: ", resp, err) + +} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java index 581eafa51c..da80705902 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java @@ -41,7 +41,7 @@ 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 = "2016-01-08T18:50:38.131+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00") public class ApiClient { private Map defaultHeaderMap = new HashMap(); private String basePath = "http://petstore.swagger.io/v2"; @@ -451,34 +451,51 @@ public class ApiClient { } } - private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + private String buildUrl(String path, List queryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); - if (body != null && !formParams.isEmpty()){ + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + return url.toString(); + } + + private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + if (body != null && !formParams.isEmpty()) { throw new ApiException(500, "Cannot have body and form params"); } updateParamsForAuth(authNames, queryParams, headerParams); - 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); - + final String url = buildUrl(path, queryParams); Builder builder; - if (accept == null) - builder = httpClient.resource(basePath + path + querystring).getRequestBuilder(); - else - builder = httpClient.resource(basePath + path + querystring).accept(accept); + if (accept == null) { + builder = httpClient.resource(url).getRequestBuilder(); + } else { + builder = httpClient.resource(url).accept(accept); + } for (String key : headerParams.keySet()) { builder = builder.header(key, headerParams.get(key)); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java index 9a215bf6e2..e34b2b8b5c 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java @@ -15,7 +15,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00") public class PetApi { private ApiClient apiClient; @@ -398,6 +398,93 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Fake endpoint to test byte array return by '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 byte[] + */ + public byte[] getPetByIdWithByteArray(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 getPetByIdWithByteArray"); + } + + // create path and map variables + String path = "/pet/{petId}?testing_byte_array=true".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" }; + + + GenericType returnType = new GenericType() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param body Pet object in the form of byte array + * @return void + */ + public void addPetUsingByteArray(byte[] body) throws ApiException { + Object postBody = body; + + // create path and map variables + String path = "/pet?testing_byte_array=true".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); } 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 index 1faa3f2758..4dcaa928c9 100644 --- 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 @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00") public class Category { private Long id = null; @@ -45,7 +45,7 @@ public class Category { @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -53,8 +53,10 @@ public class Category { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + + return true && Objects.equals(id, category.id) && + Objects.equals(name, category.name) + ; } @Override @@ -77,7 +79,7 @@ public class Category { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } 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 index ec66ccbd77..67543c5a22 100644 --- 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 @@ -11,7 +11,7 @@ import java.util.Date; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00") public class Order { private Long id = null; @@ -123,7 +123,7 @@ public class Order { @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -131,12 +131,14 @@ public class Order { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && + + return true && Objects.equals(id, order.id) && Objects.equals(petId, order.petId) && Objects.equals(quantity, order.quantity) && Objects.equals(shipDate, order.shipDate) && Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + Objects.equals(complete, order.complete) + ; } @Override @@ -163,7 +165,7 @@ public class Order { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } 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 index b82b8150e0..198e1f8928 100644 --- 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 @@ -14,7 +14,7 @@ import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00") public class Pet { private Long id = null; @@ -126,7 +126,7 @@ public class Pet { @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -134,12 +134,14 @@ public class Pet { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && + + return true && Objects.equals(id, pet.id) && Objects.equals(category, pet.category) && Objects.equals(name, pet.name) && Objects.equals(photoUrls, pet.photoUrls) && Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + Objects.equals(status, pet.status) + ; } @Override @@ -166,7 +168,7 @@ public class Pet { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } 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 index c1156c9f4c..7f65d9c963 100644 --- 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 @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00") public class Tag { private Long id = null; @@ -45,7 +45,7 @@ public class Tag { @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -53,8 +53,10 @@ public class Tag { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + + return true && Objects.equals(id, tag.id) && + Objects.equals(name, tag.name) + ; } @Override @@ -77,7 +79,7 @@ public class Tag { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } 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 index 7c07662deb..df6bc1e543 100644 --- 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 @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00") public class User { private Long id = null; @@ -130,7 +130,7 @@ public class User { @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -138,14 +138,16 @@ public class User { return false; } User user = (User) o; - return Objects.equals(id, user.id) && + + return true && Objects.equals(id, user.id) && Objects.equals(username, user.username) && Objects.equals(firstName, user.firstName) && Objects.equals(lastName, user.lastName) && Objects.equals(email, user.email) && Objects.equals(password, user.password) && Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + Objects.equals(userStatus, user.userStatus) + ; } @Override @@ -174,7 +176,7 @@ public class User { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/TestUtils.java b/samples/client/petstore/java/default/src/test/java/io/swagger/TestUtils.java new file mode 100644 index 0000000000..7ddf142426 --- /dev/null +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/TestUtils.java @@ -0,0 +1,17 @@ +package io.swagger; + +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +public class TestUtils { + private static final AtomicLong atomicId = createAtomicId(); + + public static long nextId() { + return atomicId.getAndIncrement(); + } + + private static AtomicLong createAtomicId() { + int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000; + return new AtomicLong((long) baseId); + } +} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java index c0bee9328d..dece3403fd 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -1,9 +1,12 @@ package io.swagger.petstore.test; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.Configuration; +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; +import io.swagger.TestUtils; + +import io.swagger.client.*; import io.swagger.client.api.*; import io.swagger.client.auth.*; import io.swagger.client.model.*; @@ -19,7 +22,8 @@ import org.junit.*; import static org.junit.Assert.*; public class PetApiTest { - PetApi api = null; + private PetApi api; + private ObjectMapper mapper; @Before public void setup() { @@ -68,6 +72,20 @@ public class PetApiTest { assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } + @Test + public void testCreateAndGetPetWithByteArray() throws Exception { + Pet pet = createRandomPet(); + byte[] bytes = serializeJson(pet).getBytes(); + api.addPetUsingByteArray(bytes); + + byte[] fetchedBytes = api.getPetByIdWithByteArray(pet.getId()); + Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class); + 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(); @@ -203,7 +221,7 @@ public class PetApiTest { private Pet createRandomPet() { Pet pet = new Pet(); - pet.setId(System.currentTimeMillis()); + pet.setId(TestUtils.nextId()); pet.setName("gorilla"); Category category = new Category(); @@ -216,4 +234,37 @@ public class PetApiTest { return pet; } + + private String serializeJson(Object o) { + if (mapper == null) { + mapper = createObjectMapper(); + } + try { + return mapper.writeValueAsString(o); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private T deserializeJson(String json, Class klass) { + if (mapper == null) { + mapper = createObjectMapper(); + } + try { + return mapper.readValue(json, klass); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private ObjectMapper createObjectMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + 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()); + return mapper; + } } diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java index 6094f2242e..8ba6caec77 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -1,5 +1,7 @@ package io.swagger.petstore.test; +import io.swagger.TestUtils; + import io.swagger.client.ApiException; import io.swagger.client.*; @@ -63,7 +65,7 @@ public class StoreApiTest { private Order createOrder() { Order order = new Order(); - order.setId(new Long(System.currentTimeMillis())); + order.setId(TestUtils.nextId()); order.setPetId(new Long(200)); order.setQuantity(new Integer(13)); order.setShipDate(new java.util.Date()); diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java index a3f257f568..195e5c1e86 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -1,5 +1,7 @@ package io.swagger.petstore.test; +import io.swagger.TestUtils; + import io.swagger.client.api.*; import io.swagger.client.auth.*; import io.swagger.client.model.*; @@ -33,9 +35,9 @@ public class UserApiTest { @Test public void testCreateUsersWithArray() throws Exception { User user1 = createUser(); - user1.setUsername("abc123"); + user1.setUsername("user" + user1.getId()); User user2 = createUser(); - user2.setUsername("123abc"); + user2.setUsername("user" + user2.getId()); api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); @@ -46,9 +48,9 @@ public class UserApiTest { @Test public void testCreateUsersWithList() throws Exception { User user1 = createUser(); - user1.setUsername("abc123"); + user1.setUsername("user" + user1.getId()); User user2 = createUser(); - user2.setUsername("123abc"); + user2.setUsername("user" + user2.getId()); api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); @@ -72,7 +74,7 @@ public class UserApiTest { private User createUser() { User user = new User(); - user.setId(System.currentTimeMillis()); + user.setId(TestUtils.nextId()); user.setUsername("fred" + user.getId()); user.setFirstName("Fred"); user.setLastName("Meyer"); diff --git a/samples/client/petstore/java/feign/hello.txt b/samples/client/petstore/java/feign/hello.txt new file mode 100644 index 0000000000..6769dd60bd --- /dev/null +++ b/samples/client/petstore/java/feign/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/TestUtils.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/TestUtils.java new file mode 100644 index 0000000000..7ddf142426 --- /dev/null +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/TestUtils.java @@ -0,0 +1,17 @@ +package io.swagger; + +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +public class TestUtils { + private static final AtomicLong atomicId = createAtomicId(); + + public static long nextId() { + return atomicId.getAndIncrement(); + } + + private static AtomicLong createAtomicId() { + int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000; + return new AtomicLong((long) baseId); + } +} diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/PetApiTest.java index aef8ab2561..bf06865290 100644 --- a/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -1,7 +1,8 @@ package io.swagger.petstore.test; -import io.swagger.client.ApiClient; +import io.swagger.TestUtils; +import io.swagger.client.ApiClient; import io.swagger.client.api.*; import io.swagger.client.model.*; @@ -183,7 +184,7 @@ public class PetApiTest { private Pet createRandomPet() { Pet pet = new Pet(); - pet.setId(System.currentTimeMillis()); + pet.setId(TestUtils.nextId()); pet.setName("gorilla"); Category category = new Category(); diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java index dd5bf4e71f..b9aaabb511 100644 --- a/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -1,5 +1,9 @@ package io.swagger.petstore.test; +import feign.FeignException; + +import io.swagger.TestUtils; + import io.swagger.client.*; import io.swagger.client.api.*; import io.swagger.client.model.*; @@ -44,15 +48,19 @@ public class StoreApiTest { Order fetched = api.getOrderById(order.getId().toString()); assertEquals(fetched.getId(), order.getId()); - api.deleteOrder(String.valueOf(order.getId())); + api.deleteOrder(order.getId().toString()); - api.getOrderById(order.getId().toString()); -// fail("expected an error"); + try { + api.getOrderById(order.getId().toString()); + fail("expected an error"); + } catch (FeignException e) { + assertTrue(e.getMessage().startsWith("status 404 ")); + } } private Order createOrder() { Order order = new Order(); - order.setId(new Long(System.currentTimeMillis())); + order.setId(TestUtils.nextId()); order.setPetId(new Long(200)); order.setQuantity(new Integer(13)); order.setShipDate(new java.util.Date()); diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/UserApiTest.java index 1615dbf1dc..de3cd73dd9 100644 --- a/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -1,5 +1,7 @@ package io.swagger.petstore.test; +import io.swagger.TestUtils; + import io.swagger.client.ApiClient; import io.swagger.client.api.*; import io.swagger.client.model.*; @@ -32,9 +34,9 @@ public class UserApiTest { @Test public void testCreateUsersWithArray() throws Exception { User user1 = createUser(); - user1.setUsername("abc123"); + user1.setUsername("user" + user1.getId()); User user2 = createUser(); - user2.setUsername("123abc"); + user2.setUsername("user" + user2.getId()); api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); @@ -45,9 +47,9 @@ public class UserApiTest { @Test public void testCreateUsersWithList() throws Exception { User user1 = createUser(); - user1.setUsername("abc123"); + user1.setUsername("user" + user1.getId()); User user2 = createUser(); - user2.setUsername("123abc"); + user2.setUsername("user" + user2.getId()); api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); @@ -73,7 +75,7 @@ public class UserApiTest { private User createUser() { User user = new User(); - user.setId(System.currentTimeMillis()); + user.setId(TestUtils.nextId()); user.setUsername("fred" + user.getId()); user.setFirstName("Fred"); user.setLastName("Meyer"); 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 index 7f06e36633..c5b3f24e0a 100644 --- 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 @@ -43,7 +43,7 @@ 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 = "2016-01-08T18:51:26.068+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00") public class ApiClient { private Map defaultHeaderMap = new HashMap(); private String basePath = "http://petstore.swagger.io/v2"; @@ -494,7 +494,9 @@ public class ApiClient { public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); - WebTarget target = httpClient.target(this.basePath).path(path); + // Not using `.target(this.basePath).path(path)` below, + // to support (constant) query string in `path`, e.g. "/posts?draft=1" + WebTarget target = httpClient.target(this.basePath + path); if (queryParams != null) { for (Pair queryParam : queryParams) { 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 index 8cce216212..a351ea3d03 100644 --- 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 @@ -15,7 +15,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00") public class PetApi { private ApiClient apiClient; @@ -398,6 +398,93 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Fake endpoint to test byte array return by '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 byte[] + */ + public byte[] getPetByIdWithByteArray(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 getPetByIdWithByteArray"); + } + + // create path and map variables + String path = "/pet/{petId}?testing_byte_array=true".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" }; + + + GenericType returnType = new GenericType() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param body Pet object in the form of byte array + * @return void + */ + public void addPetUsingByteArray(byte[] body) throws ApiException { + Object postBody = body; + + // create path and map variables + String path = "/pet?testing_byte_array=true".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); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java index 4a66bec68d..2235895ee8 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00") public class Category { private Long id = null; @@ -45,7 +45,7 @@ public class Category { @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -53,8 +53,10 @@ public class Category { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + + return true && Objects.equals(id, category.id) && + Objects.equals(name, category.name) + ; } @Override @@ -77,7 +79,7 @@ public class Category { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "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 index 29d0a70616..0d9b89eb58 100644 --- 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 @@ -11,7 +11,7 @@ import java.util.Date; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00") public class Order { private Long id = null; @@ -123,7 +123,7 @@ public class Order { @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -131,12 +131,14 @@ public class Order { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && + + return true && Objects.equals(id, order.id) && Objects.equals(petId, order.petId) && Objects.equals(quantity, order.quantity) && Objects.equals(shipDate, order.shipDate) && Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + Objects.equals(complete, order.complete) + ; } @Override @@ -163,7 +165,7 @@ public class Order { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } 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 index c578648b6e..a45907c171 100644 --- 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 @@ -14,7 +14,7 @@ import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00") public class Pet { private Long id = null; @@ -126,7 +126,7 @@ public class Pet { @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -134,12 +134,14 @@ public class Pet { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && + + return true && Objects.equals(id, pet.id) && Objects.equals(category, pet.category) && Objects.equals(name, pet.name) && Objects.equals(photoUrls, pet.photoUrls) && Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + Objects.equals(status, pet.status) + ; } @Override @@ -166,7 +168,7 @@ public class Pet { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java index cbdca57888..4b2cc23bc2 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00") public class Tag { private Long id = null; @@ -45,7 +45,7 @@ public class Tag { @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -53,8 +53,10 @@ public class Tag { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + + return true && Objects.equals(id, tag.id) && + Objects.equals(name, tag.name) + ; } @Override @@ -77,7 +79,7 @@ public class Tag { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java index ae1dff618f..4f859759ce 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00") public class User { private Long id = null; @@ -130,7 +130,7 @@ public class User { @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -138,14 +138,16 @@ public class User { return false; } User user = (User) o; - return Objects.equals(id, user.id) && + + return true && Objects.equals(id, user.id) && Objects.equals(username, user.username) && Objects.equals(firstName, user.firstName) && Objects.equals(lastName, user.lastName) && Objects.equals(email, user.email) && Objects.equals(password, user.password) && Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + Objects.equals(userStatus, user.userStatus) + ; } @Override @@ -174,7 +176,7 @@ public class User { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/TestUtils.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/TestUtils.java new file mode 100644 index 0000000000..7ddf142426 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/TestUtils.java @@ -0,0 +1,17 @@ +package io.swagger; + +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +public class TestUtils { + private static final AtomicLong atomicId = createAtomicId(); + + public static long nextId() { + return atomicId.getAndIncrement(); + } + + private static AtomicLong createAtomicId() { + int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000; + return new AtomicLong((long) baseId); + } +} 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 index c0bee9328d..a135b3c352 100644 --- 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 @@ -1,9 +1,10 @@ package io.swagger.petstore.test; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.Configuration; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.TestUtils; + +import io.swagger.client.*; import io.swagger.client.api.*; import io.swagger.client.auth.*; import io.swagger.client.model.*; @@ -68,6 +69,20 @@ public class PetApiTest { assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } + @Test + public void testCreateAndGetPetWithByteArray() throws Exception { + Pet pet = createRandomPet(); + byte[] bytes = serializeJson(pet, api.getApiClient()).getBytes(); + api.addPetUsingByteArray(bytes); + + byte[] fetchedBytes = api.getPetByIdWithByteArray(pet.getId()); + Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class, api.getApiClient()); + 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(); @@ -203,7 +218,7 @@ public class PetApiTest { private Pet createRandomPet() { Pet pet = new Pet(); - pet.setId(System.currentTimeMillis()); + pet.setId(TestUtils.nextId()); pet.setName("gorilla"); Category category = new Category(); @@ -216,4 +231,22 @@ public class PetApiTest { return pet; } + + private String serializeJson(Object o, ApiClient apiClient) { + ObjectMapper mapper = apiClient.getJSON().getContext(null); + try { + return mapper.writeValueAsString(o); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private T deserializeJson(String json, Class klass, ApiClient apiClient) { + ObjectMapper mapper = apiClient.getJSON().getContext(null); + try { + return mapper.readValue(json, klass); + } catch (Exception e) { + throw new RuntimeException(e); + } + } } 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 index 6094f2242e..58072ea75f 100644 --- 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 @@ -1,6 +1,6 @@ package io.swagger.petstore.test; -import io.swagger.client.ApiException; +import io.swagger.TestUtils; import io.swagger.client.*; import io.swagger.client.api.*; @@ -63,7 +63,7 @@ public class StoreApiTest { private Order createOrder() { Order order = new Order(); - order.setId(new Long(System.currentTimeMillis())); + order.setId(TestUtils.nextId()); order.setPetId(new Long(200)); order.setQuantity(new Integer(13)); order.setShipDate(new java.util.Date()); 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 index a3f257f568..195e5c1e86 100644 --- 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 @@ -1,5 +1,7 @@ package io.swagger.petstore.test; +import io.swagger.TestUtils; + import io.swagger.client.api.*; import io.swagger.client.auth.*; import io.swagger.client.model.*; @@ -33,9 +35,9 @@ public class UserApiTest { @Test public void testCreateUsersWithArray() throws Exception { User user1 = createUser(); - user1.setUsername("abc123"); + user1.setUsername("user" + user1.getId()); User user2 = createUser(); - user2.setUsername("123abc"); + user2.setUsername("user" + user2.getId()); api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); @@ -46,9 +48,9 @@ public class UserApiTest { @Test public void testCreateUsersWithList() throws Exception { User user1 = createUser(); - user1.setUsername("abc123"); + user1.setUsername("user" + user1.getId()); User user2 = createUser(); - user2.setUsername("123abc"); + user2.setUsername("user" + user2.getId()); api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); @@ -72,7 +74,7 @@ public class UserApiTest { private User createUser() { User user = new User(); - user.setId(System.currentTimeMillis()); + user.setId(TestUtils.nextId()); user.setUsername("fred" + user.getId()); user.setFirstName("Fred"); user.setLastName("Meyer"); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index e8933b9373..810922b90a 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -656,8 +656,8 @@ public class ApiClient { } /** - * Deserialize response body to Java object, according to the Content-Type - * response header. + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. * * @param response HTTP response * @param returnType The type of the Java object @@ -666,12 +666,21 @@ public class ApiClient { * or the Content-Type of the response is not supported. */ public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) + if (response == null || returnType == null) { return null; + } - // Handle file downloading. - if (returnType.equals(File.class)) + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. return (T) downloadFileFromResponse(response); + } String respBody; try { @@ -683,8 +692,9 @@ public class ApiClient { throw new ApiException(e); } - if (respBody == null || "".equals(respBody)) + if (respBody == null || "".equals(respBody)) { return null; + } String contentType = response.headers().get("Content-Type"); if (contentType == null) { @@ -706,20 +716,29 @@ public class ApiClient { } /** - * Serialize the given Java object into request body string, according to the - * request Content-Type. + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. * * @param obj The Java object * @param contentType The request Content-Type - * @return The serialized string + * @return The serialized request body * @throws ApiException If fail to serialize the given object */ - public String serialize(Object obj, String contentType) throws ApiException { - if (isJsonMime(contentType)) { - if (obj != null) - return json.serialize(obj); - else - return null; + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create(MediaType.parse(contentType), (File) obj); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = json.serialize(obj); + } else { + content = null; + } + return RequestBody.create(MediaType.parse(contentType), content); } else { throw new ApiException("Content type \"" + contentType + "\" is not supported"); } @@ -908,7 +927,7 @@ public class ApiClient { reqBody = RequestBody.create(MediaType.parse(contentType), ""); } } else { - reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType)); + reqBody = serialize(body, contentType); } Request request = null; @@ -931,20 +950,27 @@ public class ApiClient { * @return The full URL */ public String buildUrl(String path, List queryParams) { - StringBuilder query = new StringBuilder(); - if (queryParams != null) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; for (Pair param : queryParams) { if (param.getValue() != null) { - if (query.toString().length() == 0) - query.append("?"); - else - query.append("&"); + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } String value = parameterToString(param.getValue()); - query.append(escapeString(param.getName())).append("=").append(escapeString(value)); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); } } } - return basePath + path + query.toString(); + + return url.toString(); } /** diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java index 6439c6a038..0968b81524 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java @@ -895,4 +895,210 @@ public class PetApi { return call; } + /* Build call for getPetByIdWithByteArray */ + private Call getPetByIdWithByteArrayCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetByIdWithByteArray(Async)"); + } + + + // create path and map variables + String path = "/pet/{petId}?testing_byte_array=true".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + 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); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] authNames = new String[] { "api_key" }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); + } + + /** + * Fake endpoint to test byte array return by '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 byte[] + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public byte[] getPetByIdWithByteArray(Long petId) throws ApiException { + ApiResponse resp = getPetByIdWithByteArrayWithHttpInfo(petId); + return resp.getData(); + } + + /** + * Fake endpoint to test byte array return by '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 ApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getPetByIdWithByteArrayWithHttpInfo(Long petId) throws ApiException { + Call call = getPetByIdWithByteArrayCall(petId, null, null); + Type returnType = new TypeToken(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Fake endpoint to test byte array return by 'Find pet by ID' (asynchronously) + * 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 + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public Call getPetByIdWithByteArrayAsync(Long petId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call call = getPetByIdWithByteArrayCall(petId, progressListener, progressRequestListener); + Type returnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for addPetUsingByteArray */ + private Call addPetUsingByteArrayCall(byte[] body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json"); + + 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); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + "application/json", "application/xml" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] authNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); + } + + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param body Pet object in the form of byte array + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void addPetUsingByteArray(byte[] body) throws ApiException { + addPetUsingByteArrayWithHttpInfo(body); + } + + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param body Pet object in the form of byte array + * @return ApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse addPetUsingByteArrayWithHttpInfo(byte[] body) throws ApiException { + Call call = addPetUsingByteArrayCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store (asynchronously) + * + * @param body Pet object in the form of byte array + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public Call addPetUsingByteArrayAsync(byte[] body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call call = addPetUsingByteArrayCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/TestUtils.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/TestUtils.java new file mode 100644 index 0000000000..7ddf142426 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/TestUtils.java @@ -0,0 +1,17 @@ +package io.swagger; + +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +public class TestUtils { + private static final AtomicLong atomicId = createAtomicId(); + + public static long nextId() { + return atomicId.getAndIncrement(); + } + + private static AtomicLong createAtomicId() { + int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000; + return new AtomicLong((long) baseId); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java index 56cc807398..b6f9c38372 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -1,5 +1,9 @@ package io.swagger.petstore.test; +import com.google.gson.reflect.TypeToken; + +import io.swagger.TestUtils; + import io.swagger.client.*; import io.swagger.client.api.*; import io.swagger.client.auth.*; @@ -8,6 +12,7 @@ import io.swagger.client.model.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -67,6 +72,23 @@ public class PetApiTest { assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } + @Test + public void testCreateAndGetPetWithByteArray() throws Exception { + Pet pet = createRandomPet(); + System.out.println(serializeJson(pet, api.getApiClient())); + byte[] bytes = serializeJson(pet, api.getApiClient()).getBytes(); + api.addPetUsingByteArray(bytes); + + byte[] fetchedBytes = api.getPetByIdWithByteArray(pet.getId()); + System.out.println(new String(fetchedBytes)); + Type type = new TypeToken(){}.getType(); + Pet fetched = deserializeJson(new String(fetchedBytes), type, api.getApiClient()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + @Test public void testCreateAndGetPetWithHttpInfo() throws Exception { Pet pet = createRandomPet(); @@ -312,7 +334,7 @@ public class PetApiTest { private Pet createRandomPet() { Pet pet = new Pet(); - pet.setId(System.currentTimeMillis()); + pet.setId(TestUtils.nextId()); pet.setName("gorilla"); Category category = new Category(); @@ -325,4 +347,12 @@ public class PetApiTest { return pet; } + + private String serializeJson(Object o, ApiClient apiClient) { + return apiClient.getJSON().serialize(o); + } + + private T deserializeJson(String json, Type type, ApiClient apiClient) { + return (T) apiClient.getJSON().deserialize(json, type); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java index 589dae1a3c..d62bfaf175 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -1,5 +1,6 @@ package io.swagger.petstore.test; +import io.swagger.TestUtils; import io.swagger.client.ApiException; import io.swagger.client.*; @@ -67,7 +68,7 @@ public class StoreApiTest { private Order createOrder() { Order order = new Order(); - order.setId(new Long(System.currentTimeMillis())); + order.setId(TestUtils.nextId()); order.setPetId(new Long(200)); order.setQuantity(new Integer(13)); order.setShipDate(new java.util.Date()); diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java index a3f257f568..195e5c1e86 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -1,5 +1,7 @@ package io.swagger.petstore.test; +import io.swagger.TestUtils; + import io.swagger.client.api.*; import io.swagger.client.auth.*; import io.swagger.client.model.*; @@ -33,9 +35,9 @@ public class UserApiTest { @Test public void testCreateUsersWithArray() throws Exception { User user1 = createUser(); - user1.setUsername("abc123"); + user1.setUsername("user" + user1.getId()); User user2 = createUser(); - user2.setUsername("123abc"); + user2.setUsername("user" + user2.getId()); api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); @@ -46,9 +48,9 @@ public class UserApiTest { @Test public void testCreateUsersWithList() throws Exception { User user1 = createUser(); - user1.setUsername("abc123"); + user1.setUsername("user" + user1.getId()); User user2 = createUser(); - user2.setUsername("123abc"); + user2.setUsername("user" + user2.getId()); api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); @@ -72,7 +74,7 @@ public class UserApiTest { private User createUser() { User user = new User(); - user.setId(System.currentTimeMillis()); + user.setId(TestUtils.nextId()); user.setUsername("fred" + user.getId()); user.setFirstName("Fred"); user.setLastName("Meyer"); diff --git a/samples/client/petstore/java/retrofit/hello.txt b/samples/client/petstore/java/retrofit/hello.txt new file mode 100644 index 0000000000..6769dd60bd --- /dev/null +++ b/samples/client/petstore/java/retrofit/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/TestUtils.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/TestUtils.java new file mode 100644 index 0000000000..7ddf142426 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/TestUtils.java @@ -0,0 +1,17 @@ +package io.swagger; + +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +public class TestUtils { + private static final AtomicLong atomicId = createAtomicId(); + + public static long nextId() { + return atomicId.getAndIncrement(); + } + + private static AtomicLong createAtomicId() { + int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000; + return new AtomicLong((long) baseId); + } +} diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java index 1ff1dbb10e..a943a8ffe6 100644 --- a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -1,5 +1,7 @@ package io.swagger.petstore.test; +import io.swagger.TestUtils; + import io.swagger.client.ApiClient; import io.swagger.client.api.*; import io.swagger.client.model.*; @@ -172,7 +174,7 @@ public class PetApiTest { private Pet createRandomPet() { Pet pet = new Pet(); - pet.setId(System.currentTimeMillis()); + pet.setId(TestUtils.nextId()); pet.setName("gorilla"); Category category = new Category(); @@ -185,4 +187,4 @@ public class PetApiTest { return pet; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java index 95079f71af..3e0574c887 100644 --- a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -1,5 +1,7 @@ package io.swagger.petstore.test; +import io.swagger.TestUtils; + import io.swagger.client.ApiClient; import io.swagger.client.api.*; import io.swagger.client.model.*; @@ -56,7 +58,7 @@ public class StoreApiTest { private Order createOrder() { Order order = new Order(); - order.setId(new Long(System.currentTimeMillis())); + order.setId(new Long(TestUtils.nextId())); order.setPetId(new Long(200)); order.setQuantity(new Integer(13)); order.setShipDate(new java.util.Date()); @@ -65,4 +67,4 @@ public class StoreApiTest { return order; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java index f99d7f513c..9b949445cc 100644 --- a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -1,5 +1,7 @@ package io.swagger.petstore.test; +import io.swagger.TestUtils; + import io.swagger.client.ApiClient; import io.swagger.client.api.*; import io.swagger.client.model.*; @@ -31,9 +33,9 @@ public class UserApiTest { @Test public void testCreateUsersWithArray() throws Exception { User user1 = createUser(); - user1.setUsername("abc123"); + user1.setUsername("user" + user1.getId()); User user2 = createUser(); - user2.setUsername("123abc"); + user2.setUsername("user" + user2.getId()); api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); @@ -44,9 +46,9 @@ public class UserApiTest { @Test public void testCreateUsersWithList() throws Exception { User user1 = createUser(); - user1.setUsername("abc123"); + user1.setUsername("user" + user1.getId()); User user2 = createUser(); - user2.setUsername("123abc"); + user2.setUsername("user" + user2.getId()); api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); @@ -70,7 +72,7 @@ public class UserApiTest { private User createUser() { User user = new User(); - user.setId(System.currentTimeMillis()); + user.setId(TestUtils.nextId()); user.setUsername("fred" + user.getId()); user.setFirstName("Fred"); user.setLastName("Meyer"); @@ -81,4 +83,4 @@ public class UserApiTest { return user; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit2/hello.txt b/samples/client/petstore/java/retrofit2/hello.txt new file mode 100644 index 0000000000..6769dd60bd --- /dev/null +++ b/samples/client/petstore/java/retrofit2/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/TestUtils.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/TestUtils.java new file mode 100644 index 0000000000..7ddf142426 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/TestUtils.java @@ -0,0 +1,17 @@ +package io.swagger; + +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +public class TestUtils { + private static final AtomicLong atomicId = createAtomicId(); + + public static long nextId() { + return atomicId.getAndIncrement(); + } + + private static AtomicLong createAtomicId() { + int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000; + return new AtomicLong((long) baseId); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/PetApiTest.java index 8506fc08f5..ec5116e45f 100644 --- a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -1,5 +1,7 @@ package io.swagger.petstore.test; +import io.swagger.TestUtils; + import io.swagger.client.ApiClient; import io.swagger.client.api.*; import io.swagger.client.model.*; @@ -32,7 +34,7 @@ public class PetApiTest { public void testCreateAndGetPet() throws Exception { Pet pet = createRandomPet(); Response rp2 = api.addPet(pet).execute(); - + Response rp = api.getPetById(pet.getId()).execute(); Pet fetched = rp.body(); assertNotNull(fetched); @@ -171,7 +173,7 @@ public class PetApiTest { private Pet createRandomPet() { Pet pet = new Pet(); - pet.setId(System.currentTimeMillis()); + pet.setId(TestUtils.nextId()); pet.setName("gorilla"); Category category = new Category(); @@ -184,4 +186,4 @@ public class PetApiTest { return pet; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/StoreApiTest.java index 786b070870..71f77ec9b4 100644 --- a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -1,5 +1,7 @@ package io.swagger.petstore.test; +import io.swagger.TestUtils; + import io.swagger.client.ApiClient; import io.swagger.client.api.*; import io.swagger.client.model.*; @@ -47,12 +49,12 @@ public class StoreApiTest { api.deleteOrder(String.valueOf(order.getId())).execute(); api.getOrderById(String.valueOf(order.getId())).execute(); - //also in retrofit 1 should return an error but don't, check server api impl. + //also in retrofit 1 should return an error but don't, check server api impl. } private Order createOrder() { Order order = new Order(); - order.setId(new Long(System.currentTimeMillis())); + order.setId(new Long(TestUtils.nextId())); order.setPetId(new Long(200)); order.setQuantity(new Integer(13)); order.setShipDate(new java.util.Date()); @@ -61,4 +63,4 @@ public class StoreApiTest { return order; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/UserApiTest.java index d496144c9f..6c35c94383 100644 --- a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -1,5 +1,7 @@ package io.swagger.petstore.test; +import io.swagger.TestUtils; + import io.swagger.client.ApiClient; import io.swagger.client.api.*; import io.swagger.client.model.*; @@ -31,9 +33,9 @@ public class UserApiTest { @Test public void testCreateUsersWithArray() throws Exception { User user1 = createUser(); - user1.setUsername("abc123"); + user1.setUsername("user" + user1.getId()); User user2 = createUser(); - user2.setUsername("123abc"); + user2.setUsername("user" + user2.getId()); api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})).execute(); @@ -44,9 +46,9 @@ public class UserApiTest { @Test public void testCreateUsersWithList() throws Exception { User user1 = createUser(); - user1.setUsername("abc123"); + user1.setUsername("user" + user1.getId()); User user2 = createUser(); - user2.setUsername("123abc"); + user2.setUsername("user" + user2.getId()); api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})).execute(); @@ -70,7 +72,7 @@ public class UserApiTest { private User createUser() { User user = new User(); - user.setId(System.currentTimeMillis()); + user.setId(TestUtils.nextId()); user.setUsername("fred"); user.setFirstName("Fred"); user.setLastName("Meyer"); @@ -81,4 +83,4 @@ public class UserApiTest { return user; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit2rx/README.md b/samples/client/petstore/java/retrofit2rx/README.md new file mode 100644 index 0000000000..7673712f5a --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/README.md @@ -0,0 +1,43 @@ +# swagger-petstore-retrofit2-rx + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation & Usage + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +After the client libarary is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*: + +```xml + + io.swagger + swagger-petstore-retrofit2-rx + 1.0.0 + compile + + +``` + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. + +## Author + +apiteam@swagger.io + + diff --git a/samples/client/petstore/java/retrofit2rx/build.gradle b/samples/client/petstore/java/retrofit2rx/build.gradle new file mode 100644 index 0000000000..08c81cd21e --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/build.gradle @@ -0,0 +1,114 @@ +group = 'io.swagger' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-retrofit2-rx' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + okhttp_version = "2.5.0" + oltu_version = "1.0.0" + retrofit_version = "2.0.0-beta2" + gson_version = "2.4" + swagger_annotations_version = "1.5.0" + junit_version = "4.12" + rx_java_version = "1.0.15" + +} + +dependencies { + compile "com.squareup.okhttp:okhttp:$okhttp_version" + + compile "com.squareup.retrofit:retrofit:$retrofit_version" + compile "com.squareup.retrofit:converter-gson:$retrofit_version" + compile "com.squareup.retrofit:adapter-rxjava:$retrofit_version" + compile "io.reactivex:rxjava:$rx_java_version" + + + compile "com.google.code.gson:gson:$gson_version" + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + + testCompile "junit:junit:$junit_version" +} diff --git a/samples/client/petstore/java/retrofit2rx/gradle.properties b/samples/client/petstore/java/retrofit2rx/gradle.properties new file mode 100644 index 0000000000..05644f0754 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/hello.txt b/samples/client/petstore/java/retrofit2rx/hello.txt new file mode 100644 index 0000000000..6769dd60bd --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/pom.xml b/samples/client/petstore/java/retrofit2rx/pom.xml new file mode 100644 index 0000000000..ab018917b1 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/pom.xml @@ -0,0 +1,173 @@ + + 4.0.0 + io.swagger + swagger-petstore-retrofit2-rx + jar + swagger-petstore-retrofit2-rx + 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.7 + + 1.7 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + com.squareup.retrofit + retrofit + ${retrofit-version} + + + com.squareup.retrofit + converter-gson + ${retrofit-version} + + + com.google.code.gson + gson + ${gson-version} + + + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + ${oltu-version} + + + com.squareup.okhttp + okhttp + ${okhttp-version} + + + + io.reactivex + rxjava + ${rxjava-version} + + + com.squareup.retrofit + adapter-rxjava + ${retrofit-version} + + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 2.0.0-beta2 + 1.0.15 + 2.5.0 + 2.4 + 1.0.0 + 1.0.0 + 4.12 + + diff --git a/samples/client/petstore/java/retrofit2rx/settings.gradle b/samples/client/petstore/java/retrofit2rx/settings.gradle new file mode 100644 index 0000000000..6c54013a53 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-petstore-retrofit2-rx" \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/src/main/AndroidManifest.xml b/samples/client/petstore/java/retrofit2rx/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..465dcb520c --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 0000000000..869681a2ce --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,345 @@ +package io.swagger.client; + +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; + +import retrofit.Converter; +import retrofit.Retrofit; +import retrofit.GsonConverterFactory; +import retrofit.RxJavaCallAdapterFactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.ResponseBody; + + +import io.swagger.client.auth.HttpBasicAuth; +import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.OAuth; +import io.swagger.client.auth.OAuth.AccessTokenListener; +import io.swagger.client.auth.OAuthFlow; + + +public class ApiClient { + + private Map apiAuthorizations; + private OkHttpClient okClient; + private Retrofit.Builder adapterBuilder; + + public ApiClient() { + apiAuthorizations = new LinkedHashMap(); + createDefaultAdapter(); + } + + public ApiClient(String[] authNames) { + this(); + for(String authName : authNames) { + Interceptor auth; + if (authName == "petstore_auth") { + auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); + } else if (authName == "api_key") { + auth = new ApiKeyAuth("header", "api_key"); + } else { + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); + } + addAuthorization(authName, auth); + } + } + + /** + * Basic constructor for single auth name + * @param authName + */ + public ApiClient(String authName) { + this(new String[]{authName}); + } + + /** + * Helper constructor for single api key + * @param authName + * @param apiKey + */ + public ApiClient(String authName, String apiKey) { + this(authName); + this.setApiKey(apiKey); + } + + /** + * Helper constructor for single basic auth or password oauth2 + * @param authName + * @param username + * @param password + */ + public ApiClient(String authName, String username, String password) { + this(authName); + this.setCredentials(username, password); + } + + /** + * Helper constructor for single password oauth2 + * @param authName + * @param clientId + * @param secret + * @param username + * @param password + */ + public ApiClient(String authName, String clientId, String secret, String username, String password) { + this(authName); + this.getTokenEndPoint() + .setClientId(clientId) + .setClientSecret(secret) + .setUsername(username) + .setPassword(password); + } + + public void createDefaultAdapter() { + Gson gson = new GsonBuilder() + .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .create(); + + okClient = new OkHttpClient(); + + String baseUrl = "http://petstore.swagger.io/v2"; + if(!baseUrl.endsWith("/")) + baseUrl = baseUrl + "/"; + + adapterBuilder = new Retrofit + .Builder() + .baseUrl(baseUrl) + .client(okClient) + .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) + .addConverterFactory(GsonCustomConverterFactory.create(gson)); + } + + public S createService(Class serviceClass) { + return adapterBuilder.build().create(serviceClass); + + } + + /** + * Helper method to configure the first api key found + * @param apiKey + */ + private void setApiKey(String apiKey) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof ApiKeyAuth) { + ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization; + keyAuth.setApiKey(apiKey); + return; + } + } + } + + /** + * Helper method to configure the username/password for basic auth or password oauth + * @param username + * @param password + */ + private void setCredentials(String username, String password) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof HttpBasicAuth) { + HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization; + basicAuth.setCredentials(username, password); + return; + } + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); + return; + } + } + } + + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return + */ + public TokenRequestBuilder getTokenEndPoint() { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + return oauth.getTokenRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return + */ + public AuthenticationRequestBuilder getAuthorizationEndPoint() { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + return oauth.getAuthenticationRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) + * @param accessToken + */ + public void setAccessToken(String accessToken) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.setAccessToken(accessToken); + return; + } + } + } + + /** + * Helper method to configure the oauth accessCode/implicit flow parameters + * @param clientId + * @param clientSecret + * @param redirectURI + */ + public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder() + .setClientId(clientId) + .setClientSecret(clientSecret) + .setRedirectURI(redirectURI); + oauth.getAuthenticationRequestBuilder() + .setClientId(clientId) + .setRedirectURI(redirectURI); + return; + } + } + } + + /** + * Configures a listener which is notified when a new access token is received. + * @param accessTokenListener + */ + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.registerAccessTokenListener(accessTokenListener); + return; + } + } + } + + /** + * Adds an authorization to be used by the client + * @param authName + * @param authorization + */ + public void addAuthorization(String authName, Interceptor authorization) { + if (apiAuthorizations.containsKey(authName)) { + throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); + } + apiAuthorizations.put(authName, authorization); + okClient.interceptors().add(authorization); + } + + public Map getApiAuthorizations() { + return apiAuthorizations; + } + + public void setApiAuthorizations(Map apiAuthorizations) { + this.apiAuthorizations = apiAuthorizations; + } + + public Retrofit.Builder getAdapterBuilder() { + return adapterBuilder; + } + + public void setAdapterBuilder(Retrofit.Builder adapterBuilder) { + this.adapterBuilder = adapterBuilder; + } + + public OkHttpClient getOkClient() { + return okClient; + } + + public void addAuthsToOkClient(OkHttpClient okClient) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + okClient.interceptors().add(apiAuthorization); + } + } + + /** + * Clones the okClient given in parameter, adds the auth interceptors and uses it to configure the Retrofit + * @param okClient + */ + public void configureFromOkclient(OkHttpClient okClient) { + OkHttpClient clone = okClient.clone(); + addAuthsToOkClient(clone); + adapterBuilder.client(clone); + } +} + +/** + * This wrapper is to take care of this case: + * when the deserialization fails due to JsonParseException and the + * expected type is String, then just return the body string. + */ +class GsonResponseBodyConverterToString implements Converter { + private final Gson gson; + private final Type type; + + GsonResponseBodyConverterToString(Gson gson, Type type) { + this.gson = gson; + this.type = type; + } + + @Override public T convert(ResponseBody value) throws IOException { + String returned = value.string(); + try { + return gson.fromJson(returned, type); + } + catch (JsonParseException e) { + return (T) returned; + } + } +} + +class GsonCustomConverterFactory extends Converter.Factory +{ + public static GsonCustomConverterFactory create(Gson gson) { + return new GsonCustomConverterFactory(gson); + } + + private final Gson gson; + private final GsonConverterFactory gsonConverterFactory; + + private GsonCustomConverterFactory(Gson gson) { + if (gson == null) throw new NullPointerException("gson == null"); + this.gson = gson; + this.gsonConverterFactory = GsonConverterFactory.create(gson); + } + + @Override + public Converter fromResponseBody(Type type, Annotation[] annotations) { + if(type.equals(String.class)) + return new GsonResponseBodyConverterToString(gson, type); + else + return gsonConverterFactory.fromResponseBody(type, annotations); + } + + @Override + public Converter toRequestBody(Type type, Annotation[] annotations) { + return gsonConverterFactory.toRequestBody(type, annotations); + } +} + diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/CollectionFormats.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/CollectionFormats.java new file mode 100644 index 0000000000..c3cf525751 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/CollectionFormats.java @@ -0,0 +1,95 @@ +package io.swagger.client; + +import java.util.Arrays; +import java.util.List; + +public class CollectionFormats { + + public static class CSVParams { + + protected List params; + + public CSVParams() { + } + + public CSVParams(List params) { + this.params = params; + } + + public CSVParams(String... params) { + this.params = Arrays.asList(params); + } + + public List getParams() { + return params; + } + + public void setParams(List params) { + this.params = params; + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), ","); + } + + } + + public static class SSVParams extends CSVParams { + + public SSVParams() { + } + + public SSVParams(List params) { + super(params); + } + + public SSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), " "); + } + } + + public static class TSVParams extends CSVParams { + + public TSVParams() { + } + + public TSVParams(List params) { + super(params); + } + + public TSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join( params.toArray(new String[0]), "\t"); + } + } + + public static class PIPESParams extends CSVParams { + + public PIPESParams() { + } + + public PIPESParams(List params) { + super(params); + } + + public PIPESParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), "|"); + } + } + +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java new file mode 100644 index 0000000000..4a8e24d7cb --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/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 = "2016-01-22T16:57:22.418+01: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/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 0000000000..7caa426e18 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,155 @@ +package io.swagger.client.api; + +import io.swagger.client.CollectionFormats.*; + +import rx.Observable; + +import retrofit.http.*; + +import com.squareup.okhttp.RequestBody; + +import io.swagger.client.model.Pet; +import java.io.File; + +import java.util.*; + +public interface PetApi { + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + * @return Call + */ + + @PUT("pet") + Observable updatePet( + @Body Pet body + ); + + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + * @return Call + */ + + @POST("pet") + Observable addPet( + @Body Pet body + ); + + + /** + * 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 Call> + */ + + @GET("pet/findByStatus") + Observable> findPetsByStatus( + @Query("status") List status + ); + + + /** + * 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 Call> + */ + + @GET("pet/findByTags") + Observable> findPetsByTags( + @Query("tags") List tags + ); + + + /** + * 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 Call + */ + + @GET("pet/{petId}") + Observable getPetById( + @Path("petId") Long petId + ); + + + /** + * 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 Call + */ + + @FormUrlEncoded + @POST("pet/{petId}") + Observable updatePetWithForm( + @Path("petId") String petId, @Field("name") String name, @Field("status") String status + ); + + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + * @return Call + */ + + @DELETE("pet/{petId}") + Observable deletePet( + @Path("petId") Long petId, @Header("api_key") String apiKey + ); + + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @return Call + */ + + @Multipart + @POST("pet/{petId}/uploadImage") + Observable uploadFile( + @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file + ); + + + /** + * Fake endpoint to test byte array return by '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 Call + */ + + @GET("pet/{petId}?testing_byte_array=true") + Observable getPetByIdWithByteArray( + @Path("petId") Long petId + ); + + + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param body Pet object in the form of byte array + * @return Call + */ + + @POST("pet?testing_byte_array=true") + Observable addPetUsingByteArray( + @Body byte[] body + ); + + +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 0000000000..20e4dbb57f --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,68 @@ +package io.swagger.client.api; + +import io.swagger.client.CollectionFormats.*; + +import rx.Observable; + +import retrofit.http.*; + +import com.squareup.okhttp.RequestBody; + +import java.util.Map; +import io.swagger.client.model.Order; + +import java.util.*; + +public interface StoreApi { + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Call> + */ + + @GET("store/inventory") + Observable> getInventory(); + + + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return Call + */ + + @POST("store/order") + Observable placeOrder( + @Body Order body + ); + + + /** + * 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 Call + */ + + @GET("store/order/{orderId}") + Observable getOrderById( + @Path("orderId") String orderId + ); + + + /** + * 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 Call + */ + + @DELETE("store/order/{orderId}") + Observable deleteOrder( + @Path("orderId") String orderId + ); + + +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 0000000000..ec6fd01925 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,122 @@ +package io.swagger.client.api; + +import io.swagger.client.CollectionFormats.*; + +import rx.Observable; + +import retrofit.http.*; + +import com.squareup.okhttp.RequestBody; + +import io.swagger.client.model.User; +import java.util.*; + +import java.util.*; + +public interface UserApi { + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @return Call + */ + + @POST("user") + Observable createUser( + @Body User body + ); + + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return Call + */ + + @POST("user/createWithArray") + Observable createUsersWithArrayInput( + @Body List body + ); + + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return Call + */ + + @POST("user/createWithList") + Observable createUsersWithListInput( + @Body List body + ); + + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return Call + */ + + @GET("user/login") + Observable loginUser( + @Query("username") String username, @Query("password") String password + ); + + + /** + * Logs out current logged in user session + * + * @return Call + */ + + @GET("user/logout") + Observable logoutUser(); + + + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return Call + */ + + @GET("user/{username}") + Observable getUserByName( + @Path("username") String username + ); + + + /** + * 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 Call + */ + + @PUT("user/{username}") + Observable updateUser( + @Path("username") String username, @Body User body + ); + + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @return Call + */ + + @DELETE("user/{username}") + Observable deleteUser( + @Path("username") String username + ); + + +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 0000000000..59d0123879 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,68 @@ +package io.swagger.client.auth; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; + +public class ApiKeyAuth implements Interceptor { + private final String location; + private final String paramName; + + private String apiKey; + + 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; + } + + @Override + public Response intercept(Chain chain) throws IOException { + String paramValue; + Request request = chain.request(); + + if (location == "query") { + String newQuery = request.uri().getQuery(); + paramValue = paramName + "=" + apiKey; + if (newQuery == null) { + newQuery = paramValue; + } else { + newQuery += "&" + paramValue; + } + + URI newUri; + try { + newUri = new URI(request.uri().getScheme(), request.uri().getAuthority(), + request.uri().getPath(), newQuery, request.uri().getFragment()); + } catch (URISyntaxException e) { + throw new IOException(e); + } + + request = request.newBuilder().url(newUri.toURL()).build(); + } else if (location == "header") { + request = request.newBuilder() + .addHeader(paramName, apiKey) + .build(); + } + return chain.proceed(request); + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 0000000000..cb7c617767 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -0,0 +1,49 @@ +package io.swagger.client.auth; + +import java.io.IOException; + +import com.squareup.okhttp.Credentials; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; + +public class HttpBasicAuth implements Interceptor { + + 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; + } + + public void setCredentials(String username, String password) { + this.username = username; + this.password = password; + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") == null) { + String credentials = Credentials.basic(username, password); + request = request.newBuilder() + .addHeader("Authorization", credentials) + .build(); + } + return chain.proceed(request); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 0000000000..80614f0f56 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuth.java @@ -0,0 +1,161 @@ +package io.swagger.client.auth; + +import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; + +import java.io.IOException; +import java.util.Map; + +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.apache.oltu.oauth2.common.message.types.GrantType; +import org.apache.oltu.oauth2.common.token.BasicOAuthToken; + +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Request.Builder; +import com.squareup.okhttp.Response; + +public class OAuth implements Interceptor { + + public interface AccessTokenListener { + public void notify(BasicOAuthToken token); + } + + private volatile String accessToken; + private OAuthClient oauthClient; + + private TokenRequestBuilder tokenRequestBuilder; + private AuthenticationRequestBuilder authenticationRequestBuilder; + + private AccessTokenListener accessTokenListener; + + public OAuth( OkHttpClient client, TokenRequestBuilder requestBuilder ) { + this.oauthClient = new OAuthClient(new OAuthOkHttpClient(client)); + this.tokenRequestBuilder = requestBuilder; + } + + public OAuth(TokenRequestBuilder requestBuilder ) { + this(new OkHttpClient(), requestBuilder); + } + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); + setFlow(flow); + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public void setFlow(OAuthFlow flow) { + switch(flow) { + case accessCode: + case implicit: + tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE); + break; + case password: + tokenRequestBuilder.setGrantType(GrantType.PASSWORD); + break; + case application: + tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS); + break; + default: + break; + } + } + + @Override + public Response intercept(Chain chain) + throws IOException { + + Request request = chain.request(); + + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") != null) { + return chain.proceed(request); + } + + // If first time, get the token + OAuthClientRequest oAuthRequest; + if (getAccessToken() == null) { + updateAccessToken(null); + } + + // Build the request + Builder rb = request.newBuilder(); + + String requestAccessToken = new String(getAccessToken()); + try { + oAuthRequest = new OAuthBearerClientRequest(request.urlString()) + .setAccessToken(requestAccessToken) + .buildHeaderMessage(); + } catch (OAuthSystemException e) { + throw new IOException(e); + } + + for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { + rb.addHeader(header.getKey(), header.getValue()); + } + rb.url( oAuthRequest.getLocationUri()); + + //Execute the request + Response response = chain.proceed(rb.build()); + + // 401 most likely indicates that access token has expired. + // Time to refresh and resend the request + if ( response.code() == HTTP_UNAUTHORIZED ) { + updateAccessToken(requestAccessToken); + return intercept( chain ); + } + return response; + } + + public synchronized void updateAccessToken(String requestAccessToken) throws IOException { + if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { + try { + OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); + setAccessToken(accessTokenResponse.getAccessToken()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } + } catch (OAuthSystemException e) { + throw new IOException(e); + } catch (OAuthProblemException e) { + throw new IOException(e); + } + } + } + + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + this.accessTokenListener = accessTokenListener; + } + + public synchronized String getAccessToken() { + return accessToken; + } + + public synchronized void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public TokenRequestBuilder getTokenRequestBuilder() { + return tokenRequestBuilder; + } + + public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) { + this.tokenRequestBuilder = tokenRequestBuilder; + } + + public AuthenticationRequestBuilder getAuthenticationRequestBuilder() { + return authenticationRequestBuilder; + } + + public void setAuthenticationRequestBuilder(AuthenticationRequestBuilder authenticationRequestBuilder) { + this.authenticationRequestBuilder = authenticationRequestBuilder; + } + +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java new file mode 100644 index 0000000000..597ec99b48 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -0,0 +1,5 @@ +package io.swagger.client.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java new file mode 100644 index 0000000000..c872901ba2 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java @@ -0,0 +1,69 @@ +package io.swagger.client.auth; + +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.oltu.oauth2.client.HttpClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.response.OAuthClientResponse; +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.Response; + + +public class OAuthOkHttpClient implements HttpClient { + + private OkHttpClient client; + + public OAuthOkHttpClient() { + this.client = new OkHttpClient(); + } + + public OAuthOkHttpClient(OkHttpClient client) { + this.client = client; + } + + public T execute(OAuthClientRequest request, Map headers, + String requestMethod, Class responseClass) + throws OAuthSystemException, OAuthProblemException { + + MediaType mediaType = MediaType.parse("application/json"); + Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri()); + + if(headers != null) { + for (Entry entry : headers.entrySet()) { + if (entry.getKey().equalsIgnoreCase("Content-Type")) { + mediaType = MediaType.parse(entry.getValue()); + } else { + requestBuilder.addHeader(entry.getKey(), entry.getValue()); + } + } + } + + RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null; + requestBuilder.method(requestMethod, body); + + try { + Response response = client.newCall(requestBuilder.build()).execute(); + return OAuthClientResponseFactory.createCustomResponse( + response.body().string(), + response.body().contentType().toString(), + response.code(), + responseClass); + } catch (IOException e) { + throw new OAuthSystemException(e); + } + } + + public void shutdown() { + // Nothing to do here + } + +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 0000000000..d0908afd9e --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,85 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + +@ApiModel(description = "") +public class Category { + + @SerializedName("id") + private Long id = null; + + @SerializedName("name") + private String name = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(id, category.id) && + Objects.equals(name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 0000000000..59c5238b62 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,174 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.Date; + +import com.google.gson.annotations.SerializedName; + + + + +@ApiModel(description = "") +public class Order { + + @SerializedName("id") + private Long id = null; + + @SerializedName("petId") + private Long petId = null; + + @SerializedName("quantity") + private Integer quantity = null; + + @SerializedName("shipDate") + private Date shipDate = null; + + +public enum StatusEnum { + @SerializedName("placed") + PLACED("placed"), + + @SerializedName("approved") + APPROVED("approved"), + + @SerializedName("delivered") + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} + + @SerializedName("status") + private StatusEnum status = null; + + @SerializedName("complete") + private Boolean complete = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + + /** + * Order Status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(id, order.id) && + Objects.equals(petId, order.petId) && + Objects.equals(quantity, order.quantity) && + Objects.equals(shipDate, order.shipDate) && + Objects.equals(status, order.status) && + Objects.equals(complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java new file mode 100644 index 0000000000..1f9462ddc3 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,176 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Category; +import io.swagger.client.model.Tag; +import java.util.*; + +import com.google.gson.annotations.SerializedName; + + + + +@ApiModel(description = "") +public class Pet { + + @SerializedName("id") + private Long id = null; + + @SerializedName("category") + private Category category = null; + + @SerializedName("name") + private String name = null; + + @SerializedName("photoUrls") + private List photoUrls = new ArrayList(); + + @SerializedName("tags") + private List tags = new ArrayList(); + + +public enum StatusEnum { + @SerializedName("available") + AVAILABLE("available"), + + @SerializedName("pending") + PENDING("pending"), + + @SerializedName("sold") + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} + + @SerializedName("status") + private StatusEnum status = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + /** + **/ + @ApiModelProperty(value = "") + 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") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(id, pet.id) && + Objects.equals(category, pet.category) && + Objects.equals(name, pet.name) && + Objects.equals(photoUrls, pet.photoUrls) && + Objects.equals(tags, pet.tags) && + Objects.equals(status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java new file mode 100644 index 0000000000..a4ca1074ca --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,85 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + +@ApiModel(description = "") +public class Tag { + + @SerializedName("id") + private Long id = null; + + @SerializedName("name") + private String name = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(id, tag.id) && + Objects.equals(name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java new file mode 100644 index 0000000000..072f510081 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,182 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + +@ApiModel(description = "") +public class User { + + @SerializedName("id") + private Long id = null; + + @SerializedName("username") + private String username = null; + + @SerializedName("firstName") + private String firstName = null; + + @SerializedName("lastName") + private String lastName = null; + + @SerializedName("email") + private String email = null; + + @SerializedName("password") + private String password = null; + + @SerializedName("phone") + private String phone = null; + + @SerializedName("userStatus") + private Integer userStatus = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + + /** + * User Status + **/ + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(id, user.id) && + Objects.equals(username, user.username) && + Objects.equals(firstName, user.firstName) && + Objects.equals(lastName, user.lastName) && + Objects.equals(email, user.email) && + Objects.equals(password, user.password) && + Objects.equals(phone, user.phone) && + Objects.equals(userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/PetApiTest.java new file mode 100644 index 0000000000..d8450642f6 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -0,0 +1,254 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; +import io.swagger.client.api.*; +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 com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; + +import static org.junit.Assert.*; + +public class PetApiTest { + PetApi api = null; + + @Before + public void setup() { + api = new ApiClient().createService(PetApi.class); + } + + @Test + public void testCreateAndGetPet() throws Exception { + final Pet pet = createRandomPet(); + api.addPet(pet).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.getPetById(pet.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet fetched) { + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + }); + + } + }); + + } + + @Test + public void testUpdatePet() throws Exception { + final Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.getPetById(pet.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet fetched) { + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + }); + + } + }); + + } + + @Test + public void testFindPetsByStatus() throws Exception { + final Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.findPetsByStatus(Arrays.asList(new String[]{"available"})).subscribe(new SkeletonSubscriber>() { + @Override + public void onNext(List pets) { + 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 { + final 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).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.findPetsByTags(Arrays.asList(new String[]{"friendly"})).subscribe(new SkeletonSubscriber>() { + @Override + public void onNext(List pets) { + 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 { + final Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet).subscribe(SkeletonSubscriber.failTestOnError()); + api.getPetById(pet.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(final Pet fetched) { + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null) + .subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.getPetById(fetched.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet updated) { + assertEquals(updated.getName(), "furt"); + } + }); + + } + }); + } + }); + + + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet).subscribe(SkeletonSubscriber.failTestOnError()); + + api.getPetById(pet.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet fetched) { + + api.deletePet(fetched.getId(), null).subscribe(SkeletonSubscriber.failTestOnError()); + api.getPetById(fetched.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet deletedPet) { + fail("Should not have found deleted pet."); + } + + @Override + public void onError(Throwable e) { + // expected, because the pet has been deleted. + } + }); + } + }); + } + + @Test + public void testUploadFile() throws Exception { + File file = File.createTempFile("test", "hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + + writer.write("Hello world!"); + writer.close(); + + Pet pet = createRandomPet(); + api.addPet(pet).subscribe(SkeletonSubscriber.failTestOnError()); + + RequestBody body = RequestBody.create(MediaType.parse("text/plain"), file); + api.uploadFile(pet.getId(), "a test file", body).subscribe(new SkeletonSubscriber() { + @Override + public void onError(Throwable e) { + // this also yields a 400 for other tests, so I guess it's okay... + } + }); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + 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; + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/SkeletonSubscriber.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/SkeletonSubscriber.java new file mode 100644 index 0000000000..5d34a1e5d5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/SkeletonSubscriber.java @@ -0,0 +1,30 @@ +package io.swagger.petstore.test; + +import junit.framework.TestFailure; +import rx.Subscriber; + +/** + * Skeleton subscriber for tests that will fail when onError() is called unexpectedly. + */ +public abstract class SkeletonSubscriber extends Subscriber { + + public static SkeletonSubscriber failTestOnError() { + return new SkeletonSubscriber() { + }; + } + + @Override + public void onCompleted() { + // space for rent + } + + @Override + public void onNext(T t) { + // space for rent + } + + @Override + public void onError(Throwable e) { + throw new RuntimeException("Subscriber onError() called with unhandled exception!", e); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/StoreApiTest.java new file mode 100644 index 0000000000..d9e2c64139 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -0,0 +1,88 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.util.Map; + +import org.junit.*; + +import retrofit.Response; + +import static org.junit.Assert.*; + +public class StoreApiTest { + StoreApi api = null; + + @Before + public void setup() { + api = new ApiClient().createService(StoreApi.class); + } + + @Test + public void testGetInventory() throws Exception { + api.getInventory().subscribe(new SkeletonSubscriber>() { + @Override + public void onNext(Map inventory) { + assertTrue(inventory.keySet().size() > 0); + } + }); + + } + + @Test + public void testPlaceOrder() throws Exception { + final Order order = createOrder(); + api.placeOrder(order).subscribe(SkeletonSubscriber.failTestOnError()); + api.getOrderById(String.valueOf(order.getId())).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Order fetched) { + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + } + }); + } + + @Test + public void testDeleteOrder() throws Exception { + final Order order = createOrder(); + api.placeOrder(order).subscribe(SkeletonSubscriber.failTestOnError()); + + api.getOrderById(String.valueOf(order.getId())).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Order fetched) { + assertEquals(fetched.getId(), order.getId()); + } + }); + + + api.deleteOrder(String.valueOf(order.getId())).subscribe(SkeletonSubscriber.failTestOnError()); + api.getOrderById(String.valueOf(order.getId())) + .subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Order order) { + throw new RuntimeException("Should not have found deleted order."); + } + + @Override + public void onError(Throwable e) { + // should not find deleted order. + } + } + ); + } + + 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; + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/UserApiTest.java new file mode 100644 index 0000000000..59e238b457 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -0,0 +1,108 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + + +import java.util.Arrays; + +import org.junit.*; + +import static org.junit.Assert.*; + +/** + * NOTE: This serves as a sample and test case for the generator, which is why this is java-7 code. + * Much looks much nicer with no anonymous classes. + */ +public class UserApiTest { + UserApi api = null; + + @Before + public void setup() { + api = new ApiClient().createService(UserApi.class); + } + + @Test + public void testCreateUser() throws Exception { + final User user = createUser(); + + api.createUser(user).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.getUserByName(user.getUsername()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(User fetched) { + assertEquals(user.getId(), fetched.getId()); + } + }); + } + }); + } + + @Test + public void testCreateUsersWithArray() throws Exception { + final User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})).subscribe(SkeletonSubscriber.failTestOnError()); + + api.getUserByName(user1.getUsername()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(User fetched) { + assertEquals(user1.getId(), fetched.getId()); + } + }); + } + + @Test + public void testCreateUsersWithList() throws Exception { + final User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})).subscribe(SkeletonSubscriber.failTestOnError()); + + api.getUserByName(user1.getUsername()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(User fetched) { + assertEquals(user1.getId(), fetched.getId()); + } + }); + } + + @Test + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); + + api.loginUser(user.getUsername(), user.getPassword()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(String token) { + 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; + } +} \ No newline at end of file diff --git a/samples/client/petstore/javascript/package.json b/samples/client/petstore/javascript/package.json index 6810fd633d..1fdf78cf21 100644 --- a/samples/client/petstore/javascript/package.json +++ b/samples/client/petstore/javascript/package.json @@ -8,13 +8,10 @@ "test": "./node_modules/mocha/bin/mocha --recursive" }, "dependencies": { - "jquery": "~2.1.4" + "superagent": "1.7.1" }, "devDependencies": { "mocha": "~2.3.4", - "expect.js": "~0.3.1", - "mockrequire": "~0.0.5", - "domino": "~1.0.20", - "xmlhttprequest": "~1.8.0" + "expect.js": "~0.3.1" } } diff --git a/samples/client/petstore/javascript/src/ApiClient.js b/samples/client/petstore/javascript/src/ApiClient.js new file mode 100644 index 0000000000..7fdc0ca81d --- /dev/null +++ b/samples/client/petstore/javascript/src/ApiClient.js @@ -0,0 +1,183 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['superagent'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('superagent')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.ApiClient = factory(root.superagent); + } +}(this, function(superagent) { + 'use strict'; + + var ApiClient = function ApiClient() { + /** + * The base path to put in front of every API call's (relative) path. + */ + this.basePath = 'http://petstore.swagger.io/v2'.replace(/\/+$/, ''); + + /** + * The default HTTP headers to be included for all API calls. + */ + this.defaultHeaders = {}; + }; + + ApiClient.prototype.paramToString = function paramToString(param) { + if (param == null) { + // return empty string for null and undefined + return ''; + } else { + return param.toString(); + } + }; + + /** + * Build full URL by appending the given path to base path and replacing + * path parameter placeholders with parameter values. + * NOTE: query parameters are not handled here. + */ + ApiClient.prototype.buildUrl = function buildUrl(path, pathParams) { + if (!path.match(/^\//)) { + path = '/' + path; + } + var url = this.basePath + path; + var _this = this; + url = url.replace(/\{([\w-]+)\}/g, function(fullMatch, key) { + var value; + if (pathParams.hasOwnProperty(key)) { + value = _this.paramToString(pathParams[key]); + } else { + value = fullMatch; + } + return encodeURIComponent(value); + }); + return url; + }; + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + ApiClient.prototype.isJsonMime = function isJsonMime(mime) { + return Boolean(mime != null && mime.match(/^application\/json(;.*)?$/i)); + }; + + /** + * Choose a MIME from the given MIMEs with JSON preferred, + * i.e. return JSON if included, otherwise return the first one. + */ + ApiClient.prototype.jsonPreferredMime = function jsonPreferredMime(mimes) { + var len = mimes.length; + for (var i = 0; i < len; i++) { + if (this.isJsonMime(mimes[i])) { + return mimes[i]; + } + } + return mimes[0]; + }; + + /** + * Check if the given parameter value is like file content. + */ + ApiClient.prototype.isFileParam = function isFileParam(param) { + // Buffer or fs.ReadStream in Node.js + if (typeof module === 'object' && module.exports && + (param instanceof Buffer || param instanceof require('fs').ReadStream)) { + return true; + } + // Blob in browser + if (typeof Blob === 'function' && param instanceof Blob) { + return true; + } + // File in browser (it seems File object is also instance of Blob, but keep this for safe) + if (typeof File === 'function' && param instanceof File) { + return true; + } + return false; + }; + + /** + * Normalize parameters values: + * remove nils, + * keep files and arrays, + * format to string with `paramToString` for other cases. + */ + ApiClient.prototype.normalizeParams = function normalizeParams(params) { + var newParams = {}; + for (var key in params) { + if (params.hasOwnProperty(key) && params[key] != null) { + var value = params[key]; + if (this.isFileParam(value) || Array.isArray(value)) { + newParams[key] = value; + } else { + newParams[key] = this.paramToString(value); + } + } + } + return newParams; + }; + + ApiClient.prototype.callApi = function callApi(path, httpMethod, pathParams, + queryParams, headerParams, formParams, bodyParam, contentTypes, accepts, + callback) { + var url = this.buildUrl(path, pathParams); + var request = superagent(httpMethod, url); + + // set query parameters + request.query(this.normalizeParams(queryParams)); + + // set header parameters + request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); + + var contentType = this.jsonPreferredMime(contentTypes); + if (contentType) { + request.type(contentType); + } else if (!request.header['Content-Type']) { + request.type('application/json'); + } + + if (contentType === 'application/x-www-form-urlencoded') { + request.send(this.normalizeParams(formParams)); + } else if (contentType == 'multipart/form-data') { + var _formParams = this.normalizeParams(formParams); + for (var key in _formParams) { + if (_formParams.hasOwnProperty(key)) { + if (this.isFileParam(_formParams[key])) { + // file field + request.attach(key, _formParams[key]); + } else { + request.field(key, _formParams[key]); + } + } + } + } else if (bodyParam) { + request.send(bodyParam); + } + + var accept = this.jsonPreferredMime(accepts); + if (accept) { + request.accept(accept); + } + + request.end(function(error, response) { + if (callback) { + var data = response && response.body; + callback(error, data, response); + } + }); + + return request; + }; + + ApiClient.default = new ApiClient(); + + return ApiClient; +})); diff --git a/samples/client/petstore/javascript/src/api/PetApi.js b/samples/client/petstore/javascript/src/api/PetApi.js index 3b6d9c5b4c..1746e343ab 100644 --- a/samples/client/petstore/javascript/src/api/PetApi.js +++ b/samples/client/petstore/javascript/src/api/PetApi.js @@ -1,527 +1,462 @@ -// require files in Node.js environment -var $, Pet; -if (typeof module === 'object' && module.exports) { - $ = require('jquery'); - Pet = require('../model/Pet.js'); -} +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient', '../model/Pet'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient'), require('../model/Pet')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.PetApi = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Pet); + } +}(this, function(ApiClient, Pet) { + 'use strict'; -// export module for AMD -if ( typeof define === "function" && define.amd ) { - define(['jquery', 'Pet'], function($, Pet) { - return PetApi; - }); -} + var PetApi = function PetApi(apiClient) { + this.apiClient = apiClient || ApiClient.default; -var PetApi = function PetApi() { - var self = this; - - - /** - * Update an existing pet - * - * @param {Pet} body Pet object that needs to be added to the store - * @param {function} callback the callback function - * @return void - */ - self.updatePet = function(body, callback) { - var postBody = JSON.stringify(body); - var postBinaryBody = null; + var self = this; - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); + + /** + * Update an existing pet + * + * @param {Pet} body Pet object that needs to be added to the store + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.updatePet = function(body, callback) { + var postBody = body; + + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = ['application/json', 'application/xml']; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '/pet', 'PUT', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/pet", "\\{format\\}","json")); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - path += createQueryString(queryParams); - - var options = {type: "PUT", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ + /** + * Add a new pet to the store + * + * @param {Pet} body Pet object that needs to be added to the store + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.addPet = function(body, callback) { + var postBody = body; - if (callback) { - callback(response, textStatus, jqXHR); - } + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = ['application/json', 'application/xml']; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '/pet', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); - }); - - return request; - } - - /** - * Add a new pet to the store - * - * @param {Pet} body Pet object that needs to be added to the store - * @param {function} callback the callback function - * @return void - */ - self.addPet = function(body, callback) { - var postBody = JSON.stringify(body); - var postBinaryBody = null; - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/pet", "\\{format\\}","json")); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - path += createQueryString(queryParams); - - var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param {Array} status Status values that need to be considered for filter + * @param {function} callback the callback function, accepting three arguments: error, data, response + * data is of type: Array + */ + self.findPetsByStatus = function(status, callback) { + var postBody = null; - if (callback) { - callback(response, textStatus, jqXHR); - } + + + var pathParams = { + }; + var queryParams = { + 'status': status + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + // TODO: support deserializing array of models + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '/pet/findByStatus', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); - }); - - return request; - } - - /** - * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param {Array} status Status values that need to be considered for filter - * @param {function} callback the callback function - * @return Array - */ - self.findPetsByStatus = function(status, callback) { - var postBody = null; - var postBinaryBody = null; - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/pet/findByStatus", "\\{format\\}","json")); + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param {Array} tags Tags to filter by + * @param {function} callback the callback function, accepting three arguments: error, data, response + * data is of type: Array + */ + self.findPetsByTags = function(tags, callback) { + var postBody = null; + - var queryParams = {}; - var headerParams = {}; - var formParams = {}; + + var pathParams = { + }; + var queryParams = { + 'tags': tags + }; + var headerParams = { + }; + var formParams = { + }; - - queryParams.status = status; - - - + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; - path += createQueryString(queryParams); - - var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ + var handleResponse = null; if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); + handleResponse = function(error, data, response) { + // TODO: support deserializing array of models + callback(error, data, response); + }; } - }); - - request.done(function(response, textStatus, jqXHR){ + + return this.apiClient.callApi( + '/pet/findByTags', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); - /** - * @returns Array - */ - - var myResponse = new Array(); - myResponse.constructFromObject(response); - if (callback) { - callback(myResponse, textStatus, jqXHR); - } - - }); - - return request; - } - - /** - * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param {Array} tags Tags to filter by - * @param {function} callback the callback function - * @return Array - */ - self.findPetsByTags = function(tags, callback) { - var postBody = null; - var postBinaryBody = null; - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/pet/findByTags", "\\{format\\}","json")); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - queryParams.tags = tags; - - - - - path += createQueryString(queryParams); - - var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param {Integer} petId ID of pet that needs to be fetched + * @param {function} callback the callback function, accepting three arguments: error, data, response + * data is of type: Pet + */ + self.getPetById = function(petId, callback) { + var postBody = null; - /** - * @returns Array - */ - - var myResponse = new Array(); - myResponse.constructFromObject(response); - if (callback) { - callback(myResponse, textStatus, jqXHR); + // verify the required parameter 'petId' is set + if (petId == null) { + throw "Missing the required parameter 'petId' when calling getPetById"; } - }); - - return request; - } - - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param {Integer} petId ID of pet that needs to be fetched - * @param {function} callback the callback function - * @return Pet - */ - self.getPetById = function(petId, callback) { - var postBody = null; - var postBinaryBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - //throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); - var errorRequiredMsg = "Missing the required parameter 'petId' when calling getPetById"; - throw errorRequiredMsg; - } - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); + + + var pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + if (!error && data) { + var result = new Pet(); + result.constructFromObject(data); + callback(error, result, response); + } else { + callback(error, data, response); + } + }; + } + + return this.apiClient.callApi( + '/pet/{petId}', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") -, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - path += createQueryString(queryParams); - - var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ + /** + * Updates a pet in the store with form data + * + * @param {String} petId ID of pet that needs to be updated + * @param {String} name Updated name of the pet + * @param {String} status Updated status of the pet + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.updatePetWithForm = function(petId, name, status, callback) { + var postBody = null; - /** - * @returns Pet - */ - - var myResponse = new Pet(); - myResponse.constructFromObject(response); - if (callback) { - callback(myResponse, textStatus, jqXHR); + // verify the required parameter 'petId' is set + if (petId == null) { + throw "Missing the required parameter 'petId' when calling updatePetWithForm"; } - }); - - return request; - } - - /** - * Updates a pet in the store with form data - * - * @param {String} petId ID of pet that needs to be updated - * @param {String} name Updated name of the pet - * @param {String} status Updated status of the pet - * @param {function} callback the callback function - * @return void - */ - self.updatePetWithForm = function(petId, name, status, callback) { - var postBody = null; - var postBinaryBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - //throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); - var errorRequiredMsg = "Missing the required parameter 'petId' when calling updatePetWithForm"; - throw errorRequiredMsg; - } - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); + + + var pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + 'name': name, + 'status': status + }; + + var contentTypes = ['application/x-www-form-urlencoded']; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '/pet/{petId}', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") -, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - if (name != null) - formParams.put("name", name); - if (status != null) - formParams.put("status", status); - - - path += createQueryString(queryParams); - - var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ + /** + * Deletes a pet + * + * @param {Integer} petId Pet id to delete + * @param {String} apiKey + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.deletePet = function(petId, apiKey, callback) { + var postBody = null; - if (callback) { - callback(response, textStatus, jqXHR); + // verify the required parameter 'petId' is set + if (petId == null) { + throw "Missing the required parameter 'petId' when calling deletePet"; } - }); - - return request; - } - - /** - * Deletes a pet - * - * @param {Integer} petId Pet id to delete - * @param {String} apiKey - * @param {function} callback the callback function - * @return void - */ - self.deletePet = function(petId, apiKey, callback) { - var postBody = null; - var postBinaryBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - //throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); - var errorRequiredMsg = "Missing the required parameter 'petId' when calling deletePet"; - throw errorRequiredMsg; - } - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); + + + var pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + 'api_key': apiKey + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '/pet/{petId}', 'DELETE', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") -, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - if (apiKey != null) - headerParams.put("api_key", apiKey); - - - - path += createQueryString(queryParams); - - var options = {type: "DELETE", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ + /** + * uploads an image + * + * @param {Integer} petId ID of pet to update + * @param {String} additionalMetadata Additional data to pass to server + * @param {File} file file to upload + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.uploadFile = function(petId, additionalMetadata, file, callback) { + var postBody = null; - if (callback) { - callback(response, textStatus, jqXHR); + // verify the required parameter 'petId' is set + if (petId == null) { + throw "Missing the required parameter 'petId' when calling uploadFile"; } - }); - - return request; - } - - /** - * uploads an image - * - * @param {Integer} petId ID of pet to update - * @param {String} additionalMetadata Additional data to pass to server - * @param {File} file file to upload - * @param {function} callback the callback function - * @return void - */ - self.uploadFile = function(petId, additionalMetadata, file, callback) { - var postBody = null; - var postBinaryBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - //throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); - var errorRequiredMsg = "Missing the required parameter 'petId' when calling uploadFile"; - throw errorRequiredMsg; - } - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); + + + var pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + 'additionalMetadata': additionalMetadata, + 'file': file + }; + + var contentTypes = ['multipart/form-data']; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '/pet/{petId}/uploadImage', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/pet/{petId}/uploadImage", "\\{format\\}","json") -, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - if (additionalMetadata != null) - formParams.put("additionalMetadata", additionalMetadata); - if (file != null) - formParams.put("file", file); - - - path += createQueryString(queryParams); - - var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ + /** + * Fake endpoint to test byte array return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param {Integer} petId ID of pet that needs to be fetched + * @param {function} callback the callback function, accepting three arguments: error, data, response + * data is of type: String + */ + self.getPetByIdWithByteArray = function(petId, callback) { + var postBody = null; - if (callback) { - callback(response, textStatus, jqXHR); + // verify the required parameter 'petId' is set + if (petId == null) { + throw "Missing the required parameter 'petId' when calling getPetByIdWithByteArray"; } - }); - - return request; - } - - - function replaceAll (haystack, needle, replace) { - var result= haystack; - if (needle !=null && replace!=null) { - result= haystack.replace(new RegExp(needle, 'g'), replace); - } - return result; - } + + var pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; - function createQueryString (queryParams) { - var queryString =''; - var i = 0; - for (var queryParamName in queryParams) { - if (i==0) { - queryString += '?' ; - } else { - queryString += '&' ; - } - - queryString += queryParamName + '=' + encodeURIComponent(queryParams[queryParamName]); - i++; - } - - return queryString; - } -} + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; -// export module for Node.js -if (typeof module === 'object' && module.exports) { - module.exports = PetApi; -} + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '/pet/{petId}?testing_byte_array=true', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + + } + + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param {String} body Pet object in the form of byte array + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.addPetUsingByteArray = function(body, callback) { + var postBody = body; + + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = ['application/json', 'application/xml']; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '/pet?testing_byte_array=true', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + + } + + + }; + + return PetApi; +})); diff --git a/samples/client/petstore/javascript/src/api/StoreApi.js b/samples/client/petstore/javascript/src/api/StoreApi.js index e52a310596..7ef38358e9 100644 --- a/samples/client/petstore/javascript/src/api/StoreApi.js +++ b/samples/client/petstore/javascript/src/api/StoreApi.js @@ -1,286 +1,206 @@ -// require files in Node.js environment -var $, Order; -if (typeof module === 'object' && module.exports) { - $ = require('jquery'); - Order = require('../model/Order.js'); -} +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient', '../model/Order'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient'), require('../model/Order')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.StoreApi = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Order); + } +}(this, function(ApiClient, Order) { + 'use strict'; -// export module for AMD -if ( typeof define === "function" && define.amd ) { - define(['jquery', 'Order'], function($, Order) { - return StoreApi; - }); -} + var StoreApi = function StoreApi(apiClient) { + this.apiClient = apiClient || ApiClient.default; -var StoreApi = function StoreApi() { - var self = this; - - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @param {function} callback the callback function - * @return Object - */ - self.getInventory = function(callback) { - var postBody = null; - var postBinaryBody = null; + var self = this; - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @param {function} callback the callback function, accepting three arguments: error, data, response + * data is of type: Object + */ + self.getInventory = function(callback) { + var postBody = null; + + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '/store/inventory', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/store/inventory", "\\{format\\}","json")); + /** + * Place an order for a pet + * + * @param {Order} body order placed for purchasing the pet + * @param {function} callback the callback function, accepting three arguments: error, data, response + * data is of type: Order + */ + self.placeOrder = function(body, callback) { + var postBody = body; + - var queryParams = {}; - var headerParams = {}; - var formParams = {}; + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; - - - + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; - path += createQueryString(queryParams); - - var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ + var handleResponse = null; if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); + handleResponse = function(error, data, response) { + if (!error && data) { + var result = new Order(); + result.constructFromObject(data); + callback(error, result, response); + } else { + callback(error, data, response); + } + }; } - }); - - request.done(function(response, textStatus, jqXHR){ + + return this.apiClient.callApi( + '/store/order', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); - /** - * @returns Object - */ - var myResponse = response; - - if (callback) { - callback(myResponse, textStatus, jqXHR); - } - - }); - - return request; - } - - /** - * Place an order for a pet - * - * @param {Order} body order placed for purchasing the pet - * @param {function} callback the callback function - * @return Order - */ - self.placeOrder = function(body, callback) { - var postBody = JSON.stringify(body); - var postBinaryBody = null; - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/store/order", "\\{format\\}","json")); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - path += createQueryString(queryParams); - - var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param {String} orderId ID of pet that needs to be fetched + * @param {function} callback the callback function, accepting three arguments: error, data, response + * data is of type: Order + */ + self.getOrderById = function(orderId, callback) { + var postBody = null; - /** - * @returns Order - */ - - var myResponse = new Order(); - myResponse.constructFromObject(response); - if (callback) { - callback(myResponse, textStatus, jqXHR); + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw "Missing the required parameter 'orderId' when calling getOrderById"; } - }); - - return request; - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param {String} orderId ID of pet that needs to be fetched - * @param {function} callback the callback function - * @return Order - */ - self.getOrderById = function(orderId, callback) { - var postBody = null; - var postBinaryBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - //throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); - var errorRequiredMsg = "Missing the required parameter 'orderId' when calling getOrderById"; - throw errorRequiredMsg; - } - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); + + + var pathParams = { + 'orderId': orderId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + if (!error && data) { + var result = new Order(); + result.constructFromObject(data); + callback(error, result, response); + } else { + callback(error, data, response); + } + }; + } + + return this.apiClient.callApi( + '/store/order/{orderId}', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/store/order/{orderId}", "\\{format\\}","json") -, "\\{" + "orderId" + "\\}", encodeURIComponent(orderId.toString())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - path += createQueryString(queryParams); - - var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param {String} orderId ID of the order that needs to be deleted + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.deleteOrder = function(orderId, callback) { + var postBody = null; - /** - * @returns Order - */ - - var myResponse = new Order(); - myResponse.constructFromObject(response); - if (callback) { - callback(myResponse, textStatus, jqXHR); + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw "Missing the required parameter 'orderId' when calling deleteOrder"; } - }); - - return request; - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param {String} orderId ID of the order that needs to be deleted - * @param {function} callback the callback function - * @return void - */ - self.deleteOrder = function(orderId, callback) { - var postBody = null; - var postBinaryBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - //throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); - var errorRequiredMsg = "Missing the required parameter 'orderId' when calling deleteOrder"; - throw errorRequiredMsg; - } - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); + + + var pathParams = { + 'orderId': orderId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '/store/order/{orderId}', 'DELETE', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/store/order/{orderId}", "\\{format\\}","json") -, "\\{" + "orderId" + "\\}", encodeURIComponent(orderId.toString())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - + }; - path += createQueryString(queryParams); - - var options = {type: "DELETE", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ - - if (callback) { - callback(response, textStatus, jqXHR); - } - - }); - - return request; - } - - - - function replaceAll (haystack, needle, replace) { - var result= haystack; - if (needle !=null && replace!=null) { - result= haystack.replace(new RegExp(needle, 'g'), replace); - } - return result; - } - - function createQueryString (queryParams) { - var queryString =''; - var i = 0; - for (var queryParamName in queryParams) { - if (i==0) { - queryString += '?' ; - } else { - queryString += '&' ; - } - - queryString += queryParamName + '=' + encodeURIComponent(queryParams[queryParamName]); - i++; - } - - return queryString; - } -} - -// export module for Node.js -if (typeof module === 'object' && module.exports) { - module.exports = StoreApi; -} + return StoreApi; +})); diff --git a/samples/client/petstore/javascript/src/api/UserApi.js b/samples/client/petstore/javascript/src/api/UserApi.js index 148e6171ed..528214b2f8 100644 --- a/samples/client/petstore/javascript/src/api/UserApi.js +++ b/samples/client/petstore/javascript/src/api/UserApi.js @@ -1,498 +1,361 @@ -// require files in Node.js environment -var $, User; -if (typeof module === 'object' && module.exports) { - $ = require('jquery'); - User = require('../model/User.js'); -} +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient', '../model/User'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient'), require('../model/User')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.UserApi = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.User); + } +}(this, function(ApiClient, User) { + 'use strict'; -// export module for AMD -if ( typeof define === "function" && define.amd ) { - define(['jquery', 'User'], function($, User) { - return UserApi; - }); -} + var UserApi = function UserApi(apiClient) { + this.apiClient = apiClient || ApiClient.default; -var UserApi = function UserApi() { - var self = this; - - - /** - * Create user - * This can only be done by the logged in user. - * @param {User} body Created user object - * @param {function} callback the callback function - * @return void - */ - self.createUser = function(body, callback) { - var postBody = JSON.stringify(body); - var postBinaryBody = null; + var self = this; - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); + + /** + * Create user + * This can only be done by the logged in user. + * @param {User} body Created user object + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.createUser = function(body, callback) { + var postBody = body; + + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '/user', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/user", "\\{format\\}","json")); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - path += createQueryString(queryParams); - - var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ + /** + * Creates list of users with given input array + * + * @param {Array} body List of user object + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.createUsersWithArrayInput = function(body, callback) { + var postBody = body; - if (callback) { - callback(response, textStatus, jqXHR); - } + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '/user/createWithArray', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); - }); - - return request; - } - - /** - * Creates list of users with given input array - * - * @param {Array} body List of user object - * @param {function} callback the callback function - * @return void - */ - self.createUsersWithArrayInput = function(body, callback) { - var postBody = JSON.stringify(body); - var postBinaryBody = null; - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/user/createWithArray", "\\{format\\}","json")); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - path += createQueryString(queryParams); - - var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ + /** + * Creates list of users with given input array + * + * @param {Array} body List of user object + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.createUsersWithListInput = function(body, callback) { + var postBody = body; - if (callback) { - callback(response, textStatus, jqXHR); - } + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '/user/createWithList', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); - }); - - return request; - } - - /** - * Creates list of users with given input array - * - * @param {Array} body List of user object - * @param {function} callback the callback function - * @return void - */ - self.createUsersWithListInput = function(body, callback) { - var postBody = JSON.stringify(body); - var postBinaryBody = null; - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/user/createWithList", "\\{format\\}","json")); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - path += createQueryString(queryParams); - - var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ + /** + * Logs user into the system + * + * @param {String} username The user name for login + * @param {String} password The password for login in clear text + * @param {function} callback the callback function, accepting three arguments: error, data, response + * data is of type: String + */ + self.loginUser = function(username, password, callback) { + var postBody = null; - if (callback) { - callback(response, textStatus, jqXHR); - } + + + var pathParams = { + }; + var queryParams = { + 'username': username, + 'password': password + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '/user/login', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); - }); - - return request; - } - - /** - * Logs user into the system - * - * @param {String} username The user name for login - * @param {String} password The password for login in clear text - * @param {function} callback the callback function - * @return String - */ - self.loginUser = function(username, password, callback) { - var postBody = null; - var postBinaryBody = null; - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/user/login", "\\{format\\}","json")); + /** + * Logs out current logged in user session + * + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.logoutUser = function(callback) { + var postBody = null; + - var queryParams = {}; - var headerParams = {}; - var formParams = {}; + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; - - queryParams.username = username; - - queryParams.password = password; - - - + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; - path += createQueryString(queryParams); - - var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ + var handleResponse = null; if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); + handleResponse = function(error, data, response) { + callback(error, data, response); + }; } - }); - - request.done(function(response, textStatus, jqXHR){ + + return this.apiClient.callApi( + '/user/logout', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); - /** - * @returns String - */ - var myResponse = response; - - if (callback) { - callback(myResponse, textStatus, jqXHR); - } - - }); - - return request; - } - - /** - * Logs out current logged in user session - * - * @param {function} callback the callback function - * @return void - */ - self.logoutUser = function(callback) { - var postBody = null; - var postBinaryBody = null; - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/user/logout", "\\{format\\}","json")); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - path += createQueryString(queryParams); - - var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ + /** + * Get user by user name + * + * @param {String} username The name that needs to be fetched. Use user1 for testing. + * @param {function} callback the callback function, accepting three arguments: error, data, response + * data is of type: User + */ + self.getUserByName = function(username, callback) { + var postBody = null; - if (callback) { - callback(response, textStatus, jqXHR); + // verify the required parameter 'username' is set + if (username == null) { + throw "Missing the required parameter 'username' when calling getUserByName"; } - }); - - return request; - } - - /** - * Get user by user name - * - * @param {String} username The name that needs to be fetched. Use user1 for testing. - * @param {function} callback the callback function - * @return User - */ - self.getUserByName = function(username, callback) { - var postBody = null; - var postBinaryBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - //throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); - var errorRequiredMsg = "Missing the required parameter 'username' when calling getUserByName"; - throw errorRequiredMsg; - } - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); + + + var pathParams = { + 'username': username + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + if (!error && data) { + var result = new User(); + result.constructFromObject(data); + callback(error, result, response); + } else { + callback(error, data, response); + } + }; + } + + return this.apiClient.callApi( + '/user/{username}', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json") -, "\\{" + "username" + "\\}", encodeURIComponent(username.toString())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - path += createQueryString(queryParams); - - var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ + /** + * Updated user + * This can only be done by the logged in user. + * @param {String} username name that need to be deleted + * @param {User} body Updated user object + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.updateUser = function(username, body, callback) { + var postBody = body; - /** - * @returns User - */ - - var myResponse = new User(); - myResponse.constructFromObject(response); - if (callback) { - callback(myResponse, textStatus, jqXHR); + // verify the required parameter 'username' is set + if (username == null) { + throw "Missing the required parameter 'username' when calling updateUser"; } - }); - - return request; - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param {String} username name that need to be deleted - * @param {User} body Updated user object - * @param {function} callback the callback function - * @return void - */ - self.updateUser = function(username, body, callback) { - var postBody = JSON.stringify(body); - var postBinaryBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - //throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); - var errorRequiredMsg = "Missing the required parameter 'username' when calling updateUser"; - throw errorRequiredMsg; - } - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); + + + var pathParams = { + 'username': username + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '/user/{username}', 'PUT', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json") -, "\\{" + "username" + "\\}", encodeURIComponent(username.toString())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - - - - path += createQueryString(queryParams); - - var options = {type: "PUT", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ + /** + * Delete user + * This can only be done by the logged in user. + * @param {String} username The name that needs to be deleted + * @param {function} callback the callback function, accepting three arguments: error, data, response + */ + self.deleteUser = function(username, callback) { + var postBody = null; - if (callback) { - callback(response, textStatus, jqXHR); + // verify the required parameter 'username' is set + if (username == null) { + throw "Missing the required parameter 'username' when calling deleteUser"; } - }); - - return request; - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param {String} username The name that needs to be deleted - * @param {function} callback the callback function - * @return void - */ - self.deleteUser = function(username, callback) { - var postBody = null; - var postBinaryBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - //throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); - var errorRequiredMsg = "Missing the required parameter 'username' when calling deleteUser"; - throw errorRequiredMsg; - } - - // create path and map variables - var basePath = 'http://petstore.swagger.io/v2'; - // if basePath ends with a /, remove it as path starts with a leading / - if (basePath.substring(basePath.length-1, basePath.length)=='/') { - basePath = basePath.substring(0, basePath.length-1); + + + var pathParams = { + 'username': username + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + + var handleResponse = null; + if (callback) { + handleResponse = function(error, data, response) { + callback(error, data, response); + }; + } + + return this.apiClient.callApi( + '/user/{username}', 'DELETE', + pathParams, queryParams, headerParams, formParams, postBody, + contentTypes, accepts, handleResponse + ); + } - var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json") -, "\\{" + "username" + "\\}", encodeURIComponent(username.toString())); - - var queryParams = {}; - var headerParams = {}; - var formParams = {}; - - - + }; - path += createQueryString(queryParams); - - var options = {type: "DELETE", async: true, contentType: "application/json", dataType: "json", data: postBody}; - var request = $.ajax(path, options); - - request.fail(function(jqXHR, textStatus, errorThrown){ - if (callback) { - var error = errorThrown || textStatus || jqXHR.statusText || 'error'; - callback(null, textStatus, jqXHR, error); - } - }); - - request.done(function(response, textStatus, jqXHR){ - - if (callback) { - callback(response, textStatus, jqXHR); - } - - }); - - return request; - } - - - - function replaceAll (haystack, needle, replace) { - var result= haystack; - if (needle !=null && replace!=null) { - result= haystack.replace(new RegExp(needle, 'g'), replace); - } - return result; - } - - function createQueryString (queryParams) { - var queryString =''; - var i = 0; - for (var queryParamName in queryParams) { - if (i==0) { - queryString += '?' ; - } else { - queryString += '&' ; - } - - queryString += queryParamName + '=' + encodeURIComponent(queryParams[queryParamName]); - i++; - } - - return queryString; - } -} - -// export module for Node.js -if (typeof module === 'object' && module.exports) { - module.exports = UserApi; -} + return UserApi; +})); diff --git a/samples/client/petstore/javascript/src/index.js b/samples/client/petstore/javascript/src/index.js index b772f6024d..a6b290f5e6 100644 --- a/samples/client/petstore/javascript/src/index.js +++ b/samples/client/petstore/javascript/src/index.js @@ -1,22 +1,23 @@ -if (typeof module === 'object' && module.exports) { - var SwaggerPetstore = {}; - - SwaggerPetstore.User = require('./model/User.js'); - - SwaggerPetstore.Category = require('./model/Category.js'); - - SwaggerPetstore.Pet = require('./model/Pet.js'); - - SwaggerPetstore.Tag = require('./model/Tag.js'); - - SwaggerPetstore.Order = require('./model/Order.js'); - - - SwaggerPetstore.UserApi = require('./api/UserApi.js'); - - SwaggerPetstore.StoreApi = require('./api/StoreApi.js'); - - SwaggerPetstore.PetApi = require('./api/PetApi.js'); - - module.exports = SwaggerPetstore; -} \ No newline at end of file +(function(factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['./ApiClient', './model/User', './model/Category', './model/Pet', './model/Tag', './model/Order', './api/UserApi', './api/StoreApi', './api/PetApi'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('./ApiClient'), require('./model/User'), require('./model/Category'), require('./model/Pet'), require('./model/Tag'), require('./model/Order'), require('./api/UserApi'), require('./api/StoreApi'), require('./api/PetApi')); + } +}(function(ApiClient, User, Category, Pet, Tag, Order, UserApi, StoreApi, PetApi) { + 'use strict'; + + return { + ApiClient: ApiClient, + User: User, + Category: Category, + Pet: Pet, + Tag: Tag, + Order: Order, + UserApi: UserApi, + StoreApi: StoreApi, + PetApi: PetApi + }; +})); diff --git a/samples/client/petstore/javascript/src/model/Category.js b/samples/client/petstore/javascript/src/model/Category.js index ff40497a61..6b302a32f3 100644 --- a/samples/client/petstore/javascript/src/model/Category.js +++ b/samples/client/petstore/javascript/src/model/Category.js @@ -1,81 +1,89 @@ -// require files in Node.js environment +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([undefined], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(undefined); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + factory(root.SwaggerPetstore); + } +}(this, function(module) { + 'use strict'; -if (typeof module === 'object' && module.exports) { - -} - - - - -//export module -if ( typeof define === "function" && define.amd ) { - define('Category', ['jquery'], - function($) { - return Category; - }); -} - - -var Category = function Category() { - var self = this; - - /** - * datatype: Integer - **/ - self.id = null; - - /** - * datatype: String - **/ - self.name = null; - self.constructFromObject = function(data) { - if (!data) { - return; + + + var Category = function Category() { + var self = this; + + /** + * datatype: Integer + **/ + self.id = null; + + /** + * datatype: String + **/ + self.name = null; + + + self.constructFromObject = function(data) { + if (!data) { + return; + } + + self.id = data.id; + + self.name = data.name; + + } + + + /** + * @return {Integer} + **/ + self.getId = function() { + return self.id; + } + + /** + * @param {Integer} id + **/ + self.setId = function (id) { + self.id = id; } - self.id = data.id; - - self.name = data.name; + /** + * @return {String} + **/ + self.getName = function() { + return self.name; + } + + /** + * @param {String} name + **/ + self.setName = function (name) { + self.name = name; + } + + self.toJson = function () { + return JSON.stringify(self); + } + }; + + if (module) { + module.Category = Category; } + return Category; - /** - * @return {Integer} - **/ - self.getId = function() { - return self.id; - } - - /** - * @param {Integer} id - **/ - self.setId = function (id) { - self.id = id; - } - /** - * @return {String} - **/ - self.getName = function() { - return self.name; - } - - /** - * @param {String} name - **/ - self.setName = function (name) { - self.name = name; - } - - - self.toJson = function () { - return JSON.stringify(self); - } -} - -if (typeof module === 'object' && module.exports) { - module.exports = Category; -} +})); diff --git a/samples/client/petstore/javascript/src/model/Order.js b/samples/client/petstore/javascript/src/model/Order.js index 3cf2335b53..9f641242bf 100644 --- a/samples/client/petstore/javascript/src/model/Order.js +++ b/samples/client/petstore/javascript/src/model/Order.js @@ -1,11 +1,22 @@ -// require files in Node.js environment +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([undefined], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(undefined); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + factory(root.SwaggerPetstore); + } +}(this, function(module) { + 'use strict'; -if (typeof module === 'object' && module.exports) { -} - - - + //export module if ( typeof define === "function" && define.amd ) { define('StatusEnum', ['jquery'], function($) { @@ -35,162 +46,159 @@ var StatusEnum = function StatusEnum() { } -//export module -if ( typeof define === "function" && define.amd ) { - define('Order', ['jquery'], - function($) { - return Order; - }); -} + + var Order = function Order() { + var self = this; + + /** + * datatype: Integer + **/ + self.id = null; + + /** + * datatype: Integer + **/ + self.petId = null; + + /** + * datatype: Integer + **/ + self.quantity = null; + + /** + * datatype: Date + **/ + self.shipDate = null; + + /** + * Order Status + * datatype: StatusEnum + **/ + self.status = null; + + /** + * datatype: Boolean + **/ + self.complete = null; + + self.constructFromObject = function(data) { + if (!data) { + return; + } + + self.id = data.id; + + self.petId = data.petId; + + self.quantity = data.quantity; + + self.shipDate = data.shipDate; + + self.status = data.status; + + self.complete = data.complete; + + } -var Order = function Order() { - var self = this; - - /** - * datatype: Integer - **/ - self.id = null; - - /** - * datatype: Integer - **/ - self.petId = null; - - /** - * datatype: Integer - **/ - self.quantity = null; - - /** - * datatype: Date - **/ - self.shipDate = null; - - /** - * Order Status - * datatype: StatusEnum - **/ - self.status = null; - - /** - * datatype: Boolean - **/ - self.complete = null; - - - self.constructFromObject = function(data) { - if (!data) { - return; + + /** + * @return {Integer} + **/ + self.getId = function() { + return self.id; + } + + /** + * @param {Integer} id + **/ + self.setId = function (id) { + self.id = id; } - self.id = data.id; + /** + * @return {Integer} + **/ + self.getPetId = function() { + return self.petId; + } + + /** + * @param {Integer} petId + **/ + self.setPetId = function (petId) { + self.petId = petId; + } - self.petId = data.petId; + /** + * @return {Integer} + **/ + self.getQuantity = function() { + return self.quantity; + } + + /** + * @param {Integer} quantity + **/ + self.setQuantity = function (quantity) { + self.quantity = quantity; + } - self.quantity = data.quantity; + /** + * @return {Date} + **/ + self.getShipDate = function() { + return self.shipDate; + } + + /** + * @param {Date} shipDate + **/ + self.setShipDate = function (shipDate) { + self.shipDate = shipDate; + } - self.shipDate = data.shipDate; + /** + * get Order Status + * @return {StatusEnum} + **/ + self.getStatus = function() { + return self.status; + } + + /** + * set Order Status + * @param {StatusEnum} status + **/ + self.setStatus = function (status) { + self.status = status; + } - self.status = data.status; - - self.complete = data.complete; + /** + * @return {Boolean} + **/ + self.getComplete = function() { + return self.complete; + } + + /** + * @param {Boolean} complete + **/ + self.setComplete = function (complete) { + self.complete = complete; + } + + self.toJson = function () { + return JSON.stringify(self); + } + }; + + if (module) { + module.Order = Order; } + return Order; - /** - * @return {Integer} - **/ - self.getId = function() { - return self.id; - } - - /** - * @param {Integer} id - **/ - self.setId = function (id) { - self.id = id; - } - /** - * @return {Integer} - **/ - self.getPetId = function() { - return self.petId; - } - - /** - * @param {Integer} petId - **/ - self.setPetId = function (petId) { - self.petId = petId; - } - - /** - * @return {Integer} - **/ - self.getQuantity = function() { - return self.quantity; - } - - /** - * @param {Integer} quantity - **/ - self.setQuantity = function (quantity) { - self.quantity = quantity; - } - - /** - * @return {Date} - **/ - self.getShipDate = function() { - return self.shipDate; - } - - /** - * @param {Date} shipDate - **/ - self.setShipDate = function (shipDate) { - self.shipDate = shipDate; - } - - /** - * get Order Status - * @return {StatusEnum} - **/ - self.getStatus = function() { - return self.status; - } - - /** - * set Order Status - * @param {StatusEnum} status - **/ - self.setStatus = function (status) { - self.status = status; - } - - /** - * @return {Boolean} - **/ - self.getComplete = function() { - return self.complete; - } - - /** - * @param {Boolean} complete - **/ - self.setComplete = function (complete) { - self.complete = complete; - } - - - self.toJson = function () { - return JSON.stringify(self); - } -} - -if (typeof module === 'object' && module.exports) { - module.exports = Order; -} +})); diff --git a/samples/client/petstore/javascript/src/model/Pet.js b/samples/client/petstore/javascript/src/model/Pet.js index 25ae2e951c..392007d6a5 100644 --- a/samples/client/petstore/javascript/src/model/Pet.js +++ b/samples/client/petstore/javascript/src/model/Pet.js @@ -1,13 +1,22 @@ -// require files in Node.js environment -var Category;var Tag; -if (typeof module === 'object' && module.exports) { +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([undefined, './Category', './Tag'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(undefined, require('./Category'), require('./Tag')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + factory(root.SwaggerPetstore, root.SwaggerPetstore.Category, root.SwaggerPetstore.Tag); + } +}(this, function(module, Category, Tag) { + 'use strict'; + + - Category = require('./Category.js'); - Tag = require('./Tag.js'); -} - - - //export module if ( typeof define === "function" && define.amd ) { define('StatusEnum', ['jquery'], function($) { @@ -37,164 +46,161 @@ var StatusEnum = function StatusEnum() { } -//export module -if ( typeof define === "function" && define.amd ) { - define('Pet', ['jquery', 'Category', 'Array'], - function($, Category, Array) { - return Pet; - }); -} + + var Pet = function Pet(photoUrls, name) { + var self = this; + + /** + * datatype: Integer + **/ + self.id = null; + + /** + * datatype: Category + **/ + self.category = new Category(); + + /** + * datatype: String + * required + **/ + self.name = name; + + /** + * datatype: Array + * required + **/ + self.photoUrls = photoUrls; + + /** + * datatype: Array + **/ + self.tags = []; + + /** + * pet status in the store + * datatype: StatusEnum + **/ + self.status = null; + + self.constructFromObject = function(data) { + if (!data) { + return; + } + + self.id = data.id; + + self.category.constructFromObject(data.category); + + self.name = data.name; + + self.photoUrls = data.photoUrls; + + self.tags = data.tags; + + self.status = data.status; + + } -var Pet = function Pet(photoUrls, name) { - var self = this; - - /** - * datatype: Integer - **/ - self.id = null; - - /** - * datatype: Category - **/ - self.category = new Category(); - - /** - * datatype: String - * required - **/ - self.name = name; - - /** - * datatype: Array - * required - **/ - self.photoUrls = photoUrls; - - /** - * datatype: Array - **/ - self.tags = []; - - /** - * pet status in the store - * datatype: StatusEnum - **/ - self.status = null; - - - self.constructFromObject = function(data) { - if (!data) { - return; + + /** + * @return {Integer} + **/ + self.getId = function() { + return self.id; + } + + /** + * @param {Integer} id + **/ + self.setId = function (id) { + self.id = id; } - self.id = data.id; + /** + * @return {Category} + **/ + self.getCategory = function() { + return self.category; + } + + /** + * @param {Category} category + **/ + self.setCategory = function (category) { + self.category = category; + } - self.category.constructFromObject(data.category); + /** + * @return {String} + **/ + self.getName = function() { + return self.name; + } + + /** + * @param {String} name + **/ + self.setName = function (name) { + self.name = name; + } - self.name = data.name; + /** + * @return {Array} + **/ + self.getPhotoUrls = function() { + return self.photoUrls; + } + + /** + * @param {Array} photoUrls + **/ + self.setPhotoUrls = function (photoUrls) { + self.photoUrls = photoUrls; + } - self.photoUrls = new Array(); + /** + * @return {Array} + **/ + self.getTags = function() { + return self.tags; + } + + /** + * @param {Array} tags + **/ + self.setTags = function (tags) { + self.tags = tags; + } - self.tags = new Array(); - - self.status = data.status; + /** + * get pet status in the store + * @return {StatusEnum} + **/ + self.getStatus = function() { + return self.status; + } + + /** + * set pet status in the store + * @param {StatusEnum} status + **/ + self.setStatus = function (status) { + self.status = status; + } + + self.toJson = function () { + return JSON.stringify(self); + } + }; + + if (module) { + module.Pet = Pet; } + return Pet; - /** - * @return {Integer} - **/ - self.getId = function() { - return self.id; - } - - /** - * @param {Integer} id - **/ - self.setId = function (id) { - self.id = id; - } - /** - * @return {Category} - **/ - self.getCategory = function() { - return self.category; - } - - /** - * @param {Category} category - **/ - self.setCategory = function (category) { - self.category = category; - } - - /** - * @return {String} - **/ - self.getName = function() { - return self.name; - } - - /** - * @param {String} name - **/ - self.setName = function (name) { - self.name = name; - } - - /** - * @return {Array} - **/ - self.getPhotoUrls = function() { - return self.photoUrls; - } - - /** - * @param {Array} photoUrls - **/ - self.setPhotoUrls = function (photoUrls) { - self.photoUrls = photoUrls; - } - - /** - * @return {Array} - **/ - self.getTags = function() { - return self.tags; - } - - /** - * @param {Array} tags - **/ - self.setTags = function (tags) { - self.tags = tags; - } - - /** - * get pet status in the store - * @return {StatusEnum} - **/ - self.getStatus = function() { - return self.status; - } - - /** - * set pet status in the store - * @param {StatusEnum} status - **/ - self.setStatus = function (status) { - self.status = status; - } - - - self.toJson = function () { - return JSON.stringify(self); - } -} - -if (typeof module === 'object' && module.exports) { - module.exports = Pet; -} +})); diff --git a/samples/client/petstore/javascript/src/model/Tag.js b/samples/client/petstore/javascript/src/model/Tag.js index 0fa97bd8c7..2dbf932f30 100644 --- a/samples/client/petstore/javascript/src/model/Tag.js +++ b/samples/client/petstore/javascript/src/model/Tag.js @@ -1,81 +1,89 @@ -// require files in Node.js environment +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([undefined], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(undefined); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + factory(root.SwaggerPetstore); + } +}(this, function(module) { + 'use strict'; -if (typeof module === 'object' && module.exports) { - -} - - - - -//export module -if ( typeof define === "function" && define.amd ) { - define('Tag', ['jquery'], - function($) { - return Tag; - }); -} - - -var Tag = function Tag() { - var self = this; - - /** - * datatype: Integer - **/ - self.id = null; - - /** - * datatype: String - **/ - self.name = null; - self.constructFromObject = function(data) { - if (!data) { - return; + + + var Tag = function Tag() { + var self = this; + + /** + * datatype: Integer + **/ + self.id = null; + + /** + * datatype: String + **/ + self.name = null; + + + self.constructFromObject = function(data) { + if (!data) { + return; + } + + self.id = data.id; + + self.name = data.name; + + } + + + /** + * @return {Integer} + **/ + self.getId = function() { + return self.id; + } + + /** + * @param {Integer} id + **/ + self.setId = function (id) { + self.id = id; } - self.id = data.id; - - self.name = data.name; + /** + * @return {String} + **/ + self.getName = function() { + return self.name; + } + + /** + * @param {String} name + **/ + self.setName = function (name) { + self.name = name; + } + + self.toJson = function () { + return JSON.stringify(self); + } + }; + + if (module) { + module.Tag = Tag; } + return Tag; - /** - * @return {Integer} - **/ - self.getId = function() { - return self.id; - } - - /** - * @param {Integer} id - **/ - self.setId = function (id) { - self.id = id; - } - /** - * @return {String} - **/ - self.getName = function() { - return self.name; - } - - /** - * @param {String} name - **/ - self.setName = function (name) { - self.name = name; - } - - - self.toJson = function () { - return JSON.stringify(self); - } -} - -if (typeof module === 'object' && module.exports) { - module.exports = Tag; -} +})); diff --git a/samples/client/petstore/javascript/src/model/User.js b/samples/client/petstore/javascript/src/model/User.js index 632208a523..a76ccf1901 100644 --- a/samples/client/petstore/javascript/src/model/User.js +++ b/samples/client/petstore/javascript/src/model/User.js @@ -1,210 +1,218 @@ -// require files in Node.js environment +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([undefined], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(undefined); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + factory(root.SwaggerPetstore); + } +}(this, function(module) { + 'use strict'; -if (typeof module === 'object' && module.exports) { -} + + + var User = function User() { + var self = this; + + /** + * datatype: Integer + **/ + self.id = null; + + /** + * datatype: String + **/ + self.username = null; + + /** + * datatype: String + **/ + self.firstName = null; + + /** + * datatype: String + **/ + self.lastName = null; + + /** + * datatype: String + **/ + self.email = null; + + /** + * datatype: String + **/ + self.password = null; + + /** + * datatype: String + **/ + self.phone = null; + + /** + * User Status + * datatype: Integer + **/ + self.userStatus = null; + + self.constructFromObject = function(data) { + if (!data) { + return; + } + + self.id = data.id; + + self.username = data.username; + + self.firstName = data.firstName; + + self.lastName = data.lastName; + + self.email = data.email; + + self.password = data.password; + + self.phone = data.phone; + + self.userStatus = data.userStatus; + + } + + /** + * @return {Integer} + **/ + self.getId = function() { + return self.id; + } -//export module -if ( typeof define === "function" && define.amd ) { - define('User', ['jquery'], - function($) { - return User; - }); -} - - -var User = function User() { - var self = this; - - /** - * datatype: Integer - **/ - self.id = null; - - /** - * datatype: String - **/ - self.username = null; - - /** - * datatype: String - **/ - self.firstName = null; - - /** - * datatype: String - **/ - self.lastName = null; - - /** - * datatype: String - **/ - self.email = null; - - /** - * datatype: String - **/ - self.password = null; - - /** - * datatype: String - **/ - self.phone = null; - - /** - * User Status - * datatype: Integer - **/ - self.userStatus = null; - - - self.constructFromObject = function(data) { - if (!data) { - return; + /** + * @param {Integer} id + **/ + self.setId = function (id) { + self.id = id; } - self.id = data.id; + /** + * @return {String} + **/ + self.getUsername = function() { + return self.username; + } + + /** + * @param {String} username + **/ + self.setUsername = function (username) { + self.username = username; + } - self.username = data.username; + /** + * @return {String} + **/ + self.getFirstName = function() { + return self.firstName; + } + + /** + * @param {String} firstName + **/ + self.setFirstName = function (firstName) { + self.firstName = firstName; + } - self.firstName = data.firstName; + /** + * @return {String} + **/ + self.getLastName = function() { + return self.lastName; + } + + /** + * @param {String} lastName + **/ + self.setLastName = function (lastName) { + self.lastName = lastName; + } - self.lastName = data.lastName; + /** + * @return {String} + **/ + self.getEmail = function() { + return self.email; + } + + /** + * @param {String} email + **/ + self.setEmail = function (email) { + self.email = email; + } - self.email = data.email; + /** + * @return {String} + **/ + self.getPassword = function() { + return self.password; + } + + /** + * @param {String} password + **/ + self.setPassword = function (password) { + self.password = password; + } - self.password = data.password; + /** + * @return {String} + **/ + self.getPhone = function() { + return self.phone; + } + + /** + * @param {String} phone + **/ + self.setPhone = function (phone) { + self.phone = phone; + } - self.phone = data.phone; - - self.userStatus = data.userStatus; + /** + * get User Status + * @return {Integer} + **/ + self.getUserStatus = function() { + return self.userStatus; + } + + /** + * set User Status + * @param {Integer} userStatus + **/ + self.setUserStatus = function (userStatus) { + self.userStatus = userStatus; + } + + self.toJson = function () { + return JSON.stringify(self); + } + }; + + if (module) { + module.User = User; } + return User; - /** - * @return {Integer} - **/ - self.getId = function() { - return self.id; - } - - /** - * @param {Integer} id - **/ - self.setId = function (id) { - self.id = id; - } - /** - * @return {String} - **/ - self.getUsername = function() { - return self.username; - } - - /** - * @param {String} username - **/ - self.setUsername = function (username) { - self.username = username; - } - - /** - * @return {String} - **/ - self.getFirstName = function() { - return self.firstName; - } - - /** - * @param {String} firstName - **/ - self.setFirstName = function (firstName) { - self.firstName = firstName; - } - - /** - * @return {String} - **/ - self.getLastName = function() { - return self.lastName; - } - - /** - * @param {String} lastName - **/ - self.setLastName = function (lastName) { - self.lastName = lastName; - } - - /** - * @return {String} - **/ - self.getEmail = function() { - return self.email; - } - - /** - * @param {String} email - **/ - self.setEmail = function (email) { - self.email = email; - } - - /** - * @return {String} - **/ - self.getPassword = function() { - return self.password; - } - - /** - * @param {String} password - **/ - self.setPassword = function (password) { - self.password = password; - } - - /** - * @return {String} - **/ - self.getPhone = function() { - return self.phone; - } - - /** - * @param {String} phone - **/ - self.setPhone = function (phone) { - self.phone = phone; - } - - /** - * get User Status - * @return {Integer} - **/ - self.getUserStatus = function() { - return self.userStatus; - } - - /** - * set User Status - * @param {Integer} userStatus - **/ - self.setUserStatus = function (userStatus) { - self.userStatus = userStatus; - } - - - self.toJson = function () { - return JSON.stringify(self); - } -} - -if (typeof module === 'object' && module.exports) { - module.exports = User; -} +})); diff --git a/samples/client/petstore/javascript/test/ApiClientTest.js b/samples/client/petstore/javascript/test/ApiClientTest.js new file mode 100644 index 0000000000..daae849bcf --- /dev/null +++ b/samples/client/petstore/javascript/test/ApiClientTest.js @@ -0,0 +1,120 @@ +if (typeof module === 'object' && module.exports) { + var expect = require('expect.js'); + var SwaggerPetstore = require('../src/index'); +} + +var apiClient = SwaggerPetstore.ApiClient.default; + +describe('ApiClient', function() { + describe('defaults', function() { + it('should have correct default values with the default API client', function() { + expect(apiClient).to.be.ok(); + expect(apiClient.basePath).to.be('http://petstore.swagger.io/v2'); + }); + + it('should have correct default values with new API client and can customize it', function() { + var newClient = new SwaggerPetstore.ApiClient; + expect(newClient.basePath).to.be('http://petstore.swagger.io/v2'); + expect(newClient.buildUrl('/abc', {})).to.be('http://petstore.swagger.io/v2/abc'); + + newClient.basePath = 'http://example.com'; + expect(newClient.basePath).to.be('http://example.com'); + expect(newClient.buildUrl('/abc', {})).to.be('http://example.com/abc'); + }); + }); + + describe('#paramToString', function() { + it('should return empty string for null and undefined', function() { + expect(apiClient.paramToString(null)).to.be(''); + expect(apiClient.paramToString(undefined)).to.be(''); + }); + + it('should return string', function() { + expect(apiClient.paramToString('')).to.be(''); + expect(apiClient.paramToString('abc')).to.be('abc'); + expect(apiClient.paramToString(123)).to.be('123'); + }); + }); + + describe('#buildUrl', function() { + it('should work without path parameters in the path', function() { + expect(apiClient.buildUrl('/abc', {})).to + .be('http://petstore.swagger.io/v2/abc'); + expect(apiClient.buildUrl('/abc/def?ok', {id: 123})).to + .be('http://petstore.swagger.io/v2/abc/def?ok'); + }); + + it('should work with path parameters in the path', function() { + expect(apiClient.buildUrl('/{id}', {id: 123})).to + .be('http://petstore.swagger.io/v2/123'); + expect(apiClient.buildUrl('/abc/{id}/{name}?ok', {id: 456, name: 'a b'})).to. + be('http://petstore.swagger.io/v2/abc/456/a%20b?ok'); + }); + }); + + describe('#isJsonMime', function() { + it('should return true for JSON MIME', function() { + expect(apiClient.isJsonMime('application/json')).to.be(true); + expect(apiClient.isJsonMime('application/json; charset=UTF8')).to.be(true); + expect(apiClient.isJsonMime('APPLICATION/JSON')).to.be(true); + }); + + it('should return false for non-JSON MIME', function() { + expect(apiClient.isJsonMime('')).to.be(false); + expect(apiClient.isJsonMime('text/plain')).to.be(false); + expect(apiClient.isJsonMime('application/xml')).to.be(false); + expect(apiClient.isJsonMime('application/jsonp')).to.be(false); + }); + }); + + describe('#defaultHeaders', function() { + it('should initialize default headers to be an empty object', function() { + expect(apiClient.defaultHeaders).to.eql({}); + }); + + it('should put default headers in request', function() { + var newClient = new SwaggerPetstore.ApiClient; + newClient.defaultHeaders['Content-Type'] = 'text/plain' + newClient.defaultHeaders['api_key'] = 'special-key' + + var expected = {'Content-Type': 'text/plain', 'api_key': 'special-key'}; + expect(newClient.defaultHeaders).to.eql(expected); + var req = makeDumbRequest(newClient); + req.unset('User-Agent'); + expect(req.header).to.eql(expected); + }); + + it('should override default headers with provided header params', function() { + var newClient = new SwaggerPetstore.ApiClient; + newClient.defaultHeaders['Content-Type'] = 'text/plain' + newClient.defaultHeaders['api_key'] = 'special-key' + + var headerParams = {'Content-Type': 'application/json', 'Authorization': 'Bearer test-token'} + var expected = { + 'Content-Type': 'application/json', + 'api_key': 'special-key', + 'Authorization': 'Bearer test-token' + }; + var req = makeDumbRequest(newClient, {headerParams: headerParams}); + req.unset('User-Agent'); + expect(req.header).to.eql(expected); + }); + }); +}); + +function makeDumbRequest(apiClient, opts) { + opts = opts || {}; + var path = opts.path || '/store/inventory'; + var httpMethod = opts.httpMethod || 'GET'; + var pathParams = opts.pathParams || {}; + var queryParams = opts.queryParams || {}; + var headerParams = opts.headerParams || {}; + var formParams = opts.formParams || {}; + var bodyParam = opts.bodyParam; + var contentTypes = opts.contentTypes || []; + var accepts = opts.accepts || []; + var callback = opts.callback; + return apiClient.callApi(path, httpMethod, pathParams, queryParams, + headerParams, formParams, bodyParam, contentTypes, accepts, callback + ); +} diff --git a/samples/client/petstore/javascript/test/api/PetApiTest.js b/samples/client/petstore/javascript/test/api/PetApiTest.js index 325cc16b61..9385cf2701 100644 --- a/samples/client/petstore/javascript/test/api/PetApiTest.js +++ b/samples/client/petstore/javascript/test/api/PetApiTest.js @@ -1,25 +1,21 @@ if (typeof module === 'object' && module.exports) { var expect = require('expect.js'); - var requireApiWithMocks = require('../helper.js').requireApiWithMocks; - var PetApi = requireApiWithMocks('PetApi'); - var Pet = require('../../src/model/Pet'); - var Category = require('../../src/model/Category'); - var Tag = require('../../src/model/Tag'); + var SwaggerPetstore = require('../../src/index'); } var api; beforeEach(function() { - api = new PetApi(); + api = new SwaggerPetstore.PetApi(); }); var createRandomPet = function() { var id = new Date().getTime(); - var pet = new Pet(); + var pet = new SwaggerPetstore.Pet(); pet.setId(id); pet.setName("gorilla" + id); - var category = new Category(); + var category = new SwaggerPetstore.Category(); category.setName("really-happy"); pet.setCategory(category); @@ -31,23 +27,26 @@ var createRandomPet = function() { }; describe('PetApi', function() { - it('should create and get pet', function (done) { + it('should create and get pet', function(done) { var pet = createRandomPet(); - api.addPet(pet).then(function() { - api.getPetById(pet.id, function(fetched, textStatus, jqXHR, error) { - if (error) throw error; + api.addPet(pet, function(error) { + if (error) throw error; + + api.getPetById(pet.id, function(error, fetched, response) { + if (error) throw error; + expect(response.status).to.be(200); + expect(response.ok).to.be(true); + expect(response.get('Content-Type')).to.be('application/json'); - expect(textStatus).to.be('success'); expect(fetched).to.be.ok(); expect(fetched.id).to.be(pet.id); + expect(fetched.getPhotoUrls()).to.eql(pet.getPhotoUrls()); expect(fetched.getCategory()).to.be.ok(); expect(fetched.getCategory().getName()).to.be(pet.getCategory().getName()); api.deletePet(pet.id); done(); }); - }, function(jqXHR, textStatus, errorThrown) { - throw errorThrown || textStatus; }); }); }); diff --git a/samples/client/petstore/javascript/test/api/StoreApiTest.java b/samples/client/petstore/javascript/test/api/StoreApiTest.java deleted file mode 100644 index 6094f2242e..0000000000 --- a/samples/client/petstore/javascript/test/api/StoreApiTest.java +++ /dev/null @@ -1,75 +0,0 @@ -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 java.text.SimpleDateFormat; - -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"); - // set custom date format that is used by the petstore server - api.getApiClient().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); - } - - @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/javascript/test/api/UserApiTest.java b/samples/client/petstore/javascript/test/api/UserApiTest.java deleted file mode 100644 index a3f257f568..0000000000 --- a/samples/client/petstore/javascript/test/api/UserApiTest.java +++ /dev/null @@ -1,86 +0,0 @@ -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.getId()); - 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/javascript/test/helper.js b/samples/client/petstore/javascript/test/helper.js deleted file mode 100644 index 018b6428af..0000000000 --- a/samples/client/petstore/javascript/test/helper.js +++ /dev/null @@ -1,19 +0,0 @@ -var mockrequire = require('mockrequire'); - -var jquery = require('jquery'); -var domino = require('domino'); -var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; -var window = domino.createWindow(); -var $ = jquery(window); -$.support.cors = true; -$.ajaxSettings.xhr = function() { - return new XMLHttpRequest(); -}; - -var requireApiWithMocks = function(path) { - return mockrequire('../src/api/' + path, { - 'jquery': $ - }); -}; - -exports.requireApiWithMocks = requireApiWithMocks; diff --git a/samples/client/petstore/javascript/test/run_tests.html b/samples/client/petstore/javascript/test/run_tests.html index c5655275cc..eb48f37036 100644 --- a/samples/client/petstore/javascript/test/run_tests.html +++ b/samples/client/petstore/javascript/test/run_tests.html @@ -10,7 +10,6 @@ - + + + + + + + +