mirror of
https://github.com/valitydev/openapi-generator.git
synced 2024-11-08 11:23:58 +00:00
merge latest from develop_2.0 to fork
This commit is contained in:
commit
129086eea7
72
README.md
72
README.md
@ -18,7 +18,7 @@ The Swagger Specification has undergone 3 revisions since initial creation in 20
|
||||
|
||||
Swagger Codegen Version | Release Date | Swagger Spec compatibility | Notes
|
||||
----------------------- | ------------ | -------------------------- | -----
|
||||
2.1.3-M1-SNAPSHOT | 2015-02-23 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.0-M1](https://github.com/swagger-api/swagger-codegen)
|
||||
2.1.1-M2-SNAPSHOT | 2015-04-06 | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen)
|
||||
2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17)
|
||||
1.0.4 | 2012-04-12 | 1.0, 1.1 | [tag v1.0.4](https://github.com/swagger-api/swagger-codegen/tree/swagger-codegen_2.9.1-1.1)
|
||||
|
||||
@ -52,23 +52,41 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
|
||||
-o samples/client/petstore/java
|
||||
```
|
||||
|
||||
With a number of options. You can get the options with the -h flag:
|
||||
With a number of options. You can get the options with the `help generate` command:
|
||||
|
||||
```
|
||||
usage: Codegen
|
||||
-a,--auth addes authorization headers when fetching the
|
||||
swagger definitions remotely. Pass in a
|
||||
URL-encoded string of name:header with a comma
|
||||
separating multiple values
|
||||
-d,--debug-info prints additional info for debugging
|
||||
-h,--help shows this message
|
||||
-i,--input-spec <arg> location of the swagger spec, as URL or file
|
||||
-l,--lang <arg> client language to generate.
|
||||
Available languages include:
|
||||
[android, async-scala, java, jaxrs, nodejs,
|
||||
objc, scalatra, scala, dynamic-html, html,
|
||||
swagger, tizen, php, ruby, python]
|
||||
-o,--output <arg> where to write the generated files
|
||||
-t,--template-dir <arg> folder containing the template files
|
||||
NAME
|
||||
swagger generate - Generate code with chosen lang
|
||||
|
||||
SYNOPSIS
|
||||
swagger generate [(-a <authorization> | --auth <authorization>)]
|
||||
(-i <spec file> | --input-spec <spec file>)
|
||||
(-l <language> | --lang <language>)
|
||||
[(-o <output directory> | --output <output directory>)]
|
||||
[(-t <template directory> | --template-dir <template directory>)]
|
||||
[(-v | --verbose)]
|
||||
|
||||
OPTIONS
|
||||
-a <authorization>, --auth <authorization>
|
||||
adds authorization headers when fetching the swagger definitions
|
||||
remotely. Pass in a URL-encoded string of name:header with a comma
|
||||
separating multiple values
|
||||
|
||||
-i <spec file>, --input-spec <spec file>
|
||||
location of the swagger spec, as URL or file (required)
|
||||
|
||||
-l <language>, --lang <language>
|
||||
client language to generate (maybe class name in classpath,
|
||||
required)
|
||||
|
||||
-o <output directory>, --output <output directory>
|
||||
where to write the generated files (current dir by default)
|
||||
|
||||
-t <template directory>, --template-dir <template directory>
|
||||
folder containing the template files
|
||||
|
||||
-v, --verbose
|
||||
verbose mode
|
||||
```
|
||||
|
||||
You can then compile and run the client, as well as unit tests against it:
|
||||
@ -91,18 +109,17 @@ It's just as easy--just use the `-i` flag to point to either a server or file.
|
||||
### Modifying the client library format
|
||||
Don't like the default swagger client syntax? Want a different language supported? No problem! Swagger codegen processes mustache templates with the [jmustache](https://github.com/samskivert/jmustache) engine. You can modify our templates or make your own.
|
||||
|
||||
You can look at `modules/swagger-codegen/src/main/resources/${your-language}` for examples. To make your own templates, create your own files and use the `-t` flag to specify your tempalte folder. It actually is that easy.
|
||||
You can look at `modules/swagger-codegen/src/main/resources/${your-language}` for examples. To make your own templates, create your own files and use the `-t` flag to specify your template folder. It actually is that easy.
|
||||
|
||||
### Making your own codegen modules
|
||||
If you're starting a project with a new language and don't see what you need, swagger-codegen can help you create a project to generate your own libraries:
|
||||
|
||||
```
|
||||
java -cp modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
|
||||
com.wordnik.swagger.codegen.MetaGenerator \
|
||||
java -jar modules/swagger-codegen-distribution/target/swagger-codegen-cli.jar meta \
|
||||
-o output/myLibrary -n myClientCodegen -p com.my.company.codegen
|
||||
```
|
||||
|
||||
This will write, in the folder `output/myLibrary`, all the files you need to get started, including a README.md. Once modified and compiled, you can load your library with the codegen and generate clients with your own, custom-rolled logic.
|
||||
This will write, in the folder `output/myLibrary`, all the files you need to get started, including a README.md. Once modified and compiled, you can load your library with the codegen and generate clients with your own, custom-rolled logic.
|
||||
|
||||
### Where is Javascript???
|
||||
See our [javascript library](http://github.com/swagger-api/swagger-js)--it's completely dynamic and doesn't require
|
||||
@ -127,17 +144,22 @@ There are different aspects of customizing the code generator beyond just creati
|
||||
```
|
||||
$ ls -1 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/
|
||||
AndroidClientCodegen.java
|
||||
AsyncScalaClientCodegen.java
|
||||
CSharpClientCodegen.java
|
||||
JavaClientCodegen.java
|
||||
JaxRSServerCodegen.java
|
||||
NodeJSServerCodegen.java
|
||||
ObjcClientCodegen.java
|
||||
PhpClientCodegen.java
|
||||
PythonClientCodegen.java
|
||||
RubyClientCodegen.java
|
||||
ScalaClientCodegen.java
|
||||
ScalatraServerCodegen.java
|
||||
SpringMVCServerCodegen.java
|
||||
StaticDocCodegen.java
|
||||
StaticHtmlGenerator.java
|
||||
SwaggerGenerator.java
|
||||
SwaggerYamlGenerator.java
|
||||
TizenClientCodegen.java
|
||||
```
|
||||
|
||||
@ -227,6 +249,14 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
|
||||
-o samples/server/petstore/jaxrs
|
||||
```
|
||||
|
||||
### java spring-mvc
|
||||
|
||||
```
|
||||
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
|
||||
-i http://petstore.swagger.io/v2/swagger.json \
|
||||
-l spring-mvc \
|
||||
-o samples/server/petstore/spring-mvc
|
||||
```
|
||||
### To build the codegen library
|
||||
|
||||
This will create the swagger-codegen library from source.
|
||||
|
@ -19,13 +19,15 @@ fi
|
||||
|
||||
cd $APP_DIR
|
||||
./bin/android-java-petstore.sh
|
||||
./bin/csharp-petstore.sh
|
||||
./bin/dynamic-html.sh
|
||||
./bin/html.sh
|
||||
./bin/html-petstore.sh
|
||||
./bin/jaxrs-petstore-server.sh
|
||||
./bin/java-petstore-filemap.sh
|
||||
./bin/java-petstore.sh
|
||||
./bin/php-petstore.sh
|
||||
./bin/python-petstore.sh
|
||||
./bin/ruby-petstore.sh
|
||||
./bin/objc-petstore.sh
|
||||
./bin/scala-petstore.sh
|
||||
./bin/spring-mvc-petstore-server.sh
|
||||
./bin/tizen-petstore.sh
|
||||
|
@ -26,6 +26,6 @@ fi
|
||||
|
||||
# if you've executed sbt assembly previously it will use that instead.
|
||||
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -o samples/client/petstore/android-java"
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/android-java -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -o samples/client/petstore/android-java"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
31
bin/csharp-petstore.sh
Executable file
31
bin/csharp-petstore.sh
Executable file
@ -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 csharp -o samples/client/petstore/csharp"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
@ -26,6 +26,6 @@ fi
|
||||
|
||||
# if you've executed sbt assembly previously it will use that instead.
|
||||
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l jaxrs -o samples/server/petstore/jaxrs"
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l jaxrs -o samples/server/petstore/jaxrs"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -26,6 +26,6 @@ fi
|
||||
|
||||
# if you've executed sbt assembly previously it will use that instead.
|
||||
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l objc -o samples/client/petstore/objc"
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/objc -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l objc -o samples/client/petstore/objc"
|
||||
|
||||
java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -26,6 +26,6 @@ fi
|
||||
|
||||
# if you've executed sbt assembly previously it will use that instead.
|
||||
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l php -o samples/client/petstore/php"
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/php -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l php -o samples/client/petstore/php"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -26,6 +26,6 @@ fi
|
||||
|
||||
# if you've executed sbt assembly previously it will use that instead.
|
||||
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l python -o samples/client/petstore/python"
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/python -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l python -o samples/client/petstore/python"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
31
bin/python3-petstore.sh
Executable file
31
bin/python3-petstore.sh
Executable file
@ -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/python3 -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l python3 -o samples/client/petstore/python3"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
@ -26,6 +26,6 @@ fi
|
||||
|
||||
# if you've executed sbt assembly previously it will use that instead.
|
||||
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l ruby -o samples/client/petstore/ruby"
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/ruby -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l ruby -o samples/client/petstore/ruby"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -26,6 +26,6 @@ fi
|
||||
|
||||
# if you've executed sbt assembly previously it will use that instead.
|
||||
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l async-scala -o samples/client/petstore/async-scala"
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/asyncscala -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l async-scala -o samples/client/petstore/async-scala"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -26,6 +26,6 @@ fi
|
||||
|
||||
# if you've executed sbt assembly previously it will use that instead.
|
||||
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l scala -o samples/client/petstore/scala"
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/scala -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l scala -o samples/client/petstore/scala"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -26,6 +26,6 @@ fi
|
||||
|
||||
# if you've executed sbt assembly previously it will use that instead.
|
||||
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l scalatra -o samples/server/petstore/scalatra"
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/scalatra -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l scalatra -o samples/server/petstore/scalatra"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
31
bin/spring-mvc-petstore-server.sh
Executable file
31
bin/spring-mvc-petstore-server.sh
Executable file
@ -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/JavaSpringMVC -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l spring-mvc -o samples/server/petstore/spring-mvc"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
@ -26,6 +26,6 @@ fi
|
||||
|
||||
# if you've executed sbt assembly previously it will use that instead.
|
||||
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l tizen -o samples/client/petstore/tizen"
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/tizen -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l tizen -o samples/client/petstore/tizen"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -3,7 +3,7 @@
|
||||
<parent>
|
||||
<groupId>com.wordnik</groupId>
|
||||
<artifactId>swagger-codegen-project</artifactId>
|
||||
<version>2.1.3-M1-SNAPSHOT</version>
|
||||
<version>2.1.1-M2-SNAPSHOT</version>
|
||||
<relativePath>../..</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
@ -15,6 +15,14 @@
|
||||
|
||||
<build>
|
||||
<finalName>swagger-codegen-cli</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<excludes>
|
||||
<exclude>logback.xml</exclude>
|
||||
</excludes>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
|
@ -1,7 +0,0 @@
|
||||
package com.wordnik.swagger.codegen;
|
||||
|
||||
public class Readme {
|
||||
public String getInfo() {
|
||||
return "See the documentation for swagger-codegen";
|
||||
}
|
||||
}
|
@ -10,6 +10,11 @@ import io.airlift.airline.Help;
|
||||
* User: lanwen
|
||||
* Date: 24.03.15
|
||||
* Time: 17:56
|
||||
*
|
||||
* Command line interface for swagger codegen
|
||||
* use `swagger-codegen-cli.jar help` for more info
|
||||
*
|
||||
* @since 2.1.3-M1
|
||||
*/
|
||||
public class SwaggerCodegen {
|
||||
|
||||
|
@ -31,28 +31,28 @@ public class Generate implements Runnable {
|
||||
public static final String TEMPLATE_DIR_PARAM = "templateDir";
|
||||
|
||||
@Option(name = {"-v", "--verbose"}, description = "verbose mode")
|
||||
public boolean verbose;
|
||||
private boolean verbose;
|
||||
|
||||
@Option(name = {"-l", "--lang"}, title = "language", required = true,
|
||||
description = "client language to generate (maybe class name in classpath, required)")
|
||||
public String lang;
|
||||
private String lang;
|
||||
|
||||
@Option(name = {"-o", "--output"}, title = "output directory",
|
||||
description = "where to write the generated files (current dir by default)")
|
||||
public String output = "";
|
||||
private String output = "";
|
||||
|
||||
@Option(name = {"-i", "--input-spec"}, title = "spec file", required = true,
|
||||
description = "location of the swagger spec, as URL or file (required)")
|
||||
public String spec;
|
||||
private String spec;
|
||||
|
||||
@Option(name = {"-t", "--template-dir"}, title = "template directory",
|
||||
description = "folder containing the template files")
|
||||
public String templateDir;
|
||||
private String templateDir;
|
||||
|
||||
@Option(name = {"-a", "--auth"}, title = "authorization",
|
||||
description = "adds authorization headers when fetching the swagger definitions remotely. " +
|
||||
"Pass in a URL-encoded string of name:header with a comma separating multiple values")
|
||||
public String auth;
|
||||
private String auth;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
@ -33,22 +33,22 @@ import static com.google.common.base.Joiner.on;
|
||||
"specify, and includes default templates to include.")
|
||||
public class Meta implements Runnable {
|
||||
|
||||
public static final Logger LOG = LoggerFactory.getLogger(Meta.class);
|
||||
private static final Logger LOG = LoggerFactory.getLogger(Meta.class);
|
||||
|
||||
public static final String TEMPLATE_DIR_CLASSPATH = "codegen";
|
||||
public static final String MUSTACHE_EXTENSION = ".mustache";
|
||||
private static final String TEMPLATE_DIR_CLASSPATH = "codegen";
|
||||
private static final String MUSTACHE_EXTENSION = ".mustache";
|
||||
|
||||
@Option(name = {"-o", "--output"}, title = "output directory",
|
||||
description = "where to write the generated files (current dir by default)")
|
||||
public String outputFolder = "";
|
||||
private String outputFolder = "";
|
||||
|
||||
@Option(name = {"-n", "--name"}, title = "name",
|
||||
description = "the human-readable name of the generator")
|
||||
public String name = "default";
|
||||
private String name = "default";
|
||||
|
||||
@Option(name = {"-p", "--package"}, title = "package",
|
||||
description = "the package to put the main class into (defaults to com.wordnik.swagger.codegen)")
|
||||
public String targetPackage = "com.wordnik.swagger.codegen";
|
||||
private String targetPackage = "com.wordnik.swagger.codegen";
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
@ -2,7 +2,7 @@
|
||||
<parent>
|
||||
<groupId>com.wordnik</groupId>
|
||||
<artifactId>swagger-codegen-project</artifactId>
|
||||
<version>2.1.3-M1-SNAPSHOT</version>
|
||||
<version>2.1.1-M2-SNAPSHOT</version>
|
||||
<relativePath>../..</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
@ -10,10 +10,18 @@
|
||||
<artifactId>swagger-codegen</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<name>swagger-codegen (core library)</name>
|
||||
<version>2.1.3-M1-SNAPSHOT</version>
|
||||
<version>2.1.1-M2-SNAPSHOT</version>
|
||||
<build>
|
||||
<sourceDirectory>src/main/java</sourceDirectory>
|
||||
<defaultGoal>install</defaultGoal>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<excludes>
|
||||
<exclude>logback.xml</exclude>
|
||||
</excludes>
|
||||
</resource>
|
||||
</resources>
|
||||
<extensions>
|
||||
<extension>
|
||||
<groupId>org.jvnet.wagon-svn</groupId>
|
||||
|
@ -12,6 +12,11 @@ import org.apache.commons.cli.*;
|
||||
import java.io.File;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @deprecated use instead {@link com.wordnik.swagger.codegen.DefaultGenerator}
|
||||
* or cli interface from https://github.com/swagger-api/swagger-codegen/pull/547
|
||||
*/
|
||||
@Deprecated
|
||||
public class Codegen extends DefaultGenerator {
|
||||
static Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>();
|
||||
static String configString;
|
||||
|
@ -22,6 +22,7 @@ public interface CodegenConfig {
|
||||
String toApiVarName(String name);
|
||||
String toModelName(String name);
|
||||
String toParamName(String name);
|
||||
String escapeText(String text);
|
||||
String escapeReservedWord(String name);
|
||||
String getTypeDeclaration(Property p);
|
||||
String getTypeDeclaration(String name);
|
||||
|
@ -65,7 +65,7 @@ public class DefaultCodegen {
|
||||
// override with any special text escaping logic
|
||||
public String escapeText(String input) {
|
||||
if(input != null) {
|
||||
String output = input.replaceAll("\n", " ");
|
||||
String output = input.replaceAll("\n", "\\\\n");
|
||||
output = output.replace("\"", "\\\"");
|
||||
return output;
|
||||
}
|
||||
@ -312,14 +312,34 @@ public class DefaultCodegen {
|
||||
return "null";
|
||||
else if(p instanceof DateTimeProperty)
|
||||
return "null";
|
||||
else if (p instanceof DoubleProperty)
|
||||
else if (p instanceof DoubleProperty) {
|
||||
DoubleProperty dp = (DoubleProperty) p;
|
||||
if(dp.getDefault() != null) {
|
||||
return dp.getDefault().toString();
|
||||
}
|
||||
return "null";
|
||||
else if (p instanceof FloatProperty)
|
||||
}
|
||||
else if (p instanceof FloatProperty) {
|
||||
FloatProperty dp = (FloatProperty) p;
|
||||
if(dp.getDefault() != null) {
|
||||
return dp.getDefault().toString();
|
||||
}
|
||||
return "null";
|
||||
else if (p instanceof IntegerProperty)
|
||||
}
|
||||
else if (p instanceof IntegerProperty) {
|
||||
IntegerProperty dp = (IntegerProperty) p;
|
||||
if(dp.getDefault() != null) {
|
||||
return dp.getDefault().toString();
|
||||
}
|
||||
return "null";
|
||||
else if (p instanceof LongProperty)
|
||||
}
|
||||
else if (p instanceof LongProperty) {
|
||||
LongProperty dp = (LongProperty) p;
|
||||
if(dp.getDefault() != null) {
|
||||
return dp.getDefault().toString();
|
||||
}
|
||||
return "null";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
MapProperty ap = (MapProperty) p;
|
||||
String inner = getSwaggerType(ap.getAdditionalProperties());
|
||||
@ -406,7 +426,7 @@ public class DefaultCodegen {
|
||||
m.name = escapeReservedWord(name);
|
||||
else
|
||||
m.name = name;
|
||||
m.description = model.getDescription();
|
||||
m.description = escapeText(model.getDescription());
|
||||
m.classname = toModelName(name);
|
||||
m.classVarName = toVarName(name);
|
||||
m.modelJson = Json.pretty(model);
|
||||
@ -465,7 +485,7 @@ public class DefaultCodegen {
|
||||
System.out.println("failed to process model " + name);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
cp.required = false;
|
||||
cp.required = null;
|
||||
if(impl.getRequired() != null) {
|
||||
for(String req : impl.getRequired()) {
|
||||
if(key.equals(req))
|
||||
@ -672,11 +692,11 @@ public class DefaultCodegen {
|
||||
for(String key: operation.getConsumes()) {
|
||||
Map<String, String> mediaType = new HashMap<String, String>();
|
||||
mediaType.put("mediaType", key);
|
||||
count += 1;
|
||||
if (count < operation.getConsumes().size())
|
||||
mediaType.put("hasMore", "true");
|
||||
else
|
||||
mediaType.put("hasMore", null);
|
||||
count += 1;
|
||||
c.add(mediaType);
|
||||
}
|
||||
op.consumes = c;
|
||||
@ -818,7 +838,8 @@ public class DefaultCodegen {
|
||||
// op.cookieParams = cookieParams;
|
||||
op.formParams = addHasMore(formParams);
|
||||
// legacy support
|
||||
op.nickname = operationId;
|
||||
op.nickname = op.operationId;
|
||||
|
||||
|
||||
if(op.allParams.size() > 0)
|
||||
op.hasParams = true;
|
||||
@ -878,8 +899,9 @@ public class DefaultCodegen {
|
||||
public CodegenParameter fromParameter(Parameter param, Set<String> imports) {
|
||||
CodegenParameter p = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER);
|
||||
p.baseName = param.getName();
|
||||
p.description = param.getDescription();
|
||||
p.required = param.getRequired();
|
||||
p.description = escapeText(param.getDescription());
|
||||
if(param.getRequired())
|
||||
p.required = param.getRequired();
|
||||
p.jsonSchema = Json.pretty(param);
|
||||
|
||||
if(param instanceof SerializableParameter) {
|
||||
@ -1099,6 +1121,21 @@ public class DefaultCodegen {
|
||||
m = p.matcher(word);
|
||||
}
|
||||
|
||||
// case out dots
|
||||
String[] parts = word.split("\\.");
|
||||
StringBuilder f = new StringBuilder();
|
||||
for(String z : parts) {
|
||||
if(z.length() > 0)
|
||||
f.append(Character.toUpperCase(z.charAt(0))).append(z.substring(1));
|
||||
}
|
||||
word = f.toString();
|
||||
|
||||
m = p.matcher(word);
|
||||
while (m.find()) {
|
||||
word = m.replaceFirst("" + Character.toUpperCase(m.group(1).charAt(0)) + m.group(1).substring(1)/*.toUpperCase()*/);
|
||||
m = p.matcher(word);
|
||||
}
|
||||
|
||||
// Uppercase the class name.
|
||||
p = Pattern.compile("(\\.?)(\\w)([^\\.]*)$");
|
||||
m = p.matcher(word);
|
||||
|
@ -11,12 +11,20 @@ import com.wordnik.swagger.models.Path;
|
||||
import com.wordnik.swagger.models.Swagger;
|
||||
import com.wordnik.swagger.models.auth.SecuritySchemeDefinition;
|
||||
import com.wordnik.swagger.util.Json;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.Reader;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
@ -60,7 +68,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
config.additionalProperties().put("appVersion", info.getVersion());
|
||||
}
|
||||
if (info.getDescription() != null) {
|
||||
config.additionalProperties().put("appDescription", info.getDescription());
|
||||
config.additionalProperties().put("appDescription",
|
||||
config.escapeText(info.getDescription()));
|
||||
}
|
||||
if (info.getContact() != null) {
|
||||
Contact contact = info.getContact();
|
||||
@ -84,12 +93,14 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
}
|
||||
|
||||
StringBuilder hostBuilder = new StringBuilder();
|
||||
String scheme;
|
||||
if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) {
|
||||
hostBuilder.append(swagger.getSchemes().get(0).toValue());
|
||||
hostBuilder.append("://");
|
||||
scheme = swagger.getSchemes().get(0).toValue();
|
||||
} else {
|
||||
hostBuilder.append("https://");
|
||||
scheme = "https";
|
||||
}
|
||||
hostBuilder.append(scheme);
|
||||
hostBuilder.append("://");
|
||||
if (swagger.getHost() != null) {
|
||||
hostBuilder.append(swagger.getHost());
|
||||
} else {
|
||||
@ -146,6 +157,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
for (String tag : paths.keySet()) {
|
||||
List<CodegenOperation> ops = paths.get(tag);
|
||||
Map<String, Object> operation = processOperations(config, tag, ops);
|
||||
|
||||
operation.put("basePath", basePath);
|
||||
operation.put("contextPath", contextPath);
|
||||
operation.put("baseName", tag);
|
||||
@ -199,6 +211,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
bundle.put("host", swagger.getHost());
|
||||
}
|
||||
bundle.put("basePath", basePath);
|
||||
bundle.put("scheme", scheme);
|
||||
bundle.put("contextPath", contextPath);
|
||||
bundle.put("apiInfo", apis);
|
||||
bundle.put("models", allModels);
|
||||
@ -245,10 +258,29 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
writeToFile(outputFilename, tmpl.execute(bundle));
|
||||
files.add(new File(outputFilename));
|
||||
} else {
|
||||
String template = readTemplate(config.templateDir() + File.separator + support.templateFile);
|
||||
FileUtils.writeStringToFile(new File(outputFilename), template);
|
||||
System.out.println("copying file to " + outputFilename);
|
||||
files.add(new File(outputFilename));
|
||||
InputStream in = null;
|
||||
|
||||
try {
|
||||
in = new FileInputStream(config.templateDir() + File.separator + support.templateFile);
|
||||
}
|
||||
catch (Exception e) {
|
||||
// continue
|
||||
}
|
||||
if(in == null) {
|
||||
in = this.getClass().getClassLoader().getResourceAsStream(config.templateDir() + File.separator + support.templateFile);
|
||||
}
|
||||
File outputFile = new File(outputFilename);
|
||||
OutputStream out = new FileOutputStream(outputFile, false);
|
||||
if(in != null && out != null)
|
||||
IOUtils.copy(in,out);
|
||||
else {
|
||||
if(in == null)
|
||||
System.out.println("can't open " + config.templateDir() + File.separator + support.templateFile + " for input");
|
||||
if(out == null)
|
||||
System.out.println("can't open " + outputFile + " for output");
|
||||
}
|
||||
|
||||
files.add(outputFile);
|
||||
}
|
||||
}
|
||||
|
||||
@ -336,10 +368,24 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
Map<String, Object> operations = new HashMap<String, Object>();
|
||||
Map<String, Object> objs = new HashMap<String, Object>();
|
||||
objs.put("classname", config.toApiName(tag));
|
||||
|
||||
// check for operationId uniqueness
|
||||
Set<String> opIds = new HashSet<String>();
|
||||
int counter = 0;
|
||||
for(CodegenOperation op : ops) {
|
||||
String opId = op.nickname;
|
||||
if(opIds.contains(opId)) {
|
||||
counter ++;
|
||||
op.nickname += "_" + counter;
|
||||
}
|
||||
opIds.add(opId);
|
||||
}
|
||||
objs.put("operation", ops);
|
||||
|
||||
operations.put("operations", objs);
|
||||
operations.put("package", config.apiPackage());
|
||||
|
||||
|
||||
Set<String> allImports = new LinkedHashSet<String>();
|
||||
for (CodegenOperation op : ops) {
|
||||
allImports.addAll(op.imports);
|
||||
|
@ -16,6 +16,11 @@ import java.io.File;
|
||||
import java.io.Reader;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @deprecated use instead {@link com.wordnik.swagger.codegen.DefaultGenerator}
|
||||
* or cli interface from https://github.com/swagger-api/swagger-codegen/pull/547
|
||||
*/
|
||||
@Deprecated
|
||||
public class MetaGenerator extends AbstractGenerator {
|
||||
static Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>();
|
||||
static String configString;
|
||||
|
@ -9,9 +9,10 @@ import java.io.File;
|
||||
public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.client";
|
||||
protected String groupId = "io.swagger";
|
||||
protected String artifactId = "swagger-client";
|
||||
protected String artifactId = "swagger-android-client";
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String sourceFolder = "src/main/java";
|
||||
protected String projectFolder = "src/main";
|
||||
protected String sourceFolder = projectFolder + "/java";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
@ -50,7 +51,8 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
additionalProperties.put("artifactId", artifactId);
|
||||
additionalProperties.put("artifactVersion", artifactVersion);
|
||||
|
||||
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
|
||||
supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle"));
|
||||
supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml"));
|
||||
supportingFiles.add(new SupportingFile("apiInvoker.mustache",
|
||||
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.java"));
|
||||
supportingFiles.add(new SupportingFile("httpPatch.mustache",
|
||||
@ -162,5 +164,14 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
return toModelName(name);
|
||||
}
|
||||
|
||||
@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, true);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -9,7 +9,7 @@ import java.io.File;
|
||||
public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.client";
|
||||
protected String groupId = "com.wordnik";
|
||||
protected String artifactId = "swagger-client";
|
||||
protected String artifactId = "swagger-async-scala-client";
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String sourceFolder = "src/main/scala";
|
||||
protected String clientName = "SwaggerClient";
|
||||
|
@ -0,0 +1,186 @@
|
||||
package com.wordnik.swagger.codegen.languages;
|
||||
|
||||
import com.wordnik.swagger.codegen.*;
|
||||
import com.wordnik.swagger.models.properties.*;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
|
||||
public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.client";
|
||||
protected String groupId = "io.swagger";
|
||||
protected String artifactId = "swagger-csharp-client";
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String sourceFolder = "src/main/csharp";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "csharp";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a CSharp client library.";
|
||||
}
|
||||
|
||||
public CSharpClientCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code/csharp";
|
||||
modelTemplateFiles.put("model.mustache", ".cs");
|
||||
apiTemplateFiles.put("api.mustache", ".cs");
|
||||
templateDir = "csharp";
|
||||
apiPackage = "io.swagger.Api";
|
||||
modelPackage = "io.swagger.Model";
|
||||
|
||||
reservedWords = new HashSet<String> (
|
||||
Arrays.asList(
|
||||
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while")
|
||||
);
|
||||
|
||||
additionalProperties.put("invokerPackage", invokerPackage);
|
||||
|
||||
supportingFiles.add(new SupportingFile("apiInvoker.mustache",
|
||||
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.cs"));
|
||||
supportingFiles.add(new SupportingFile("apiException.mustache",
|
||||
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.cs"));
|
||||
supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll"));
|
||||
supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat"));
|
||||
|
||||
languageSpecificPrimitives = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"string",
|
||||
"bool?",
|
||||
"double?",
|
||||
"int?",
|
||||
"long?",
|
||||
"float?",
|
||||
"byte[]",
|
||||
"List",
|
||||
"Dictionary",
|
||||
"DateTime",
|
||||
"String",
|
||||
"Boolean",
|
||||
"Double",
|
||||
"Integer",
|
||||
"Long",
|
||||
"Float",
|
||||
"Object")
|
||||
);
|
||||
instantiationTypes.put("array", "List");
|
||||
instantiationTypes.put("map", "Dictionary");
|
||||
|
||||
typeMapping = new HashMap<String, String>();
|
||||
typeMapping.put("string", "string");
|
||||
typeMapping.put("boolean", "bool?");
|
||||
typeMapping.put("integer", "int?");
|
||||
typeMapping.put("float", "float?");
|
||||
typeMapping.put("long", "long?");
|
||||
typeMapping.put("double", "double?");
|
||||
typeMapping.put("number", "double?");
|
||||
typeMapping.put("Date", "DateTime");
|
||||
typeMapping.put("file", "byte[]");
|
||||
typeMapping.put("array", "List");
|
||||
typeMapping.put("map", "Dictionary");
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String apiFileFolder() {
|
||||
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
public String modelFileFolder() {
|
||||
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toVarName(String name) {
|
||||
// replace - with _ e.g. created-at => created_at
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// if it's all uppper case, do nothing
|
||||
if (name.matches("^[A-Z_]*$"))
|
||||
return name;
|
||||
|
||||
// camelize 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 getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
return getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">";
|
||||
}
|
||||
return super.getTypeDeclaration(p);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if(languageSpecificPrimitives.contains(type))
|
||||
return type;
|
||||
}
|
||||
else
|
||||
type = swaggerType;
|
||||
return toModelName(type);
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
}
|
@ -9,7 +9,7 @@ import java.io.File;
|
||||
public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.client";
|
||||
protected String groupId = "io.swagger";
|
||||
protected String artifactId = "swagger-client";
|
||||
protected String artifactId = "swagger-java-client";
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String sourceFolder = "src/main/java";
|
||||
|
||||
@ -160,4 +160,15 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
type = swaggerType;
|
||||
return toModelName(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, true);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -12,7 +12,7 @@ import java.io.File;
|
||||
public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.api";
|
||||
protected String groupId = "io.swagger";
|
||||
protected String artifactId = "swagger-server";
|
||||
protected String artifactId = "swagger-jaxrs-server";
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String sourceFolder = "src/main/java";
|
||||
protected String title = "Swagger Server";
|
||||
|
@ -48,6 +48,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
"NSObject",
|
||||
"NSArray",
|
||||
"NSNumber",
|
||||
"NSDate",
|
||||
"NSDictionary",
|
||||
"NSMutableArray",
|
||||
"NSMutableDictionary")
|
||||
@ -57,6 +58,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
"NSNumber",
|
||||
"NSString",
|
||||
"NSObject",
|
||||
"NSDate",
|
||||
"bool")
|
||||
);
|
||||
|
||||
@ -70,9 +72,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
typeMapping = new HashMap<String, String>();
|
||||
typeMapping.put("enum", "NSString");
|
||||
typeMapping.put("Date", "SWGDate");
|
||||
typeMapping.put("DateTime", "SWGDate");
|
||||
// typeMapping.put("Date", "SWGDate");
|
||||
typeMapping.put("Date", "NSDate");
|
||||
typeMapping.put("DateTime", "NSDate");
|
||||
typeMapping.put("boolean", "NSNumber");
|
||||
typeMapping.put("string", "NSString");
|
||||
typeMapping.put("integer", "NSNumber");
|
||||
@ -87,13 +88,13 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
typeMapping.put("object", "NSObject");
|
||||
|
||||
importMapping = new HashMap<String, String> ();
|
||||
importMapping.put("Date", "SWGDate");
|
||||
|
||||
foundationClasses = new HashSet<String> (
|
||||
Arrays.asList(
|
||||
"NSNumber",
|
||||
"NSObject",
|
||||
"NSString",
|
||||
"NSDate",
|
||||
"NSDictionary")
|
||||
);
|
||||
|
||||
@ -102,6 +103,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
supportingFiles.add(new SupportingFile("SWGObject.h", sourceFolder, "SWGObject.h"));
|
||||
supportingFiles.add(new SupportingFile("SWGObject.m", sourceFolder, "SWGObject.m"));
|
||||
supportingFiles.add(new SupportingFile("SWGQueryParamCollection.h", sourceFolder, "SWGQueryParamCollection.h"));
|
||||
supportingFiles.add(new SupportingFile("SWGQueryParamCollection.m", sourceFolder, "SWGQueryParamCollection.m"));
|
||||
supportingFiles.add(new SupportingFile("SWGApiClient.h", sourceFolder, "SWGApiClient.h"));
|
||||
supportingFiles.add(new SupportingFile("SWGApiClient.m", sourceFolder, "SWGApiClient.m"));
|
||||
supportingFiles.add(new SupportingFile("SWGFile.h", sourceFolder, "SWGFile.h"));
|
||||
@ -151,11 +154,45 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
String swaggerType = getSwaggerType(p);
|
||||
if(languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType))
|
||||
return toModelName(swaggerType);
|
||||
else
|
||||
return swaggerType + "*";
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
String innerType = getSwaggerType(inner);
|
||||
|
||||
// In this codition, type of property p is array of primitive,
|
||||
// return container type with pointer, e.g. `NSArray*'
|
||||
if (languageSpecificPrimitives.contains(innerType))
|
||||
return getSwaggerType(p) + "*";
|
||||
|
||||
// In this codition, type of property p is array of model,
|
||||
// return container type combine inner type with pointer, e.g. `NSArray<SWGTag>*'
|
||||
String innerTypeDeclaration = getTypeDeclaration(inner);
|
||||
|
||||
if (innerTypeDeclaration.endsWith("*"))
|
||||
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
|
||||
|
||||
return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*";
|
||||
}
|
||||
else {
|
||||
String swaggerType = getSwaggerType(p);
|
||||
|
||||
// In this codition, type of p is objective-c primitive type, e.g. `NSSNumber',
|
||||
// return type of p with pointer, e.g. `NSNumber*'
|
||||
if (languageSpecificPrimitives.contains(swaggerType) &&
|
||||
foundationClasses.contains(swaggerType)) {
|
||||
return swaggerType + "*";
|
||||
}
|
||||
// In this codition, type of p is c primitive type, e.g. `bool',
|
||||
// return type of p, e.g. `bool'
|
||||
else if (languageSpecificPrimitives.contains(swaggerType)) {
|
||||
return swaggerType;
|
||||
}
|
||||
// In this codition, type of p is objective-c object type, e.g. `SWGPet',
|
||||
// return type of p with pointer, e.g. `'
|
||||
else {
|
||||
return swaggerType + "*";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -229,8 +266,24 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
else
|
||||
return paramName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toParamName(String name) {
|
||||
// should be the same as variable name
|
||||
return toVarName(name);
|
||||
}
|
||||
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
}
|
||||
|
||||
@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, true);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -27,7 +27,13 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
public PhpClientCodegen() {
|
||||
super();
|
||||
modelPackage = "models";
|
||||
|
||||
invokerPackage = camelize("SwaggerClient");
|
||||
|
||||
String packagePath = invokerPackage + "-php";
|
||||
|
||||
modelPackage = packagePath + "/lib/models";
|
||||
apiPackage = packagePath + "/lib";
|
||||
outputFolder = "generated-code/php";
|
||||
modelTemplateFiles.put("model.mustache", ".php");
|
||||
apiTemplateFiles.put("api.mustache", ".php");
|
||||
@ -59,7 +65,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
typeMapping.put("List", "array");
|
||||
typeMapping.put("map", "map");
|
||||
|
||||
supportingFiles.add(new SupportingFile("Swagger.mustache", "", "Swagger.php"));
|
||||
supportingFiles.add(new SupportingFile("composer.mustache", packagePath, "composer.json"));
|
||||
supportingFiles.add(new SupportingFile("APIClient.mustache", packagePath + "/lib", "APIClient.php"));
|
||||
supportingFiles.add(new SupportingFile("APIClientException.mustache", packagePath + "/lib", "APIClientException.php"));
|
||||
supportingFiles.add(new SupportingFile("require.mustache", packagePath, invokerPackage + ".php"));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -0,0 +1,198 @@
|
||||
package com.wordnik.swagger.codegen.languages;
|
||||
|
||||
import com.wordnik.swagger.codegen.*;
|
||||
import com.wordnik.swagger.models.properties.*;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.*;
|
||||
|
||||
public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
String module = "client";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "python3";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Python3 client library.";
|
||||
}
|
||||
|
||||
public Python3ClientCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code/python3";
|
||||
modelTemplateFiles.put("model.mustache", ".py");
|
||||
apiTemplateFiles.put("api.mustache", ".py");
|
||||
templateDir = "python3";
|
||||
|
||||
apiPackage = module;
|
||||
modelPackage = module + ".models";
|
||||
|
||||
languageSpecificPrimitives.clear();
|
||||
languageSpecificPrimitives.add("int");
|
||||
languageSpecificPrimitives.add("float");
|
||||
//languageSpecificPrimitives.add("long");
|
||||
languageSpecificPrimitives.add("list");
|
||||
languageSpecificPrimitives.add("bool");
|
||||
languageSpecificPrimitives.add("str");
|
||||
languageSpecificPrimitives.add("datetime");
|
||||
|
||||
typeMapping.clear();
|
||||
typeMapping.put("integer", "int");
|
||||
typeMapping.put("float", "float");
|
||||
typeMapping.put("long", "int");
|
||||
typeMapping.put("double", "float");
|
||||
typeMapping.put("array", "list");
|
||||
typeMapping.put("map", "map");
|
||||
typeMapping.put("boolean", "bool");
|
||||
typeMapping.put("string", "str");
|
||||
typeMapping.put("date", "datetime");
|
||||
|
||||
// from https://docs.python.org/release/2.5.4/ref/keywords.html
|
||||
reservedWords = new HashSet<String> (
|
||||
Arrays.asList(
|
||||
"and", "del", "from", "not", "while", "as", "elif", "global", "or", "with",
|
||||
"assert", "else", "if", "pass", "yield", "break", "except", "import",
|
||||
"print", "class", "exec", "in", "raise", "continue", "finally", "is",
|
||||
"return", "def", "for", "lambda", "try"));
|
||||
|
||||
//supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
|
||||
supportingFiles.add(new SupportingFile("swagger.mustache", module, "swagger.py"));
|
||||
supportingFiles.add(new SupportingFile("__init__.mustache", module, "__init__.py"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String apiFileFolder() {
|
||||
return outputFolder + "/" + apiPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
public String modelFileFolder() {
|
||||
return outputFolder + "/" + modelPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
return getSwaggerType(p) + "(String, " + getTypeDeclaration(inner) + ")";
|
||||
}
|
||||
return super.getTypeDeclaration(p);
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
|
||||
public String toDefaultValue(Property p) {
|
||||
// TODO: Support Python def value
|
||||
return "null";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toVarName(String name) {
|
||||
// replace - with _ e.g. created-at => created_at
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// if it's all uppper case, convert to lower case
|
||||
if (name.matches("^[A-Z_]*$"))
|
||||
name = name.toLowerCase();
|
||||
|
||||
// camelize (lower first character) the variable name
|
||||
// petId => pet_id
|
||||
name = underscore(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) {
|
||||
// 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");
|
||||
|
||||
// underscore the model file name
|
||||
// PhoneNumber.rb => phone_number.rb
|
||||
return underscore(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiFilename(String name) {
|
||||
// replace - with _ e.g. created-at => created_at
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// e.g. PhoneNumberApi.rb => phone_number_api.rb
|
||||
return underscore(name) + "_api";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiName(String name) {
|
||||
if(name.length() == 0)
|
||||
return "DefaultApi";
|
||||
// e.g. phone_number_api => PhoneNumberApi
|
||||
return camelize(name) + "Api";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiVarName(String name) {
|
||||
if(name.length() == 0)
|
||||
return "default_api";
|
||||
return underscore(name) + "_api";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toOperationId(String operationId) {
|
||||
// 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 underscore(operationId);
|
||||
}
|
||||
|
||||
}
|
@ -4,9 +4,12 @@ import com.wordnik.swagger.codegen.*;
|
||||
import com.wordnik.swagger.models.properties.*;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.*;
|
||||
|
||||
public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
String module = "client";
|
||||
protected String module = "SwaggerPetstore";
|
||||
protected String invokerPackage;
|
||||
protected String eggPackage;
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
@ -22,14 +25,18 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
|
||||
public PythonClientCodegen() {
|
||||
super();
|
||||
|
||||
eggPackage = module + "-python";
|
||||
invokerPackage = eggPackage + "/" + module;
|
||||
|
||||
outputFolder = "generated-code/python";
|
||||
modelTemplateFiles.put("model.mustache", ".py");
|
||||
apiTemplateFiles.put("api.mustache", ".py");
|
||||
templateDir = "python";
|
||||
|
||||
apiPackage = module;
|
||||
modelPackage = module + ".models";
|
||||
|
||||
|
||||
apiPackage = invokerPackage;
|
||||
modelPackage = invokerPackage + ".models";
|
||||
|
||||
languageSpecificPrimitives.clear();
|
||||
languageSpecificPrimitives.add("int");
|
||||
languageSpecificPrimitives.add("float");
|
||||
@ -50,11 +57,21 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
typeMapping.put("string", "str");
|
||||
typeMapping.put("date", "datetime");
|
||||
|
||||
|
||||
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
|
||||
supportingFiles.add(new SupportingFile("swagger.mustache", module, "swagger.py"));
|
||||
supportingFiles.add(new SupportingFile("__init__.mustache", module, "__init__.py"));
|
||||
supportingFiles.add(new SupportingFile("__init__.mustache", modelPackage.replace('.', File.separatorChar), "__init__.py"));
|
||||
// from https://docs.python.org/release/2.5.4/ref/keywords.html
|
||||
reservedWords = new HashSet<String> (
|
||||
Arrays.asList(
|
||||
"and", "del", "from", "not", "while", "as", "elif", "global", "or", "with",
|
||||
"assert", "else", "if", "pass", "yield", "break", "except", "import",
|
||||
"print", "class", "exec", "in", "raise", "continue", "finally", "is",
|
||||
"return", "def", "for", "lambda", "try"));
|
||||
|
||||
additionalProperties.put("module", module);
|
||||
|
||||
supportingFiles.add(new SupportingFile("README.mustache", eggPackage, "README.md"));
|
||||
supportingFiles.add(new SupportingFile("setup.mustache", eggPackage, "setup.py"));
|
||||
supportingFiles.add(new SupportingFile("swagger.mustache", invokerPackage, "swagger.py"));
|
||||
supportingFiles.add(new SupportingFile("__init__package.mustache", invokerPackage, "__init__.py"));
|
||||
supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage.replace('.', File.separatorChar), "__init__.py"));
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -105,5 +122,87 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
public String toDefaultValue(Property p) {
|
||||
// TODO: Support Python def value
|
||||
return "null";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toVarName(String name) {
|
||||
// replace - with _ e.g. created-at => created_at
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// if it's all uppper case, convert to lower case
|
||||
if (name.matches("^[A-Z_]*$"))
|
||||
name = name.toLowerCase();
|
||||
|
||||
// camelize (lower first character) the variable name
|
||||
// petId => pet_id
|
||||
name = underscore(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) {
|
||||
// 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");
|
||||
|
||||
// underscore the model file name
|
||||
// PhoneNumber.rb => phone_number.rb
|
||||
return underscore(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiFilename(String name) {
|
||||
// replace - with _ e.g. created-at => created_at
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// e.g. PhoneNumberApi.rb => phone_number_api.rb
|
||||
return underscore(name) + "_api";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiName(String name) {
|
||||
if(name.length() == 0)
|
||||
return "DefaultApi";
|
||||
// e.g. phone_number_api => PhoneNumberApi
|
||||
return camelize(name) + "Api";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiVarName(String name) {
|
||||
if(name.length() == 0)
|
||||
return "default_api";
|
||||
return underscore(name) + "_api";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toOperationId(String operationId) {
|
||||
// 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 underscore(operationId);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -64,6 +64,8 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
typeMapping.put("List", "array");
|
||||
typeMapping.put("map", "map");
|
||||
|
||||
supportingFiles.add(new SupportingFile("swagger-client.gemspec.mustache", "", "swagger-client.gemspec"));
|
||||
supportingFiles.add(new SupportingFile("swagger-client.mustache", "", "lib/swagger-client.rb"));
|
||||
supportingFiles.add(new SupportingFile("swagger.mustache", "", "lib/swagger.rb"));
|
||||
supportingFiles.add(new SupportingFile("monkey.mustache", "", "lib/monkey.rb"));
|
||||
supportingFiles.add(new SupportingFile("swagger/request.mustache", "", "lib/swagger/request.rb"));
|
||||
@ -187,4 +189,14 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
return camelize(name) + "Api";
|
||||
}
|
||||
|
||||
@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 underscore(operationId);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -9,7 +9,7 @@ import java.io.File;
|
||||
public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.client";
|
||||
protected String groupId = "com.wordnik";
|
||||
protected String artifactId = "swagger-client";
|
||||
protected String artifactId = "swagger-scala-client";
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String sourceFolder = "src/main/scala";
|
||||
protected String authScheme = "";
|
||||
@ -189,4 +189,15 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
else
|
||||
return "null";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@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, true);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -9,13 +9,13 @@ import com.wordnik.swagger.models.properties.*;
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
|
||||
public class SpringdoxServerCodegen extends JavaClientCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "com.concur.service.api";
|
||||
protected String groupId = "com.concur.service";
|
||||
protected String artifactId = "swagger-server";
|
||||
public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.api";
|
||||
protected String groupId = "io.swagger";
|
||||
protected String artifactId = "swagger-spring-mvc-server";
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String sourceFolder = "src/main/java";
|
||||
protected String title = "Concur Server";
|
||||
protected String title = "Petstore Server";
|
||||
|
||||
protected String configPackage = "";
|
||||
|
||||
@ -24,22 +24,22 @@ public class SpringdoxServerCodegen extends JavaClientCodegen implements Codegen
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "springdox";
|
||||
return "spring-mvc";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Java SpringDox Server application.";
|
||||
return "Generates a Java Spring-MVC Server application using the SpringFox integration.";
|
||||
}
|
||||
|
||||
public SpringdoxServerCodegen() {
|
||||
public SpringMVCServerCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code/javaSpringdox";
|
||||
outputFolder = "generated-code/javaSpringMVC";
|
||||
modelTemplateFiles.put("model.mustache", ".java");
|
||||
apiTemplateFiles.put("api.mustache", ".java");
|
||||
templateDir = "JavaSpringdox";
|
||||
apiPackage = "com.concur.service.api";
|
||||
modelPackage = "com.concur.service.model";
|
||||
configPackage = "com.concur.service.configuration";
|
||||
templateDir = "JavaSpringMVC";
|
||||
apiPackage = "io.swagger.api";
|
||||
modelPackage = "io.swagger.model";
|
||||
configPackage = "io.swagger.configuration";
|
||||
|
||||
|
||||
additionalProperties.put("invokerPackage", invokerPackage);
|
||||
@ -47,32 +47,41 @@ public class SpringdoxServerCodegen extends JavaClientCodegen implements Codegen
|
||||
additionalProperties.put("artifactId", artifactId);
|
||||
additionalProperties.put("artifactVersion", artifactVersion);
|
||||
additionalProperties.put("title", title);
|
||||
additionalProperties.put("apiPackage", apiPackage);
|
||||
additionalProperties.put("configPackage", configPackage);
|
||||
|
||||
supportingFiles.clear();
|
||||
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
|
||||
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
|
||||
supportingFiles.add(new SupportingFile("ApiException.mustache",
|
||||
supportingFiles.add(new SupportingFile("apiException.mustache",
|
||||
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
|
||||
supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache",
|
||||
supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
|
||||
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
|
||||
supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache",
|
||||
supportingFiles.add(new SupportingFile("apiResponseMessage.mustache",
|
||||
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
|
||||
supportingFiles.add(new SupportingFile("NotFoundException.mustache",
|
||||
supportingFiles.add(new SupportingFile("notFoundException.mustache",
|
||||
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
|
||||
|
||||
|
||||
supportingFiles.add(new SupportingFile("SwaggerConfig.mustache",
|
||||
supportingFiles.add(new SupportingFile("swaggerConfig.mustache",
|
||||
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerConfig.java"));
|
||||
supportingFiles.add(new SupportingFile("webApplication.mustache",
|
||||
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebApplication.java"));
|
||||
supportingFiles.add(new SupportingFile("webMvcConfiguration.mustache",
|
||||
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebMvcConfiguration.java"));
|
||||
supportingFiles.add(new SupportingFile("swaggerUiConfiguration.mustache",
|
||||
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerUiConfiguration.java"));
|
||||
supportingFiles.add(new SupportingFile("swagger.properties",
|
||||
("src.main.resources").replace(".", java.io.File.separator), "swagger.properties"));
|
||||
|
||||
languageSpecificPrimitives = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"String",
|
||||
"boolean",
|
||||
"Boolean",
|
||||
"Double",
|
||||
"Integer",
|
||||
"Long",
|
||||
"Float")
|
||||
Arrays.asList(
|
||||
"String",
|
||||
"boolean",
|
||||
"Boolean",
|
||||
"Double",
|
||||
"Integer",
|
||||
"Long",
|
||||
"Float")
|
||||
);
|
||||
}
|
||||
|
@ -1,6 +1,7 @@
|
||||
package com.wordnik.swagger.codegen.languages;
|
||||
|
||||
import com.wordnik.swagger.codegen.*;
|
||||
import com.wordnik.swagger.models.Operation;
|
||||
import com.wordnik.swagger.models.properties.*;
|
||||
import com.wordnik.swagger.util.Json;
|
||||
|
||||
@ -8,6 +9,7 @@ import java.util.*;
|
||||
import java.io.File;
|
||||
|
||||
public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
private static final String ALL_OPERATIONS = "";
|
||||
protected String invokerPackage = "com.wordnik.client";
|
||||
protected String groupId = "com.wordnik";
|
||||
protected String artifactId = "swagger-client";
|
||||
@ -33,12 +35,6 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
|
||||
|
||||
defaultIncludes = new HashSet<String>();
|
||||
|
||||
String partner = "our Partner";
|
||||
|
||||
if(System.getProperty("partner") != null)
|
||||
partner = System.getProperty("partner");
|
||||
|
||||
additionalProperties.put("partner", partner);
|
||||
additionalProperties.put("appName", "Swagger Sample");
|
||||
additionalProperties.put("appDescription", "A sample swagger server");
|
||||
additionalProperties.put("infoUrl", "https://helloreverb.com");
|
||||
@ -82,4 +78,20 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
|
||||
}
|
||||
return objs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
|
||||
List<CodegenOperation> opList = operations.get(ALL_OPERATIONS);
|
||||
if(opList == null) {
|
||||
opList = new ArrayList<CodegenOperation>();
|
||||
operations.put(ALL_OPERATIONS, opList);
|
||||
}
|
||||
for (CodegenOperation addedOperation: opList){
|
||||
if (addedOperation.operationId.equals(co.operationId) && addedOperation.path.equals(co.path) && addedOperation.httpMethod.equals(co.httpMethod)) {
|
||||
addedOperation.tags.addAll(co.tags);
|
||||
return;
|
||||
}
|
||||
}
|
||||
opList.add(co);
|
||||
}
|
||||
}
|
@ -244,4 +244,15 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
}
|
||||
|
||||
@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");
|
||||
|
||||
// add_pet_by_id => addPetById
|
||||
return camelize(operationId, true);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -11,6 +11,7 @@ import java.util.*;
|
||||
{{/imports}}
|
||||
|
||||
import com.sun.jersey.multipart.FormDataMultiPart;
|
||||
import com.sun.jersey.multipart.file.FileDataBodyPart;
|
||||
|
||||
import javax.ws.rs.core.MediaType;
|
||||
|
||||
@ -36,10 +37,12 @@ public class {{classname}} {
|
||||
}
|
||||
|
||||
{{#operation}}
|
||||
{{#errorList}} //error info- code: {{code}} reason: "{{reason}}" model: {{#responseModel}}{{responseModel}}
|
||||
{{/responseModel}}{{^responseModel}}<none>
|
||||
{{/responseModel}}
|
||||
{{/errorList}}
|
||||
/**
|
||||
* {{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 ApiException {
|
||||
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
|
||||
{{#requiredParamCount}}
|
||||
@ -77,7 +80,8 @@ public class {{classname}} {
|
||||
mp.field("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), MediaType.MULTIPART_FORM_DATA_TYPE);
|
||||
{{/notFile}}{{#isFile}}
|
||||
hasFields = true;
|
||||
mp.field("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE);
|
||||
mp.field("{{baseName}}", file.getName());
|
||||
mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE));
|
||||
{{/isFile}}{{/formParams}}
|
||||
if(hasFields)
|
||||
postBody = mp;
|
||||
@ -96,12 +100,7 @@ public class {{classname}} {
|
||||
return {{#returnType}}null{{/returnType}};
|
||||
}
|
||||
} catch (ApiException ex) {
|
||||
if(ex.getCode() == 404) {
|
||||
return {{#returnType}} null{{/returnType}};
|
||||
}
|
||||
else {
|
||||
throw ex;
|
||||
}
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
{{/operation}}
|
||||
|
@ -16,6 +16,7 @@ import com.sun.jersey.multipart.FormDataMultiPart;
|
||||
import javax.ws.rs.core.Response.Status.Family;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@ -40,7 +41,7 @@ public class ApiInvoker {
|
||||
* ISO 8601 date time format.
|
||||
* @see https://en.wikipedia.org/wiki/ISO_8601
|
||||
*/
|
||||
public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
|
||||
public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
|
||||
|
||||
/**
|
||||
* ISO 8601 date format.
|
||||
@ -52,6 +53,13 @@ public class ApiInvoker {
|
||||
// Use UTC as the default time zone.
|
||||
DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
|
||||
// Set default User-Agent.
|
||||
setUserAgent("Java-Swagger");
|
||||
}
|
||||
|
||||
public static void setUserAgent(String userAgent) {
|
||||
INSTANCE.addDefaultHeader("User-Agent", userAgent);
|
||||
}
|
||||
|
||||
public static Date parseDateTime(String str) {
|
||||
@ -83,11 +91,19 @@ public class ApiInvoker {
|
||||
return "";
|
||||
} else if (param instanceof Date) {
|
||||
return formatDateTime((Date) param);
|
||||
} else if (param instanceof Collection) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
for(Object o : (Collection)param) {
|
||||
if(b.length() > 0) {
|
||||
b.append(",");
|
||||
}
|
||||
b.append(String.valueOf(o));
|
||||
}
|
||||
return b.toString();
|
||||
} else {
|
||||
return String.valueOf(param);
|
||||
}
|
||||
}
|
||||
|
||||
public void enableDebug() {
|
||||
isDebug = true;
|
||||
}
|
||||
@ -217,7 +233,7 @@ public class ApiInvoker {
|
||||
}
|
||||
else if ("DELETE".equals(method)) {
|
||||
if(body == null)
|
||||
response = builder.delete(ClientResponse.class, serialize(body));
|
||||
response = builder.delete(ClientResponse.class);
|
||||
else
|
||||
response = builder.type(contentType).delete(ClientResponse.class, serialize(body));
|
||||
}
|
||||
@ -228,12 +244,26 @@ public class ApiInvoker {
|
||||
return null;
|
||||
}
|
||||
else if(response.getClientResponseStatus().getFamily() == Family.SUCCESSFUL) {
|
||||
return (String) response.getEntity(String.class);
|
||||
if(response.hasEntity()) {
|
||||
return (String) response.getEntity(String.class);
|
||||
}
|
||||
else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
else {
|
||||
String message = "error";
|
||||
if(response.hasEntity()) {
|
||||
try{
|
||||
message = String.valueOf(response.getEntity(String.class));
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
// e.printStackTrace();
|
||||
}
|
||||
}
|
||||
throw new ApiException(
|
||||
response.getClientResponseStatus().getStatusCode(),
|
||||
response.getEntity(String.class));
|
||||
message);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -26,7 +26,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
|
||||
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
|
||||
* maximum: {{maximum}}{{/maximum}}
|
||||
**/
|
||||
@ApiModelProperty(required = {{required}}, value = "{{{description}}}")
|
||||
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
|
||||
@JsonProperty("{{baseName}}")
|
||||
public {{{datatypeWithEnum}}} {{getter}}() {
|
||||
return {{name}};
|
||||
|
@ -157,11 +157,10 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<swagger-annotations-version>1.5.0-M1</swagger-annotations-version>
|
||||
<jersey-version>1.7</jersey-version>
|
||||
<jackson-version>2.1.4</jackson-version>
|
||||
<swagger-annotations-version>1.5.3-M1</swagger-annotations-version>
|
||||
<jersey-version>1.18</jersey-version>
|
||||
<jackson-version>2.4.2</jackson-version>
|
||||
<jodatime-version>2.3</jodatime-version>
|
||||
<junit-version>4.8.1</junit-version>
|
||||
<maven-plugin-version>1.0.0</maven-plugin-version>
|
||||
<junit-version>4.8.1</junit-version>
|
||||
</properties>
|
||||
|
@ -1 +1 @@
|
||||
{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@HeaderParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}}
|
||||
{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@HeaderParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}}
|
@ -26,7 +26,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
|
||||
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
|
||||
* maximum: {{maximum}}{{/maximum}}
|
||||
**/
|
||||
@ApiModelProperty(required = {{required}}, value = "{{{description}}}")
|
||||
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
|
||||
@JsonProperty("{{name}}")
|
||||
public {{{datatypeWithEnum}}} {{getter}}() {
|
||||
return {{name}};
|
||||
|
@ -1 +1 @@
|
||||
{{#isPathParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/isPathParam}}
|
||||
{{#isPathParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}}
|
@ -26,31 +26,27 @@
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.mortbay.jetty</groupId>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-maven-plugin</artifactId>
|
||||
<version>${jetty-version}</version>
|
||||
<configuration>
|
||||
<webAppConfig>
|
||||
<contextPath>{{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}}</contextPath>
|
||||
</webAppConfig>
|
||||
<webApp>
|
||||
<contextPath>/</contextPath>
|
||||
</webApp>
|
||||
<webAppSourceDirectory>target/${project.artifactId}-${project.version}</webAppSourceDirectory>
|
||||
<webDefaultXml>${project.basedir}/conf/jetty/webdefault.xml</webDefaultXml>
|
||||
<stopPort>8079</stopPort>
|
||||
<stopKey>stopit</stopKey>
|
||||
<connectors>
|
||||
<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
|
||||
<port>8002</port>
|
||||
<maxIdleTime>60000</maxIdleTime>
|
||||
<confidentialPort>8443</confidentialPort>
|
||||
</connector>
|
||||
</connectors>
|
||||
<httpConnector>
|
||||
<port>8080</port>
|
||||
<idleTimeout>60000</idleTimeout>
|
||||
</httpConnector>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>start-jetty</id>
|
||||
<phase>pre-integration-test</phase>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
<goal>start</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<scanIntervalSeconds>0</scanIntervalSeconds>
|
||||
@ -133,8 +129,8 @@
|
||||
</repository>
|
||||
</repositories>
|
||||
<properties>
|
||||
<swagger-core-version>1.5.3-M1-SNAPSHOT</swagger-core-version>
|
||||
<jetty-version>8.1.11.v20130520</jetty-version>
|
||||
<swagger-core-version>2.1.1-M2-SNAPSHOT</swagger-core-version>
|
||||
<jetty-version>9.2.9.v20150224</jetty-version>
|
||||
<jersey-version>1.13</jersey-version>
|
||||
<slf4j-version>1.6.3</slf4j-version>
|
||||
<scala-test-version>1.6.1</scala-test-version>
|
||||
|
@ -1 +1 @@
|
||||
{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @QueryParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}}
|
||||
{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @QueryParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}}
|
@ -34,7 +34,7 @@
|
||||
</init-param>
|
||||
<init-param>
|
||||
<param-name>swagger.api.basepath</param-name>
|
||||
<param-value>http://localhost:8002</param-value>
|
||||
<param-value>http://localhost:8080</param-value>
|
||||
</init-param>
|
||||
<load-on-startup>2</load-on-startup>
|
||||
</servlet>
|
||||
|
@ -0,0 +1,11 @@
|
||||
# Swagger generated server
|
||||
|
||||
Spring MVC Server
|
||||
|
||||
|
||||
## Overview
|
||||
This server 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-core), you can easily generate a server stub. This is an example of building a swagger-enabled server in Java using the Spring MVC framework.
|
||||
|
||||
The underlying library integrating swagger to Spring-MVC is [springfox](https://github.com/springfox/springfox)
|
||||
|
||||
You can view the server in swagger-ui by pointing to http://localhost:8002{{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}}/sdoc.jsp
|
@ -0,0 +1,53 @@
|
||||
package {{apiPackage}};
|
||||
|
||||
import {{modelPackage}}.*;
|
||||
|
||||
{{#imports}}import {{import}};
|
||||
{{/imports}}
|
||||
|
||||
import com.wordnik.swagger.annotations.Api;
|
||||
import com.wordnik.swagger.annotations.ApiOperation;
|
||||
import com.wordnik.swagger.annotations.ApiParam;
|
||||
import com.wordnik.swagger.annotations.ApiResponse;
|
||||
import com.wordnik.swagger.annotations.ApiResponses;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RequestPart;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.springframework.http.MediaType.*;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/{{baseName}}", produces = {APPLICATION_JSON_VALUE})
|
||||
@Api(value = "/{{baseName}}", description = "the {{baseName}} API")
|
||||
{{#operations}}
|
||||
public class {{classname}} {
|
||||
{{#operation}}
|
||||
|
||||
@ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}})
|
||||
@ApiResponses(value = { {{#responses}}
|
||||
@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}}
|
||||
method = RequestMethod.{{httpMethod}})
|
||||
public ResponseEntity<{{returnType}}> {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
|
||||
{{/hasMore}}{{/allParams}})
|
||||
throws NotFoundException {
|
||||
// do some magic!
|
||||
return new ResponseEntity<{{returnType}}>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
{{/operation}}
|
||||
}
|
||||
{{/operations}}
|
@ -0,0 +1,2 @@
|
||||
{{#isFormParam}}{{#notFile}}
|
||||
@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@RequestPart("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile fileDetail{{/isFile}}{{/isFormParam}}
|
@ -1 +1 @@
|
||||
{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@HeaderParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}}
|
||||
{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@RequestHeader("{{paramName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}}
|
@ -26,7 +26,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
|
||||
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
|
||||
* maximum: {{maximum}}{{/maximum}}
|
||||
**/
|
||||
@ApiModelProperty(required = {{required}}, value = "{{{description}}}")
|
||||
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
|
||||
@JsonProperty("{{name}}")
|
||||
public {{{datatypeWithEnum}}} {{getter}}() {
|
||||
return {{name}};
|
@ -1 +1 @@
|
||||
{{#isPathParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/isPathParam}}
|
||||
{{#isPathParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathVariable("{{paramName}}") {{{dataType}}} {{paramName}}{{/isPathParam}}
|
@ -26,31 +26,28 @@
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.mortbay.jetty</groupId>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-maven-plugin</artifactId>
|
||||
<version>${jetty-version}</version>
|
||||
<configuration>
|
||||
<webAppConfig>
|
||||
<contextPath>{{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}}</contextPath>
|
||||
</webAppConfig>
|
||||
<webAppSourceDirectory>target/${project.artifactId}-${project.version}</webAppSourceDirectory>
|
||||
<webAppSourceDirectory>target/${project.artifactId}-${project-version}</webAppSourceDirectory>
|
||||
<webDefaultXml>${project.basedir}/conf/jetty/webdefault.xml</webDefaultXml>
|
||||
<stopPort>8079</stopPort>
|
||||
<stopKey>stopit</stopKey>
|
||||
<connectors>
|
||||
<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
|
||||
<port>8002</port>
|
||||
<maxIdleTime>60000</maxIdleTime>
|
||||
<confidentialPort>8443</confidentialPort>
|
||||
</connector>
|
||||
</connectors>
|
||||
<httpConnector>
|
||||
<port>8002</port>
|
||||
<idleTimeout>60000</idleTimeout>
|
||||
</httpConnector>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>start-jetty</id>
|
||||
<phase>pre-integration-test</phase>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
<goal>start</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<scanIntervalSeconds>0</scanIntervalSeconds>
|
||||
@ -66,6 +63,49 @@
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>com.googlecode.maven-download-plugin</groupId>
|
||||
<artifactId>download-maven-plugin</artifactId>
|
||||
<version>1.2.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>swagger-ui</id>
|
||||
<goals>
|
||||
<goal>wget</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<url>https://github.com/swagger-api/swagger-ui/archive/v${swagger-ui-version}.tar.gz</url>
|
||||
<unpack>true</unpack>
|
||||
<outputDirectory>${project.build.directory}</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<version>2.6</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-resources</id>
|
||||
<phase>validate</phase>
|
||||
<goals>
|
||||
<goal>copy-resources</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>target/${project.artifactId}-${project.version}</outputDirectory>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>${project.build.directory}/swagger-ui-${swagger-ui-version}/dist</directory>
|
||||
<filtering>true</filtering>
|
||||
<excludes>
|
||||
<exclude>index.html</exclude>
|
||||
</excludes>
|
||||
</resource>
|
||||
</resources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
@ -105,6 +145,50 @@
|
||||
<version>${jersey-version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--Spring dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${spring-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${spring-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${spring-version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--SpringFox dependencies-->
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-core</artifactId>
|
||||
<version>${springfox-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-spi</artifactId>
|
||||
<version>${springfox-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-spring-web</artifactId>
|
||||
<version>${springfox-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger2</artifactId>
|
||||
<version>${springfox-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
<version>${springfox-version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.scalatest</groupId>
|
||||
<artifactId>scalatest_2.9.1</artifactId>
|
||||
@ -125,20 +209,21 @@
|
||||
</dependencies>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>sonatype-snapshots</id>
|
||||
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
<id>jcenter-snapshots</id>
|
||||
<name>jcenter</name>
|
||||
<url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
<properties>
|
||||
<swagger-core-version>1.5.3-M1-SNAPSHOT</swagger-core-version>
|
||||
<jetty-version>8.1.11.v20130520</jetty-version>
|
||||
<jetty-version>9.2.9.v20150224</jetty-version>
|
||||
<swagger-ui-version>2.1.0-M2</swagger-ui-version>
|
||||
<jersey-version>1.13</jersey-version>
|
||||
<slf4j-version>1.6.3</slf4j-version>
|
||||
<scala-test-version>1.6.1</scala-test-version>
|
||||
<junit-version>4.8.1</junit-version>
|
||||
<servlet-api-version>2.5</servlet-api-version>
|
||||
<springfox-version>2.0.0-SNAPSHOT</springfox-version>
|
||||
<spring-version>4.0.9.RELEASE</spring-version>
|
||||
</properties>
|
||||
</project>
|
@ -0,0 +1 @@
|
||||
{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value = "{{paramName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/isQueryParam}}
|
@ -0,0 +1 @@
|
||||
springfox.documentation.swagger.v2.path=/api-docs
|
@ -0,0 +1,40 @@
|
||||
package {{configPackage}};
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import springfox.documentation.service.ApiInfo;
|
||||
import springfox.documentation.spi.DocumentationType;
|
||||
import springfox.documentation.spring.web.plugins.Docket;
|
||||
import springfox.documentation.swagger2.annotations.EnableSwagger2;
|
||||
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = "{{apiPackage}}")
|
||||
@EnableWebMvc
|
||||
@EnableSwagger2 //Loads the spring beans required by the framework
|
||||
@PropertySource("classpath:swagger.properties")
|
||||
@Import(SwaggerUiConfiguration.class)
|
||||
public class SwaggerConfig {
|
||||
@Bean
|
||||
ApiInfo apiInfo() {
|
||||
ApiInfo apiInfo = new ApiInfo(
|
||||
"{{appName}}",
|
||||
"{{{appDescription}}}",
|
||||
"{{appVersion}}",
|
||||
"{{infoUrl}}",
|
||||
"{{infoEmail}}",
|
||||
"{{licenseInfo}}",
|
||||
"{{licenseUrl}}" );
|
||||
return apiInfo;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Docket customImplementation(){
|
||||
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
package {{configPackage}};
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter {
|
||||
private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" };
|
||||
|
||||
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
|
||||
"classpath:/META-INF/resources/", "classpath:/resources/",
|
||||
"classpath:/static/", "classpath:/public/" };
|
||||
|
||||
private static final String[] RESOURCE_LOCATIONS;
|
||||
static {
|
||||
RESOURCE_LOCATIONS = new String[CLASSPATH_RESOURCE_LOCATIONS.length
|
||||
+ SERVLET_RESOURCE_LOCATIONS.length];
|
||||
System.arraycopy(SERVLET_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, 0,
|
||||
SERVLET_RESOURCE_LOCATIONS.length);
|
||||
System.arraycopy(CLASSPATH_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS,
|
||||
SERVLET_RESOURCE_LOCATIONS.length, CLASSPATH_RESOURCE_LOCATIONS.length);
|
||||
}
|
||||
|
||||
private static final String[] STATIC_INDEX_HTML_RESOURCES;
|
||||
static {
|
||||
STATIC_INDEX_HTML_RESOURCES = new String[RESOURCE_LOCATIONS.length];
|
||||
for (int i = 0; i < STATIC_INDEX_HTML_RESOURCES.length; i++) {
|
||||
STATIC_INDEX_HTML_RESOURCES[i] = RESOURCE_LOCATIONS[i] + "index.html";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
if (!registry.hasMappingForPattern("/webjars/**")) {
|
||||
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
|
||||
}
|
||||
if (!registry.hasMappingForPattern("/**")) {
|
||||
registry.addResourceHandler("/**").addResourceLocations(RESOURCE_LOCATIONS);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package {{configPackage}};
|
||||
|
||||
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
|
||||
|
||||
public class WebApplication extends AbstractAnnotationConfigDispatcherServletInitializer {
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getRootConfigClasses() {
|
||||
return new Class[] { SwaggerConfig.class };
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getServletConfigClasses() {
|
||||
return new Class<?>[] { WebMvcConfiguration.class };
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String[] getServletMappings() {
|
||||
return new String[] { "/" };
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package {{configPackage}};
|
||||
|
||||
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
|
||||
|
||||
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
|
||||
@Override
|
||||
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
|
||||
configurer.enable();
|
||||
}
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
# Swagger generated server
|
||||
|
||||
Springdox
|
||||
|
||||
|
||||
## Overview
|
||||
This server was generated by the [swagger-codegen](https://github.com/wordnik/swagger-codegen) project. By using the
|
||||
[swagger-spec](https://github.com/wordnik/swagger-core/wiki) from a remote server, you can easily generate a server stub. This
|
||||
is an example of building a swagger-enabled scalatra server.
|
||||
|
||||
This example uses the [Springdox](https://github.com/springdox/springdox) framework.
|
||||
|
@ -1,55 +0,0 @@
|
||||
package {{configPackage}};
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import springdox.documentation.swagger2.annotations.EnableSwagger2;
|
||||
import springdox.documentation.spring.web.plugins.DocumentationConfigurer;
|
||||
|
||||
import springdox.documentation.spi.DocumentationType;
|
||||
import springdox.documentation.service.ApiInfo;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@EnableSwagger2 //Loads the spring beans required by the framework
|
||||
public class SwaggerConfig {
|
||||
|
||||
private DocumentationConfigurer documentationConfigurer;
|
||||
|
||||
@Autowired
|
||||
public void setDocumentationConfigurer(DocumentationConfigurer configurer){
|
||||
this.documentationConfigurer = documentationConfigurer;
|
||||
}
|
||||
|
||||
@Bean
|
||||
ApiInfo apiInfo() {
|
||||
ApiInfo apiInfo = new ApiInfo(
|
||||
"{{appName}}",
|
||||
"{{appDescription}}",
|
||||
"1.0.0",
|
||||
"My Apps API terms of service",
|
||||
"{{infoEmail}}",
|
||||
"{{licenseInfo}}",
|
||||
"{{licenseUrl}}" );
|
||||
return apiInfo;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DocumentationConfigurer customImplementation(){
|
||||
return new DocumentationConfigurer(DocumentationType.SWAGGER_2)
|
||||
.groupName("default")
|
||||
.includePatterns(".*replace {{appName}} with your api classes.*")
|
||||
.apiInfo(apiInfo());
|
||||
}
|
||||
|
||||
@Bean
|
||||
ObjectMapper objectMapper() { return new ObjectMapper(); }
|
||||
|
||||
}
|
@ -1,49 +0,0 @@
|
||||
package {{apiPackage}};
|
||||
|
||||
import {{modelPackage}}.*;
|
||||
|
||||
import com.wordnik.swagger.annotations.*;
|
||||
|
||||
import com.sun.jersey.multipart.FormDataParam;
|
||||
|
||||
{{#imports}}import {{import}};
|
||||
{{/imports}}
|
||||
|
||||
import java.util.List;
|
||||
import {{package}}.NotFoundException;
|
||||
|
||||
import java.io.InputStream;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import static org.springframework.http.MediaType.*;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/{{baseName}}",produces = {APPLICATION_JSON_VALUE})
|
||||
@Api(value = "/{{baseName}}", description = "the {{baseName}} API")
|
||||
{{#operations}}
|
||||
public class {{classname}} {
|
||||
{{#operation}}
|
||||
|
||||
{{#subresourceOperation}}@RequestMapping(value = {{path}}, method = RequestMethod.{{httpMethod}} ){{/subresourceOperation}}
|
||||
{{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}}
|
||||
{{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
|
||||
@ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}})
|
||||
@ApiResponses(value = { {{#responses}}
|
||||
@ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},
|
||||
{{/hasMore}}{{/responses}} })
|
||||
|
||||
public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
|
||||
{{/hasMore}}{{/allParams}})
|
||||
throws NotFoundException {
|
||||
// do some magic!
|
||||
return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
|
||||
}
|
||||
|
||||
{{/operation}}
|
||||
}
|
||||
{{/operations}}
|
@ -1,2 +0,0 @@
|
||||
{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "{{{description}}}") @FormDataParam("file") InputStream inputStream,
|
||||
@ApiParam(value = "file detail") @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}}
|
@ -1 +0,0 @@
|
||||
{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @QueryParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}}
|
@ -1,17 +1,19 @@
|
||||
com.wordnik.swagger.codegen.languages.AndroidClientCodegen
|
||||
com.wordnik.swagger.codegen.languages.AsyncScalaClientCodegen
|
||||
com.wordnik.swagger.codegen.languages.CSharpClientCodegen
|
||||
com.wordnik.swagger.codegen.languages.JavaClientCodegen
|
||||
com.wordnik.swagger.codegen.languages.JaxRSServerCodegen
|
||||
com.wordnik.swagger.codegen.languages.SpringdoxServerCodegen
|
||||
com.wordnik.swagger.codegen.languages.NodeJSServerCodegen
|
||||
com.wordnik.swagger.codegen.languages.ObjcClientCodegen
|
||||
com.wordnik.swagger.codegen.languages.ScalatraServerCodegen
|
||||
com.wordnik.swagger.codegen.languages.PhpClientCodegen
|
||||
com.wordnik.swagger.codegen.languages.PythonClientCodegen
|
||||
com.wordnik.swagger.codegen.languages.Python3ClientCodegen
|
||||
com.wordnik.swagger.codegen.languages.RubyClientCodegen
|
||||
com.wordnik.swagger.codegen.languages.ScalaClientCodegen
|
||||
com.wordnik.swagger.codegen.languages.ScalatraServerCodegen
|
||||
com.wordnik.swagger.codegen.languages.SpringMVCServerCodegen
|
||||
com.wordnik.swagger.codegen.languages.StaticDocCodegen
|
||||
com.wordnik.swagger.codegen.languages.StaticHtmlGenerator
|
||||
com.wordnik.swagger.codegen.languages.SwaggerGenerator
|
||||
com.wordnik.swagger.codegen.languages.SwaggerYamlGenerator
|
||||
com.wordnik.swagger.codegen.languages.TizenClientCodegen
|
||||
com.wordnik.swagger.codegen.languages.PhpClientCodegen
|
||||
com.wordnik.swagger.codegen.languages.RubyClientCodegen
|
||||
com.wordnik.swagger.codegen.languages.PythonClientCodegen
|
||||
|
@ -39,10 +39,12 @@ public class {{classname}} {
|
||||
}
|
||||
|
||||
{{#operation}}
|
||||
{{#errorList}} //error info- code: {{code}} reason: "{{reason}}" model: {{#responseModel}}{{responseModel}}
|
||||
{{/responseModel}}{{^responseModel}}<none>
|
||||
{{/responseModel}}
|
||||
{{/errorList}}
|
||||
/**
|
||||
* {{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 ApiException {
|
||||
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
|
||||
|
||||
@ -105,12 +107,7 @@ public class {{classname}} {
|
||||
return {{#returnType}}null{{/returnType}};
|
||||
}
|
||||
} catch (ApiException ex) {
|
||||
if(ex.getCode() == 404) {
|
||||
return {{#returnType}} null{{/returnType}};
|
||||
}
|
||||
else {
|
||||
throw ex;
|
||||
}
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
{{/operation}}
|
||||
|
@ -16,6 +16,7 @@ import org.apache.http.entity.ContentType;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.*;
|
||||
import org.apache.http.impl.conn.*;
|
||||
import org.apache.http.impl.conn.tsccm.*;
|
||||
import org.apache.http.params.*;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
||||
@ -24,6 +25,7 @@ import java.net.Socket;
|
||||
import java.net.UnknownHostException;
|
||||
import java.net.URLEncoder;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@ -70,7 +72,7 @@ public class ApiInvoker {
|
||||
* ISO 8601 date time format.
|
||||
* @see https://en.wikipedia.org/wiki/ISO_8601
|
||||
*/
|
||||
public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
|
||||
public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
|
||||
|
||||
/**
|
||||
* ISO 8601 date format.
|
||||
@ -82,6 +84,13 @@ public class ApiInvoker {
|
||||
// Use UTC as the default time zone.
|
||||
DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
|
||||
// Set default User-Agent.
|
||||
setUserAgent("Android-Java-Swagger");
|
||||
}
|
||||
|
||||
public static void setUserAgent(String userAgent) {
|
||||
INSTANCE.addDefaultHeader("User-Agent", userAgent);
|
||||
}
|
||||
|
||||
public static Date parseDateTime(String str) {
|
||||
@ -113,6 +122,15 @@ public class ApiInvoker {
|
||||
return "";
|
||||
} else if (param instanceof Date) {
|
||||
return formatDateTime((Date) param);
|
||||
} else if (param instanceof Collection) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
for(Object o : (Collection)param) {
|
||||
if(b.length() > 0) {
|
||||
b.append(",");
|
||||
}
|
||||
b.append(String.valueOf(o));
|
||||
}
|
||||
return b.toString();
|
||||
} else {
|
||||
return String.valueOf(param);
|
||||
}
|
||||
@ -140,7 +158,7 @@ public class ApiInvoker {
|
||||
|
||||
public static Object deserialize(String json, String containerType, Class cls) throws ApiException {
|
||||
try{
|
||||
if("List".equals(containerType)) {
|
||||
if("list".equalsIgnoreCase(containerType) || "array".equalsIgnoreCase(containerType)) {
|
||||
JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls);
|
||||
List response = (List<?>) JsonUtil.getJsonMapper().readValue(json, typeInfo);
|
||||
return response;
|
||||
@ -300,6 +318,7 @@ public class ApiInvoker {
|
||||
HttpEntity resEntity = response.getEntity();
|
||||
responseString = EntityUtils.toString(resEntity);
|
||||
}
|
||||
return responseString;
|
||||
}
|
||||
else {
|
||||
if(response.getEntity() != null) {
|
||||
@ -308,9 +327,8 @@ public class ApiInvoker {
|
||||
}
|
||||
else
|
||||
responseString = "no data";
|
||||
throw new ApiException(code, responseString);
|
||||
}
|
||||
return responseString;
|
||||
throw new ApiException(code, responseString);
|
||||
}
|
||||
catch(IOException e) {
|
||||
throw new ApiException(500, e.getMessage());
|
||||
@ -364,7 +382,7 @@ public class ApiInvoker {
|
||||
schemeRegistry.register(httpsScheme);
|
||||
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
|
||||
|
||||
ignoreSSLConnectionManager = new SingleClientConnManager(new BasicHttpParams(), schemeRegistry);
|
||||
ignoreSSLConnectionManager = new ThreadSafeClientConnManager(new BasicHttpParams(), schemeRegistry);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
// This will only be thrown if SSL isn't available for some reason.
|
||||
} catch (KeyManagementException e) {
|
||||
|
@ -0,0 +1,55 @@
|
||||
buildscript {
|
||||
repositories {
|
||||
jcenter()
|
||||
}
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:1.2.2'
|
||||
}
|
||||
}
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
jcenter()
|
||||
}
|
||||
}
|
||||
|
||||
apply plugin: 'com.android.library'
|
||||
|
||||
android {
|
||||
compileSdkVersion 22
|
||||
buildToolsVersion '22.0.0'
|
||||
defaultConfig {
|
||||
minSdkVersion 14
|
||||
targetSdkVersion 22
|
||||
}
|
||||
}
|
||||
|
||||
ext {
|
||||
swagger_annotations_version = "1.5.3-M1"
|
||||
jackson_version = "2.5.2"
|
||||
httpclient_version = "4.3.3"
|
||||
junit_version = "4.8.1"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile "com.wordnik:swagger-annotations:$swagger_annotations_version"
|
||||
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
|
||||
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
|
||||
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
|
||||
compile "org.apache.httpcomponents:httpcore:$httpclient_version"
|
||||
compile "org.apache.httpcomponents:httpclient:$httpclient_version"
|
||||
compile "org.apache.httpcomponents:httpmime:$httpclient_version"
|
||||
testCompile "junit:junit:$junit_version"
|
||||
}
|
||||
|
||||
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}.jar"
|
||||
artifacts.add('archives', task);
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
<manifest package="{{invokerPackage}}">
|
||||
<application />
|
||||
</manifest>
|
@ -26,7 +26,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
|
||||
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
|
||||
* maximum: {{maximum}}{{/maximum}}
|
||||
**/
|
||||
@ApiModelProperty(required = {{required}}, value = "{{{description}}}")
|
||||
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
|
||||
@JsonProperty("{{baseName}}")
|
||||
public {{{datatypeWithEnum}}} {{getter}}() {
|
||||
return {{name}};
|
||||
|
@ -1,168 +0,0 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>{{groupId}}</groupId>
|
||||
<artifactId>{{artifactId}}</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<name>{{artifactId}}</name>
|
||||
<version>{{artifactVersion}}</version>
|
||||
<scm>
|
||||
<connection>scm:git:git@github.com:wordnik/swagger-mustache.git</connection>
|
||||
<developerConnection>scm:git:git@github.com:wordnik/swagger-codegen.git</developerConnection>
|
||||
<url>https://github.com/wordnik/swagger-codegen</url>
|
||||
</scm>
|
||||
<prerequisites>
|
||||
<maven>2.2.0</maven>
|
||||
</prerequisites>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.12</version>
|
||||
<configuration>
|
||||
<systemProperties>
|
||||
<property>
|
||||
<name>loggerPath</name>
|
||||
<value>conf/log4j.properties</value>
|
||||
</property>
|
||||
</systemProperties>
|
||||
<argLine>-Xms512m -Xmx1500m</argLine>
|
||||
<parallel>methods</parallel>
|
||||
<forkMode>pertest</forkMode>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/lib</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<!-- attach test jar -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>2.2</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
<goal>test-jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>add_sources</id>
|
||||
<phase>generate-sources</phase>
|
||||
<goals>
|
||||
<goal>add-source</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>src/main/java</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>add_test_sources</id>
|
||||
<phase>generate-test-sources</phase>
|
||||
<goals>
|
||||
<goal>add-test-source</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>src/test/java</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>2.3.2</version>
|
||||
<configuration>
|
||||
<source>1.6</source>
|
||||
<target>1.6</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.wordnik</groupId>
|
||||
<artifactId>swagger-annotations</artifactId>
|
||||
<version>${swagger-annotations-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-core</artifactId>
|
||||
<version>${jackson-version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-annotations</artifactId>
|
||||
<version>${jackson-version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson-version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${httpclient-version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpmime</artifactId>
|
||||
<version>${httpclient-version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- test dependencies -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit-version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>sonatype-snapshots</id>
|
||||
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
<properties>
|
||||
<swagger-annotations-version>1.5.1-M1</swagger-annotations-version>
|
||||
<jackson-version>2.1.4</jackson-version>
|
||||
<junit-version>4.8.1</junit-version>
|
||||
<maven-plugin-version>1.0.0</maven-plugin-version>
|
||||
<junit-version>4.8.1</junit-version>
|
||||
<httpclient-version>4.3.6</httpclient-version>
|
||||
</properties>
|
||||
</project>
|
@ -2,10 +2,11 @@ organization := "{{package}}"
|
||||
|
||||
name := "{{projectName}}-client"
|
||||
|
||||
libraryDependencies += "com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5"
|
||||
|
||||
libraryDependencies += "joda-time" % "joda-time" % "2.3"
|
||||
|
||||
libraryDependencies += "org.joda" % "joda-convert" % "1.3.1"
|
||||
|
||||
libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.0.13" % "provided"
|
||||
libraryDependencies ++= Seq(
|
||||
"com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5",
|
||||
"joda-time" % "joda-time" % "2.3",
|
||||
"org.joda" % "joda-convert" % "1.3.1",
|
||||
"ch.qos.logback" % "logback-classic" % "1.0.13" % "provided",
|
||||
"org.scalatest" %% "scalatest" % "2.2.1" % "test",
|
||||
"junit" % "junit" % "4.11" % "test"
|
||||
)
|
||||
|
@ -1,101 +1,111 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using {{invokerPackage}};
|
||||
using {{modelPackage}};
|
||||
{{#imports}}
|
||||
{{/imports}}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using {{invokerPackage}};
|
||||
using {{modelPackage}};
|
||||
{{#imports}}
|
||||
{{/imports}}
|
||||
|
||||
namespace {{package}} {
|
||||
{{#operations}}
|
||||
public class {{classname}} {
|
||||
string basePath;
|
||||
private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance();
|
||||
namespace {{package}} {
|
||||
{{#operations}}
|
||||
public class {{classname}} {
|
||||
string basePath;
|
||||
private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance();
|
||||
|
||||
public {{classname}}(String basePath = "{{basePath}}")
|
||||
{
|
||||
this.basePath = basePath;
|
||||
public {{classname}}(String basePath = "{{basePath}}")
|
||||
{
|
||||
this.basePath = basePath;
|
||||
}
|
||||
|
||||
public ApiInvoker getInvoker() {
|
||||
return apiInvoker;
|
||||
}
|
||||
|
||||
// Sets the endpoint base url for the services being accessed
|
||||
public void setBasePath(string basePath) {
|
||||
this.basePath = basePath;
|
||||
}
|
||||
|
||||
// Gets the endpoint base url for the services being accessed
|
||||
public String getBasePath() {
|
||||
return basePath;
|
||||
}
|
||||
|
||||
{{#operation}}
|
||||
|
||||
/// <summary>
|
||||
/// {{summary}} {{notes}}
|
||||
/// </summary>
|
||||
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param>
|
||||
{{#hasMore}} {{/hasMore}}{{/allParams}}
|
||||
/// <returns></returns>
|
||||
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
|
||||
// create path and map variables
|
||||
var path = "{{path}}".Replace("{format}","json"){{#pathParams}}.Replace("{" + "{{baseName}}" + "}", apiInvoker.ParameterToString({{{paramName}}})){{/pathParams}};
|
||||
|
||||
// query params
|
||||
var queryParams = new Dictionary<String, String>();
|
||||
var headerParams = new Dictionary<String, String>();
|
||||
var formParams = new Dictionary<String, object>();
|
||||
|
||||
{{#requiredParamCount}}
|
||||
// verify required params are set
|
||||
if ({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) {
|
||||
throw new ApiException(400, "missing required params");
|
||||
}
|
||||
{{/requiredParamCount}}
|
||||
|
||||
public ApiInvoker getInvoker() {
|
||||
return apiInvoker;
|
||||
{{#queryParams}}if ({{paramName}} != null){
|
||||
queryParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}}));
|
||||
}
|
||||
{{/queryParams}}
|
||||
|
||||
// Sets the endpoint base url for the services being accessed
|
||||
public void setBasePath(string basePath) {
|
||||
this.basePath = basePath;
|
||||
}
|
||||
{{#headerParams}}headerParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}}));
|
||||
{{/headerParams}}
|
||||
|
||||
// Gets the endpoint base url for the services being accessed
|
||||
public String getBasePath() {
|
||||
return basePath;
|
||||
}
|
||||
|
||||
{{#operation}}
|
||||
|
||||
/// <summary>
|
||||
/// {{summary}} {{notes}}
|
||||
/// </summary>
|
||||
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param>
|
||||
{{#hasMore}} {{/hasMore}}{{/allParams}}
|
||||
/// <returns></returns>
|
||||
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
|
||||
// create path and map variables
|
||||
var path = "{{path}}".Replace("{format}","json"){{#pathParams}}.Replace("{" + "{{paramName}}" + "}", apiInvoker.escapeString({{{paramName}}}.ToString())){{/pathParams}};
|
||||
|
||||
// query params
|
||||
var queryParams = new Dictionary<String, String>();
|
||||
var headerParams = new Dictionary<String, String>();
|
||||
var formParams = new Dictionary<String, object>();
|
||||
|
||||
{{#requiredParamCount}}
|
||||
// verify required params are set
|
||||
if ({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) {
|
||||
throw new ApiException(400, "missing required params");
|
||||
{{#formParams}}if ({{paramName}} != null){
|
||||
if({{paramName}} is byte[]) {
|
||||
formParams.Add("{{baseName}}", {{paramName}});
|
||||
} else {
|
||||
formParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}}));
|
||||
}
|
||||
{{/requiredParamCount}}
|
||||
}
|
||||
{{/formParams}}
|
||||
|
||||
{{#queryParams}}if ({{paramName}} != null){
|
||||
string paramStr = ({{paramName}} is DateTime) ? ((DateTime)(object){{paramName}}).ToString("u") : Convert.ToString({{paramName}});
|
||||
queryParams.Add("{{paramName}}", paramStr);
|
||||
}
|
||||
{{/queryParams}}
|
||||
|
||||
{{#headerParams}}headerParams.Add("{{paramName}}", {{paramName}});
|
||||
{{/headerParams}}
|
||||
|
||||
{{#formParams}}if ({{paramName}} != null){
|
||||
if({{paramName}} is byte[]) {
|
||||
formParams.Add("{{paramName}}", {{paramName}});
|
||||
} else {
|
||||
string paramStr = ({{paramName}} is DateTime) ? ((DateTime)(object){{paramName}}).ToString("u") : Convert.ToString({{paramName}});
|
||||
formParams.Add("{{paramName}}", paramStr);
|
||||
}
|
||||
}
|
||||
{{/formParams}}
|
||||
|
||||
try {
|
||||
if (typeof({{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}) == typeof(byte[])) {
|
||||
var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams);
|
||||
return {{#returnType}}((object)response) as {{{returnType}}}{{/returnType}};
|
||||
} else {
|
||||
var response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{bodyParam}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams, formParams);
|
||||
if(response != null){
|
||||
return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(response, typeof({{{returnType}}})){{/returnType}};
|
||||
}
|
||||
else {
|
||||
return {{#returnType}}null{{/returnType}};
|
||||
}
|
||||
}
|
||||
} catch (ApiException ex) {
|
||||
if(ex.ErrorCode == 404) {
|
||||
return {{#returnType}}null{{/returnType}};
|
||||
try {
|
||||
if (typeof({{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}) == typeof(byte[])) {
|
||||
{{#returnType}}
|
||||
var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams);
|
||||
return ((object)response) as {{{returnType}}};
|
||||
{{/returnType}}
|
||||
{{^returnType}}
|
||||
apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams);
|
||||
return;
|
||||
{{/returnType}}
|
||||
} else {
|
||||
{{#returnType}}
|
||||
var response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams, formParams);
|
||||
if (response != null){
|
||||
return ({{{returnType}}}) ApiInvoker.deserialize(response, typeof({{{returnType}}}));
|
||||
}
|
||||
else {
|
||||
throw ex;
|
||||
return null;
|
||||
}
|
||||
{{/returnType}}
|
||||
{{^returnType}}
|
||||
apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams, formParams);
|
||||
return;
|
||||
{{/returnType}}
|
||||
}
|
||||
} catch (ApiException ex) {
|
||||
if(ex.ErrorCode == 404) {
|
||||
return {{#returnType}}null{{/returnType}};
|
||||
}
|
||||
else {
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
{{/operation}}
|
||||
}
|
||||
{{/operations}}
|
||||
}
|
||||
{{/operation}}
|
||||
}
|
||||
{{/operations}}
|
||||
}
|
||||
|
@ -15,14 +15,41 @@
|
||||
return _instance;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add default header
|
||||
/// </summary>
|
||||
/// <param name="key"> Header field name
|
||||
/// <param name="value"> Header field value
|
||||
/// <returns></returns>
|
||||
public void addDefaultHeader(string key, string value) {
|
||||
defaultHeaderMap.Add(key, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// escape string (url-encoded)
|
||||
/// </summary>
|
||||
/// <param name="str"> String to be escaped
|
||||
/// <returns>Escaped string</returns>
|
||||
public string escapeString(string str) {
|
||||
return str;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// if parameter is DateTime, output in ISO8601 format, otherwise just return the string
|
||||
/// </summary>
|
||||
/// <param name="obj"> The parameter (header, path, query, form)
|
||||
/// <returns>Formatted string</returns>
|
||||
public string ParameterToString(object obj)
|
||||
{
|
||||
return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserialize the JSON string into a proper object
|
||||
/// </summary>
|
||||
/// <param name="json"> JSON string
|
||||
/// <param name="type"> Object type
|
||||
/// <returns>Object representation of the JSON string</returns>
|
||||
public static object deserialize(string json, Type type) {
|
||||
try
|
||||
{
|
||||
@ -99,6 +126,7 @@
|
||||
case "GET":
|
||||
break;
|
||||
case "POST":
|
||||
case "PATCH":
|
||||
case "PUT":
|
||||
case "DELETE":
|
||||
using (Stream requestStream = client.GetRequestStream())
|
||||
|
@ -13,13 +13,14 @@
|
||||
<div class="license-info">{{{licenseInfo}}}</div>
|
||||
<div class="license-url">{{{licenseUrl}}}</div>
|
||||
<h2>Access</h2>
|
||||
<div class="method-summary">Access to the API requires an api key to be provided by {{partner}} for all requests. The api key is passed as a header with the name `api_key` and the value provided by Reverb Technologies, Inc. Unless otherwise agreed upon, access to the Reverb API is intended solely for usage by {{partner}} and not third parties.</div>
|
||||
<div class="method-summary">Customize this message as you see fit!</div>
|
||||
<h2>Methods</h2>
|
||||
{{#apiInfo}}
|
||||
{{#apis}}
|
||||
{{#operations}}{{#operation}}
|
||||
<div class="method">
|
||||
<div class="method-path"><pre class="{{httpMethod}}"><code class="huge"><span>{{httpMethod}}</span>: {{path}}</code></pre></div>
|
||||
<div class="method-tags"> {{#tags}}<span class="method-tag">{{this}}</span>{{/tags}}</div>
|
||||
<div class="method-summary"><span class="nickname">{{nickname}}</span> {{summary}}</div>
|
||||
<div class="method-notes">{{notes}}</div>
|
||||
|
||||
|
@ -54,6 +54,7 @@ hr {
|
||||
|
||||
pre {
|
||||
padding: 10px;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
pre.get {
|
||||
@ -134,3 +135,17 @@ code {
|
||||
.param-header {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.method-tags {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.method-tag {
|
||||
background: none repeat scroll 0% 0% #24A600;
|
||||
border-radius: 3px;
|
||||
padding: 2px 10px;
|
||||
margin: 2px;
|
||||
color: #FFF;
|
||||
display: inline-block;
|
||||
text-decoration: none;
|
||||
}
|
@ -1,3 +1,4 @@
|
||||
platform :ios, '6.0'
|
||||
xcodeproj '{{projectName}}/{{projectName}}.xcodeproj'
|
||||
pod 'AFNetworking', '~> 2.1'
|
||||
pod 'JSONModel', '~> 1.0'
|
||||
|
@ -1,5 +1,6 @@
|
||||
#import "SWGApiClient.h"
|
||||
#import "SWGFile.h"
|
||||
#import "SWGQueryParamCollection.h"
|
||||
|
||||
@implementation SWGApiClient
|
||||
|
||||
@ -30,13 +31,13 @@ static bool loggingEnabled = true;
|
||||
diskSize: (unsigned long) diskSize {
|
||||
NSAssert(memorySize > 0, @"invalid in-memory cache size");
|
||||
NSAssert(diskSize >= 0, @"invalid disk cache size");
|
||||
|
||||
|
||||
NSURLCache *cache =
|
||||
[[NSURLCache alloc]
|
||||
initWithMemoryCapacity:memorySize
|
||||
diskCapacity:diskSize
|
||||
diskPath:@"swagger_url_cache"];
|
||||
|
||||
|
||||
[NSURLCache setSharedURLCache:cache];
|
||||
}
|
||||
|
||||
@ -53,17 +54,17 @@ static bool loggingEnabled = true;
|
||||
// setup static vars
|
||||
// create queue
|
||||
sharedQueue = [[NSOperationQueue alloc] init];
|
||||
|
||||
|
||||
// create pool
|
||||
_pool = [[NSMutableDictionary alloc] init];
|
||||
|
||||
|
||||
// initialize URL cache
|
||||
[SWGApiClient configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024];
|
||||
|
||||
|
||||
// configure reachability
|
||||
[SWGApiClient configureCacheReachibilityForHost:baseUrl];
|
||||
}
|
||||
|
||||
|
||||
@synchronized(self) {
|
||||
SWGApiClient * client = [_pool objectForKey:baseUrl];
|
||||
if (client == nil) {
|
||||
@ -127,7 +128,7 @@ static bool loggingEnabled = true;
|
||||
return TRUE;
|
||||
else return FALSE;
|
||||
}];
|
||||
|
||||
|
||||
if(matchingItems.count == 1) {
|
||||
if(loggingEnabled)
|
||||
NSLog(@"removing request id %@", requestId);
|
||||
@ -168,19 +169,19 @@ static bool loggingEnabled = true;
|
||||
NSLog(@"reachability changed to AFNetworkReachabilityStatusUnknown");
|
||||
[SWGApiClient setOfflineState:true];
|
||||
break;
|
||||
|
||||
|
||||
case AFNetworkReachabilityStatusNotReachable:
|
||||
if(loggingEnabled)
|
||||
NSLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable");
|
||||
[SWGApiClient setOfflineState:true];
|
||||
break;
|
||||
|
||||
|
||||
case AFNetworkReachabilityStatusReachableViaWWAN:
|
||||
if(loggingEnabled)
|
||||
NSLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN");
|
||||
[SWGApiClient setOfflineState:false];
|
||||
break;
|
||||
|
||||
|
||||
case AFNetworkReachabilityStatusReachableViaWiFi:
|
||||
if(loggingEnabled)
|
||||
NSLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi");
|
||||
@ -201,21 +202,52 @@ static bool loggingEnabled = true;
|
||||
queryParams:(NSDictionary*) queryParams {
|
||||
NSString * separator = nil;
|
||||
int counter = 0;
|
||||
|
||||
|
||||
NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path];
|
||||
if(queryParams != nil){
|
||||
for(NSString * key in [queryParams keyEnumerator]){
|
||||
if(counter == 0) separator = @"?";
|
||||
else separator = @"&";
|
||||
NSString * value;
|
||||
if([[queryParams valueForKey:key] isKindOfClass:[NSString class]]){
|
||||
value = [SWGApiClient escape:[queryParams valueForKey:key]];
|
||||
id queryParam = [queryParams valueForKey:key];
|
||||
if([queryParam isKindOfClass:[NSString class]]){
|
||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator,
|
||||
[SWGApiClient escape:key], [SWGApiClient escape:[queryParams valueForKey:key]]]];
|
||||
}
|
||||
else if([queryParam isKindOfClass:[SWGQueryParamCollection class]]){
|
||||
SWGQueryParamCollection * coll = (SWGQueryParamCollection*) queryParam;
|
||||
NSArray* values = [coll values];
|
||||
NSString* format = [coll format];
|
||||
|
||||
if([format isEqualToString:@"csv"]) {
|
||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator,
|
||||
[SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@","]]]];
|
||||
|
||||
}
|
||||
else if([format isEqualToString:@"tsv"]) {
|
||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator,
|
||||
[SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"\t"]]]];
|
||||
|
||||
}
|
||||
else if([format isEqualToString:@"pipes"]) {
|
||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator,
|
||||
[SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"|"]]]];
|
||||
|
||||
}
|
||||
else if([format isEqualToString:@"multi"]) {
|
||||
for(id obj in values) {
|
||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator,
|
||||
[SWGApiClient escape:key], [NSString stringWithFormat:@"%@", obj]]];
|
||||
counter += 1;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
else {
|
||||
value = [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]];
|
||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator,
|
||||
[SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]]];
|
||||
}
|
||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator,
|
||||
[SWGApiClient escape:key], value]];
|
||||
|
||||
counter += 1;
|
||||
}
|
||||
}
|
||||
@ -242,7 +274,28 @@ static bool loggingEnabled = true;
|
||||
requestContentType: (NSString*) requestContentType
|
||||
responseContentType: (NSString*) responseContentType
|
||||
completionBlock: (void (^)(NSDictionary*, NSError *))completionBlock {
|
||||
|
||||
// setting request serializer
|
||||
if ([requestContentType isEqualToString:@"application/json"]) {
|
||||
self.requestSerializer = [AFJSONRequestSerializer serializer];
|
||||
}
|
||||
else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) {
|
||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
||||
}
|
||||
else if ([requestContentType isEqualToString:@"multipart/form-data"]) {
|
||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
||||
}
|
||||
else {
|
||||
NSAssert(false, @"unsupport request type %@", requestContentType);
|
||||
}
|
||||
|
||||
// setting response serializer
|
||||
if ([responseContentType isEqualToString:@"application/json"]) {
|
||||
self.responseSerializer = [AFJSONResponseSerializer serializer];
|
||||
}
|
||||
else {
|
||||
self.responseSerializer = [AFHTTPResponseSerializer serializer];
|
||||
}
|
||||
|
||||
NSMutableURLRequest * request = nil;
|
||||
if (body != nil && [body isKindOfClass:[NSArray class]]){
|
||||
SWGFile * file;
|
||||
@ -259,8 +312,9 @@ static bool loggingEnabled = true;
|
||||
}
|
||||
}
|
||||
NSString * urlString = [[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString];
|
||||
|
||||
if(file != nil) {
|
||||
|
||||
// request with multipart form
|
||||
if([requestContentType isEqualToString:@"multipart/form-data"]) {
|
||||
request = [self.requestSerializer multipartFormRequestWithMethod: @"POST"
|
||||
URLString: urlString
|
||||
parameters: nil
|
||||
@ -270,20 +324,32 @@ static bool loggingEnabled = true;
|
||||
NSData* data = [params[key] dataUsingEncoding:NSUTF8StringEncoding];
|
||||
[formData appendPartWithFormData: data name: key];
|
||||
}
|
||||
|
||||
[formData appendPartWithFileData: [file data]
|
||||
name: [file paramName]
|
||||
fileName: [file name]
|
||||
mimeType: [file mimeType]];
|
||||
|
||||
|
||||
if (file) {
|
||||
[formData appendPartWithFileData: [file data]
|
||||
name: [file paramName]
|
||||
fileName: [file name]
|
||||
mimeType: [file mimeType]];
|
||||
}
|
||||
|
||||
}
|
||||
error:nil];
|
||||
}
|
||||
// request with form parameters or json
|
||||
else {
|
||||
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams];
|
||||
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
|
||||
|
||||
request = [self.requestSerializer requestWithMethod:method
|
||||
URLString:urlString
|
||||
parameters:params
|
||||
error:nil];
|
||||
}
|
||||
}
|
||||
else {
|
||||
NSString * pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams];
|
||||
NSString * urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
|
||||
|
||||
|
||||
request = [self.requestSerializer requestWithMethod:method
|
||||
URLString:urlString
|
||||
parameters:body
|
||||
@ -305,11 +371,9 @@ static bool loggingEnabled = true;
|
||||
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
|
||||
}
|
||||
|
||||
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
|
||||
|
||||
if(body != nil) {
|
||||
if([body isKindOfClass:[NSDictionary class]] || [body isKindOfClass:[NSArray class]]){
|
||||
[requestSerializer setValue:requestContentType forHTTPHeaderField:@"Content-Type"];
|
||||
[self.requestSerializer setValue:requestContentType forHTTPHeaderField:@"Content-Type"];
|
||||
}
|
||||
else if ([body isKindOfClass:[SWGFile class]]) {}
|
||||
else {
|
||||
@ -321,16 +385,16 @@ static bool loggingEnabled = true;
|
||||
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
|
||||
}
|
||||
}
|
||||
[requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
|
||||
|
||||
[self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
|
||||
|
||||
// Always disable cookies!
|
||||
[request setHTTPShouldHandleCookies:NO];
|
||||
|
||||
|
||||
|
||||
|
||||
if (self.logRequests) {
|
||||
[self logRequest:request];
|
||||
}
|
||||
|
||||
|
||||
NSNumber* requestId = [SWGApiClient queueRequest];
|
||||
AFHTTPRequestOperation *op =
|
||||
[self HTTPRequestOperationWithRequest:request
|
||||
@ -348,14 +412,14 @@ static bool loggingEnabled = true;
|
||||
userInfo[SWGResponseObjectErrorKey] = operation.responseObject;
|
||||
}
|
||||
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
|
||||
|
||||
|
||||
if(self.logServerResponses)
|
||||
[self logResponse:nil forRequest:request error:augmentedError];
|
||||
completionBlock(nil, augmentedError);
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
[self.operationQueue addOperation:op];
|
||||
return requestId;
|
||||
}
|
||||
@ -368,6 +432,28 @@ static bool loggingEnabled = true;
|
||||
requestContentType: (NSString*) requestContentType
|
||||
responseContentType: (NSString*) responseContentType
|
||||
completionBlock: (void (^)(NSString*, NSError *))completionBlock {
|
||||
// setting request serializer
|
||||
if ([requestContentType isEqualToString:@"application/json"]) {
|
||||
self.requestSerializer = [AFJSONRequestSerializer serializer];
|
||||
}
|
||||
else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) {
|
||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
||||
}
|
||||
else if ([requestContentType isEqualToString:@"multipart/form-data"]) {
|
||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
||||
}
|
||||
else {
|
||||
NSAssert(false, @"unsupport request type %@", requestContentType);
|
||||
}
|
||||
|
||||
// setting response serializer
|
||||
if ([responseContentType isEqualToString:@"application/json"]) {
|
||||
self.responseSerializer = [AFJSONResponseSerializer serializer];
|
||||
}
|
||||
else {
|
||||
self.responseSerializer = [AFHTTPResponseSerializer serializer];
|
||||
}
|
||||
|
||||
NSMutableURLRequest * request = nil;
|
||||
if (body != nil && [body isKindOfClass:[NSArray class]]){
|
||||
SWGFile * file;
|
||||
@ -384,31 +470,45 @@ static bool loggingEnabled = true;
|
||||
}
|
||||
}
|
||||
NSString * urlString = [[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString];
|
||||
|
||||
if(file != nil) {
|
||||
|
||||
// request with multipart form
|
||||
if([requestContentType isEqualToString:@"multipart/form-data"]) {
|
||||
request = [self.requestSerializer multipartFormRequestWithMethod: @"POST"
|
||||
URLString: urlString
|
||||
parameters: nil
|
||||
constructingBodyWithBlock: ^(id<AFMultipartFormData> formData) {
|
||||
|
||||
|
||||
for(NSString * key in params) {
|
||||
NSData* data = [params[key] dataUsingEncoding:NSUTF8StringEncoding];
|
||||
[formData appendPartWithFormData: data name: key];
|
||||
}
|
||||
|
||||
[formData appendPartWithFileData: [file data]
|
||||
name: [file paramName]
|
||||
fileName: [file name]
|
||||
mimeType: [file mimeType]];
|
||||
|
||||
|
||||
if (file) {
|
||||
[formData appendPartWithFileData: [file data]
|
||||
name: [file paramName]
|
||||
fileName: [file name]
|
||||
mimeType: [file mimeType]];
|
||||
}
|
||||
|
||||
}
|
||||
error:nil];
|
||||
}
|
||||
// request with form parameters or json
|
||||
else {
|
||||
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams];
|
||||
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
|
||||
|
||||
request = [self.requestSerializer requestWithMethod:method
|
||||
URLString:urlString
|
||||
parameters:params
|
||||
error:nil];
|
||||
}
|
||||
|
||||
}
|
||||
else {
|
||||
NSString * pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams];
|
||||
NSString * urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
|
||||
|
||||
|
||||
request = [self.requestSerializer requestWithMethod: method
|
||||
URLString: urlString
|
||||
parameters: body
|
||||
@ -429,13 +529,11 @@ static bool loggingEnabled = true;
|
||||
NSLog(@"%@ cache disabled", path);
|
||||
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
|
||||
}
|
||||
|
||||
|
||||
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
|
||||
|
||||
|
||||
if(body != nil) {
|
||||
if([body isKindOfClass:[NSDictionary class]] || [body isKindOfClass:[NSArray class]]){
|
||||
[requestSerializer setValue:requestContentType forHTTPHeaderField:@"Content-Type"];
|
||||
[self.requestSerializer setValue:requestContentType forHTTPHeaderField:@"Content-Type"];
|
||||
}
|
||||
else if ([body isKindOfClass:[SWGFile class]]){}
|
||||
else {
|
||||
@ -447,12 +545,12 @@ static bool loggingEnabled = true;
|
||||
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
|
||||
}
|
||||
}
|
||||
[requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
|
||||
[self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
|
||||
|
||||
|
||||
|
||||
// Always disable cookies!
|
||||
[request setHTTPShouldHandleCookies:NO];
|
||||
|
||||
|
||||
NSNumber* requestId = [SWGApiClient queueRequest];
|
||||
AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request
|
||||
success:^(AFHTTPRequestOperation *operation, id responseObject) {
|
||||
@ -470,15 +568,23 @@ static bool loggingEnabled = true;
|
||||
userInfo[SWGResponseObjectErrorKey] = operation.responseObject;
|
||||
}
|
||||
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
|
||||
|
||||
|
||||
if(self.logServerResponses)
|
||||
[self logResponse:nil forRequest:request error:augmentedError];
|
||||
completionBlock(nil, augmentedError);
|
||||
}
|
||||
}];
|
||||
|
||||
|
||||
[self.operationQueue addOperation:op];
|
||||
return requestId;
|
||||
}
|
||||
|
||||
@end
|
||||
@end
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
@ -1,6 +1,5 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "JSONModel.h"
|
||||
|
||||
@interface SWGObject : NSObject
|
||||
- (id) initWithValues:(NSDictionary*)dict;
|
||||
- (NSDictionary*) asDictionary;
|
||||
@interface SWGObject : JSONModel
|
||||
@end
|
||||
|
@ -1,17 +1,4 @@
|
||||
#import "SWGObject.h"
|
||||
|
||||
@implementation SWGObject
|
||||
|
||||
- (id) initWithValues:(NSDictionary*)dict {
|
||||
return self;
|
||||
}
|
||||
|
||||
- (NSDictionary*) asDictionary{
|
||||
return [NSDictionary init];
|
||||
}
|
||||
|
||||
- (NSString*)description {
|
||||
return [NSString stringWithFormat:@"%@ %@", [super description], [self asDictionary]];
|
||||
}
|
||||
|
||||
@end
|
||||
|
@ -0,0 +1,11 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@interface SWGQueryParamCollection : NSObject
|
||||
|
||||
@property(nonatomic, readonly) NSArray* values;
|
||||
@property(nonatomic, readonly) NSString* format;
|
||||
|
||||
- (id) initWithValuesAndFormat: (NSArray*) values
|
||||
format: (NSString*) format;
|
||||
|
||||
@end
|
@ -0,0 +1,16 @@
|
||||
#import "SWGQueryParamCollection.h"
|
||||
|
||||
@implementation SWGQueryParamCollection
|
||||
|
||||
@synthesize values = _values;
|
||||
@synthesize format = _format;
|
||||
|
||||
- (id) initWithValuesAndFormat: (NSArray*) values
|
||||
format: (NSString*) format {
|
||||
_values = values;
|
||||
_format = format;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
@ -1,11 +1,15 @@
|
||||
{{#operations}}
|
||||
#import "{{classname}}.h"
|
||||
#import "SWGFile.h"
|
||||
#import "SWGQueryParamCollection.h"
|
||||
#import "SWGApiClient.h"
|
||||
{{#imports}}#import "{{import}}.h"
|
||||
{{/imports}}
|
||||
{{newline}}
|
||||
|
||||
@interface {{classname}} ()
|
||||
@property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders;
|
||||
@end
|
||||
|
||||
@implementation {{classname}}
|
||||
static NSString * basePath = @"{{basePath}}";
|
||||
@ -33,18 +37,19 @@ static NSString * basePath = @"{{basePath}}";
|
||||
}
|
||||
|
||||
-(void) addHeader:(NSString*)value forKey:(NSString*)key {
|
||||
[[self apiClient] setHeaderValue:value forKey:key];
|
||||
[self.defaultHeaders setValue:value forKey:key];
|
||||
}
|
||||
|
||||
-(id) init {
|
||||
self = [super init];
|
||||
self.defaultHeaders = [NSMutableDictionary dictionary];
|
||||
[self apiClient];
|
||||
return self;
|
||||
}
|
||||
|
||||
-(void) setHeaderValue:(NSString*) value
|
||||
forKey:(NSString*)key {
|
||||
[[self apiClient] setHeaderValue:value forKey:key];
|
||||
[self.defaultHeaders setValue:value forKey:key];
|
||||
}
|
||||
|
||||
-(unsigned long) requestQueueSize {
|
||||
@ -53,9 +58,15 @@ static NSString * basePath = @"{{basePath}}";
|
||||
|
||||
|
||||
{{#operation}}
|
||||
/*!
|
||||
* {{{summary}}}
|
||||
* {{{notes}}}
|
||||
{{#allParams}} * \param {{paramName}} {{{description}}}
|
||||
{{/allParams}} * \returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
|
||||
*/
|
||||
-(NSNumber*) {{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}
|
||||
{{/allParams}}
|
||||
{{#returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{returnType}} output, NSError* error))completionBlock{{/returnBaseType}}
|
||||
{{#returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock{{/returnBaseType}}
|
||||
{{^returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock{{/returnBaseType}} {
|
||||
|
||||
NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@{{path}}", basePath];
|
||||
@ -67,14 +78,22 @@ static NSString * basePath = @"{{basePath}}";
|
||||
{{#pathParams}}[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"{{baseName}}", @"}"]] withString: [SWGApiClient escape:{{paramName}}]];
|
||||
{{/pathParams}}
|
||||
|
||||
NSString* requestContentType = @"application/json";
|
||||
NSString* responseContentType = @"application/json";
|
||||
NSArray* requestContentTypes = @[{{#consumes}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}];
|
||||
NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json";
|
||||
|
||||
NSArray* responseContentTypes = @[{{#produces}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}];
|
||||
NSString* responseContentType = [responseContentTypes count] > 0 ? responseContentTypes[0] : @"application/json";
|
||||
|
||||
NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
|
||||
{{#queryParams}}if({{paramName}} != nil)
|
||||
queryParams[@"{{baseName}}"] = {{paramName}};
|
||||
{{#queryParams}}if({{paramName}} != nil) {
|
||||
{{#collectionFormat}}
|
||||
queryParams[@"{{baseName}}"] = [[SWGQueryParamCollection alloc] initWithValuesAndFormat: {{baseName}} format: @"{{collectionFormat}}"];
|
||||
{{/collectionFormat}}
|
||||
{{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}}
|
||||
}
|
||||
{{/queryParams}}
|
||||
NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init];
|
||||
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders];
|
||||
|
||||
{{#headerParams}}if({{paramName}} != nil)
|
||||
headerParams[@"{{baseName}}"] = {{paramName}};
|
||||
{{/headerParams}}
|
||||
@ -86,8 +105,8 @@ static NSString * basePath = @"{{basePath}}";
|
||||
if(__body != nil && [__body isKindOfClass:[NSArray class]]){
|
||||
NSMutableArray * objs = [[NSMutableArray alloc] init];
|
||||
for (id dict in (NSArray*)__body) {
|
||||
if([dict respondsToSelector:@selector(asDictionary)]) {
|
||||
[objs addObject:[(SWGObject*)dict asDictionary]];
|
||||
if([dict respondsToSelector:@selector(toDictionary)]) {
|
||||
[objs addObject:[(SWGObject*)dict toDictionary]];
|
||||
}
|
||||
else{
|
||||
[objs addObject:dict];
|
||||
@ -95,8 +114,8 @@ static NSString * basePath = @"{{basePath}}";
|
||||
}
|
||||
bodyDictionary = objs;
|
||||
}
|
||||
else if([__body respondsToSelector:@selector(asDictionary)]) {
|
||||
bodyDictionary = [(SWGObject*)__body asDictionary];
|
||||
else if([__body respondsToSelector:@selector(toDictionary)]) {
|
||||
bodyDictionary = [(SWGObject*)__body toDictionary];
|
||||
}
|
||||
else if([__body isKindOfClass:[NSString class]]) {
|
||||
// convert it to a dictionary
|
||||
@ -111,7 +130,7 @@ static NSString * basePath = @"{{basePath}}";
|
||||
{{/bodyParam}}
|
||||
{{^bodyParam}}
|
||||
|
||||
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
|
||||
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
|
||||
|
||||
{{#formParams}}
|
||||
{{#notFile}}
|
||||
@ -121,8 +140,10 @@ static NSString * basePath = @"{{basePath}}";
|
||||
if(bodyDictionary == nil) {
|
||||
bodyDictionary = [[NSMutableArray alloc] init];
|
||||
}
|
||||
[bodyDictionary addObject:{{paramName}}];
|
||||
{{paramName}}.paramName = @"{{baseName}}";
|
||||
if({{paramName}} != nil) {
|
||||
[bodyDictionary addObject:{{paramName}}];
|
||||
{{paramName}}.paramName = @"{{baseName}}";
|
||||
}
|
||||
{{/isFile}}
|
||||
if(bodyDictionary == nil) {
|
||||
bodyDictionary = [[NSMutableArray alloc] init];
|
||||
@ -167,4 +188,4 @@ static NSString * basePath = @"{{basePath}}";
|
||||
|
||||
{{newline}}
|
||||
{{/operations}}
|
||||
@end
|
||||
@end
|
||||
|
@ -16,20 +16,17 @@
|
||||
/**
|
||||
|
||||
{{{summary}}}
|
||||
{{#notes}}
|
||||
{{{notes}}}
|
||||
{{/notes}}
|
||||
{{#notes}}{{{notes}}}{{/notes}}
|
||||
|
||||
{{#allParams}}
|
||||
@param {{paramName}} {{description}}
|
||||
{{#allParams}}@param {{paramName}} {{description}}
|
||||
{{/allParams}}
|
||||
|
||||
return type: {{returnType}}
|
||||
return type: {{{returnType}}}
|
||||
*/
|
||||
-(NSNumber*) {{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}} {{#hasMore}}
|
||||
{{/hasMore}}{{/allParams}}
|
||||
{{#returnBaseType}}{{#hasParams}}
|
||||
completionHandler: {{/hasParams}}(void (^)({{returnType}} output, NSError* error))completionBlock;{{/returnBaseType}}
|
||||
completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock;{{/returnBaseType}}
|
||||
{{^returnBaseType}}{{#hasParams}}
|
||||
completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock;{{/returnBaseType}}
|
||||
|
||||
|
@ -25,11 +25,11 @@
|
||||
{{returnBaseType}}* d = [[{{{returnBaseType}}} alloc]initWithString: dict];
|
||||
{{/returnTypeIsPrimitive}}
|
||||
{{^returnTypeIsPrimitive}}
|
||||
{{{returnBaseType}}}* d = [[{{{returnBaseType}}} alloc]initWithValues: dict];
|
||||
{{{returnBaseType}}}* d = [[{{{returnBaseType}}} alloc] initWithDictionary:dict error:nil];
|
||||
{{/returnTypeIsPrimitive}}
|
||||
[objs addObject:d];
|
||||
}
|
||||
completionBlock(objs, nil);
|
||||
completionBlock(({{{returnType}}})objs, nil);
|
||||
}
|
||||
{{/returnBaseType}}
|
||||
{{/isListContainer}}
|
||||
|
@ -1,9 +1,9 @@
|
||||
{{^returnTypeIsPrimitive}}
|
||||
// comples response type
|
||||
return [client dictionary: requestUrl
|
||||
method: @"{{httpMethod}}"
|
||||
queryParams: queryParams
|
||||
body: bodyDictionary
|
||||
return [client dictionary: requestUrl
|
||||
method: @"{{httpMethod}}"
|
||||
queryParams: queryParams
|
||||
body: bodyDictionary
|
||||
headerParams: headerParams
|
||||
requestContentType: requestContentType
|
||||
responseContentType: responseContentType
|
||||
@ -15,9 +15,9 @@
|
||||
}
|
||||
{{#returnType}}{{returnType}} result = nil;
|
||||
if (data) {
|
||||
result = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc] {{#returnContainer}}{{#isMapContainer}}initWithDictionary{{/isMapContainer}}{{#isListContainer}}initWithValues{{/isListContainer}}{{/returnContainer}}{{^returnContainer}}initWithValues {{/returnContainer}}: data];
|
||||
result = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc] {{#returnContainer}}{{#isMapContainer}}initWithDictionary{{/isMapContainer}}{{#isListContainer}} initWithDictionary{{/isListContainer}}{{/returnContainer}}{{^returnContainer}} initWithDictionary{{/returnContainer}}:data error:nil];
|
||||
}
|
||||
{{#returnType}}completionBlock(result , nil);{{/returnType}}
|
||||
{{/returnType}}
|
||||
}];
|
||||
{{/returnTypeIsPrimitive}}
|
||||
{{/returnTypeIsPrimitive}}
|
||||
|
@ -1,81 +1,24 @@
|
||||
{{#models}}
|
||||
{{#model}}
|
||||
#import "SWGDate.h"
|
||||
#import "{{classname}}.h"
|
||||
|
||||
@implementation {{classname}}
|
||||
|
||||
-(id){{#vars}}{{name}}: ({{datatype}}) {{name}}
|
||||
{{/vars}}
|
||||
{{newline}}{
|
||||
{{#vars}}_{{name}} = {{name}};
|
||||
{{/vars}}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
-(id) initWithValues:(NSDictionary*)dict
|
||||
|
||||
+ (JSONKeyMapper *)keyMapper
|
||||
{
|
||||
self = [super init];
|
||||
if(self) {
|
||||
{{#vars}}{{#isPrimitiveType}}_{{name}} = dict[@"{{baseName}}"];{{/isPrimitiveType}}
|
||||
{{#complexType}}
|
||||
id {{name}}_dict = dict[@"{{baseName}}"];
|
||||
{{#isContainer}}
|
||||
if([{{name}}_dict isKindOfClass:[NSArray class]]) {
|
||||
NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[(NSArray*){{name}}_dict count]];
|
||||
if([(NSArray*){{name}}_dict count] > 0) {
|
||||
for (NSDictionary* dict in (NSArray*){{name}}_dict) {
|
||||
{{{complexType}}}* d = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{complexType}}}{{/instantiationType}} alloc] initWithValues:dict];
|
||||
[objs addObject:d];
|
||||
}
|
||||
_{{{name}}} = [[NSArray alloc] initWithArray:objs];
|
||||
}
|
||||
else
|
||||
_{{name}} = [[NSArray alloc] init];
|
||||
}
|
||||
else {
|
||||
_{{name}} = [[NSArray alloc] init];
|
||||
}
|
||||
{{/isContainer}}{{#isNotContainer}}
|
||||
if({{name}}_dict != nil)
|
||||
_{{name}} = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{complexType}}} {{/instantiationType}} alloc]{{setter}}:{{name}}_dict];
|
||||
{{/isNotContainer}}
|
||||
{{/complexType}}
|
||||
{{/vars}}{{newline}}
|
||||
}
|
||||
return self;
|
||||
return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }];
|
||||
}
|
||||
|
||||
-(NSDictionary*) asDictionary {
|
||||
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
|
||||
{{#vars}}
|
||||
{{#complexType}}
|
||||
if(_{{name}} != nil){
|
||||
if([_{{name}} isKindOfClass:[NSArray class]]){
|
||||
NSMutableArray * array = [[NSMutableArray alloc] init];
|
||||
for( {{complexType}} *{{name}} in (NSArray*)_{{name}}) {
|
||||
[array addObject:[(SWGObject*){{name}} asDictionary]];
|
||||
}
|
||||
dict[@"{{name}}"] = array;
|
||||
}
|
||||
else if(_{{name}} && [_{{name}} isKindOfClass:[SWGDate class]]) {
|
||||
NSString * dateString = [(SWGDate*)_{{name}} toString];
|
||||
if(dateString){
|
||||
dict[@"{{name}}"] = dateString;
|
||||
}
|
||||
}
|
||||
else {
|
||||
{{/complexType}}
|
||||
if(_{{name}} != nil) dict[@"{{baseName}}"] = {{#complexType}}[(SWGObject*){{/complexType}}_{{name}} {{#complexType}}asDictionary]{{/complexType}};
|
||||
{{#complexType}}
|
||||
}
|
||||
}
|
||||
{{/complexType}}
|
||||
{{/vars}}
|
||||
+ (BOOL)propertyIsOptional:(NSString *)propertyName
|
||||
{
|
||||
NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}];
|
||||
|
||||
NSDictionary* output = [dict copy];
|
||||
return output;
|
||||
if ([optionalProperties containsObject:propertyName]) {
|
||||
return YES;
|
||||
}
|
||||
else {
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
|
||||
{{/model}}
|
||||
|
@ -6,17 +6,17 @@
|
||||
{{#models}}
|
||||
{{#model}}
|
||||
|
||||
@protocol {{classname}}
|
||||
@end
|
||||
|
||||
@interface {{classname}} : SWGObject
|
||||
|
||||
{{#vars}}
|
||||
@property(nonatomic) {{datatype}} {{name}}; {{#description}}/* {{{description}}} {{#isNotRequired}}[optional]{{/isNotRequired}} */{{/description}}{{newline}}
|
||||
{{#description}}/* {{{description}}} {{^required}}[optional]{{/required}}
|
||||
*/{{/description}}
|
||||
@property(nonatomic) {{{ datatype }}} {{name}};
|
||||
{{/vars}}
|
||||
- (id) {{#vars}}{{name}}: ({{datatype}}) {{name}}{{#hasMore}}{{newline}} {{/hasMore}}{{^hasMore}};{{/hasMore}}
|
||||
{{/vars}}
|
||||
{{newline}}
|
||||
- (id) initWithValues: (NSDictionary*)dict;
|
||||
- (NSDictionary*) asDictionary;
|
||||
{{newline}}
|
||||
|
||||
@end
|
||||
{{/model}}
|
||||
{{/models}}
|
||||
{{/models}}
|
||||
|
@ -15,29 +15,26 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/* Autoload the model definition files */
|
||||
/**
|
||||
*
|
||||
* @param string $className the class to attempt to load
|
||||
*/
|
||||
function swagger_autoloader($className) {
|
||||
$currentDir = dirname(__FILE__);
|
||||
if (file_exists($currentDir . '/' . $className . '.php')) {
|
||||
include $currentDir . '/' . $className . '.php';
|
||||
} elseif (file_exists($currentDir . '/models/' . $className . '.php')) {
|
||||
include $currentDir . '/models/' . $className . '.php';
|
||||
}
|
||||
}
|
||||
spl_autoload_register('swagger_autoloader');
|
||||
|
||||
namespace {{invokerPackage}};
|
||||
|
||||
class APIClient {
|
||||
|
||||
public static $PATCH = "PATCH";
|
||||
public static $POST = "POST";
|
||||
public static $GET = "GET";
|
||||
public static $PUT = "PUT";
|
||||
public static $DELETE = "DELETE";
|
||||
|
||||
/*
|
||||
* @var string timeout (second) of the HTTP request, by default set to 0, no timeout
|
||||
*/
|
||||
protected $curl_timeout = 0;
|
||||
|
||||
/*
|
||||
* @var string user agent of the HTTP request, set to "PHP-Swagger" by default
|
||||
*/
|
||||
protected $user_agent = "PHP-Swagger";
|
||||
|
||||
/**
|
||||
* @param string $host the address of the API server
|
||||
* @param string $headerName a header to pass on requests
|
||||
@ -67,7 +64,7 @@ class APIClient {
|
||||
if (!is_numeric($seconds)) {
|
||||
throw new Exception('Timeout variable must be numeric.');
|
||||
}
|
||||
$this->curl_timout = $seconds;
|
||||
$this->curl_timeout = $seconds;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -97,15 +94,16 @@ class APIClient {
|
||||
$headers[] = $this->headerName . ": " . $this->headerValue;
|
||||
}
|
||||
|
||||
if (strpos($headers['Content-Type'], "multipart/form-data") < 0 and (is_object($postData) or is_array($postData))) {
|
||||
if ((isset($headerName['Content-Type']) and strpos($headerName['Content-Type'], "multipart/form-data") === FALSE) and (is_object($postData) or is_array($postData))) {
|
||||
$postData = json_encode($this->sanitizeForSerialization($postData));
|
||||
}
|
||||
|
||||
$url = $this->host . $resourcePath;
|
||||
|
||||
$curl = curl_init();
|
||||
if ($this->curl_timout) {
|
||||
curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timout);
|
||||
// set timeout, if needed
|
||||
if ($this->curl_timeout != 0) {
|
||||
curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timeout);
|
||||
}
|
||||
// return the result on success, rather than just TRUE
|
||||
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
|
||||
@ -133,11 +131,7 @@ class APIClient {
|
||||
curl_setopt($curl, CURLOPT_URL, $url);
|
||||
|
||||
// Set user agent
|
||||
if ($this->user_agent) {
|
||||
curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
|
||||
} else { // use PHP-Swagger as the default user agent
|
||||
curl_setopt($curl, CURLOPT_USERAGENT, 'PHP-Swagger');
|
||||
}
|
||||
curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
|
||||
|
||||
// Make the request
|
||||
$response = curl_exec($curl);
|
||||
@ -199,7 +193,7 @@ class APIClient {
|
||||
* @return string the serialized object
|
||||
*/
|
||||
public static function toPathValue($value) {
|
||||
return rawurlencode(toString($value));
|
||||
return rawurlencode(self::toString($value));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -214,7 +208,7 @@ class APIClient {
|
||||
if (is_array($object)) {
|
||||
return implode(',', $object);
|
||||
} else {
|
||||
return toString($object);
|
||||
return self::toString($object);
|
||||
}
|
||||
}
|
||||
|
||||
@ -226,7 +220,7 @@ class APIClient {
|
||||
* @return string the header string
|
||||
*/
|
||||
public static function toHeaderValue($value) {
|
||||
return toString($value);
|
||||
return self::toString($value);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -237,7 +231,7 @@ class APIClient {
|
||||
* @return string the form string
|
||||
*/
|
||||
public static function toFormValue($value) {
|
||||
return toString($value);
|
||||
return self::toString($value);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -288,14 +282,15 @@ class APIClient {
|
||||
$deserialized = $values;
|
||||
} elseif ($class == 'DateTime') {
|
||||
$deserialized = new \DateTime($data);
|
||||
} elseif (in_array($class, array('string', 'int', 'float', 'bool'))) {
|
||||
} elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool'))) {
|
||||
settype($data, $class);
|
||||
$deserialized = $data;
|
||||
} else {
|
||||
$class = "{{invokerPackage}}\\models\\".$class;
|
||||
$instance = new $class();
|
||||
foreach ($instance::$swaggerTypes as $property => $type) {
|
||||
if (isset($data->$property)) {
|
||||
$original_property_name = $instance::$attributeMap[$property];
|
||||
$original_property_name = $instance::$attributeMap[$property];
|
||||
if (isset($original_property_name)) {
|
||||
$instance->$property = self::deserialize($data->$original_property_name, $type);
|
||||
}
|
||||
}
|
||||
@ -307,20 +302,3 @@ class APIClient {
|
||||
|
||||
}
|
||||
|
||||
class APIClientException extends Exception {
|
||||
protected $response, $response_info;
|
||||
|
||||
public function __construct($message="", $code=0, $response_info=null, $response=null) {
|
||||
parent::__construct($message, $code);
|
||||
$this->response_info = $response_info;
|
||||
$this->response = $response;
|
||||
}
|
||||
|
||||
public function getResponse() {
|
||||
return $this->response;
|
||||
}
|
||||
|
||||
public function getResponseInfo() {
|
||||
return $this->response_info;
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user