forked from loafle/openapi-generator-original
Compare commits
389 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1d51266b3 | ||
|
|
b85c8bbe7f | ||
|
|
e8ae9178af | ||
|
|
12d4e812a6 | ||
|
|
07030e1f42 | ||
|
|
c04f947a85 | ||
|
|
d55aaffc48 | ||
|
|
b9514a40de | ||
|
|
ed43a38db2 | ||
|
|
2967cc3801 | ||
|
|
9c5153e8c8 | ||
|
|
0a4fc6a40f | ||
|
|
a717aba826 | ||
|
|
5c335beb60 | ||
|
|
8d6d1cb329 | ||
|
|
6b2035e353 | ||
|
|
3811a5a209 | ||
|
|
c1046cc87b | ||
|
|
2bb42a1147 | ||
|
|
1b4367ffba | ||
|
|
b4df8477d8 | ||
|
|
27c7e69fba | ||
|
|
5a5bb6edbf | ||
|
|
448462552f | ||
|
|
14cbc2d90d | ||
|
|
dfa2c22e0c | ||
|
|
a57588caa1 | ||
|
|
fad7246e05 | ||
|
|
a0c9296ee8 | ||
|
|
0c2e464c71 | ||
|
|
15236ef376 | ||
|
|
950bfff1c1 | ||
|
|
bba91c7e92 | ||
|
|
33c87e8e72 | ||
|
|
ba2ccf788c | ||
|
|
e114875f02 | ||
|
|
09346c761b | ||
|
|
f0e41bf43e | ||
|
|
9c75304832 | ||
|
|
02fd96a24a | ||
|
|
568ca26747 | ||
|
|
1e82fc5d24 | ||
|
|
d9f8fcb7a4 | ||
|
|
17ca7c4648 | ||
|
|
acf2c8cc9d | ||
|
|
43c88f51c6 | ||
|
|
60e5899dc3 | ||
|
|
f75312105d | ||
|
|
610143f4ad | ||
|
|
2cc9b10a1e | ||
|
|
f3ab28b92d | ||
|
|
660d336646 | ||
|
|
15c25c8277 | ||
|
|
b4d4fa1a43 | ||
|
|
d4ac668cd4 | ||
|
|
38e34e0dd6 | ||
|
|
9159892965 | ||
|
|
eda1a44fa3 | ||
|
|
40d512fe43 | ||
|
|
e73957e790 | ||
|
|
b773d40034 | ||
|
|
b6be19b266 | ||
|
|
1c0cb7f884 | ||
|
|
bc24e5e290 | ||
|
|
80259fbcc4 | ||
|
|
64292cdc9b | ||
|
|
df771b5a4d | ||
|
|
8b8e8d70f9 | ||
|
|
27dfa12335 | ||
|
|
13ee40a4b8 | ||
|
|
df9efe5734 | ||
|
|
f142474a54 | ||
|
|
084d448fd4 | ||
|
|
1385a157e9 | ||
|
|
fe3c3cc8bc | ||
|
|
97e44679d3 | ||
|
|
d5ad4c4ae7 | ||
|
|
6ac497d774 | ||
|
|
cd2c8f6527 | ||
|
|
d4b9a41786 | ||
|
|
93fef67c7e | ||
|
|
f72e5907bb | ||
|
|
01c956caba | ||
|
|
5f07fb0b03 | ||
|
|
f17968d5b3 | ||
|
|
055c4397e9 | ||
|
|
62a99115fc | ||
|
|
7483a06226 | ||
|
|
f265ce361a | ||
|
|
744952aee4 | ||
|
|
66591f567c | ||
|
|
03c48af9e6 | ||
|
|
3096c6c3ce | ||
|
|
cb2f1e1bb1 | ||
|
|
59140bd3f3 | ||
|
|
ce700b9421 | ||
|
|
761ab22f08 | ||
|
|
0ee39c67fe | ||
|
|
148b2daaa3 | ||
|
|
a927d679f0 | ||
|
|
a4ce6d7074 | ||
|
|
3739d2876e | ||
|
|
0c50d9807e | ||
|
|
5e83b6602e | ||
|
|
5ab425e82d | ||
|
|
b5be12a25b | ||
|
|
367f81d52d | ||
|
|
b10445f3f6 | ||
|
|
1e7862a466 | ||
|
|
943efce971 | ||
|
|
e7675e48ed | ||
|
|
63efc4f442 | ||
|
|
a5c92be360 | ||
|
|
8de8f48679 | ||
|
|
63fae85ff4 | ||
|
|
8f6afda99a | ||
|
|
510254e5a3 | ||
|
|
9981daad61 | ||
|
|
c1824b5387 | ||
|
|
517c0a4f52 | ||
|
|
cab50ccb59 | ||
|
|
e51f548807 | ||
|
|
8a214838e5 | ||
|
|
37118cab47 | ||
|
|
e6d7517e63 | ||
|
|
90db8e2147 | ||
|
|
65883a5d85 | ||
|
|
7383520639 | ||
|
|
49e9c74324 | ||
|
|
492ab20c00 | ||
|
|
92621f2f2d | ||
|
|
f2ce5ef273 | ||
|
|
836f7ecb95 | ||
|
|
0dcd307333 | ||
|
|
c2b3e68f8c | ||
|
|
11c8e2268a | ||
|
|
a12cc1c544 | ||
|
|
27e1b1c4b2 | ||
|
|
a62cd193ad | ||
|
|
0686a91690 | ||
|
|
4f6d5f6265 | ||
|
|
99271e77ab | ||
|
|
c9a2a14da5 | ||
|
|
236a1147b7 | ||
|
|
7eba8670e3 | ||
|
|
bdd1d1621f | ||
|
|
98c8f867e5 | ||
|
|
bfb35aa3ee | ||
|
|
6ab51bcb4e | ||
|
|
1c547e9598 | ||
|
|
19c05eefab | ||
|
|
3d12c8847f | ||
|
|
5d6d563a8e | ||
|
|
442be8624c | ||
|
|
287bb7d936 | ||
|
|
ddb1d6e0d3 | ||
|
|
8b98a92805 | ||
|
|
8b4a077f8a | ||
|
|
3d53cfc298 | ||
|
|
fb2ab79455 | ||
|
|
731bfc1fc6 | ||
|
|
ae52a62c09 | ||
|
|
9ba1398831 | ||
|
|
a4690d76db | ||
|
|
fe11b064af | ||
|
|
a2dc767559 | ||
|
|
93e19e48db | ||
|
|
fbe069cf5c | ||
|
|
20add5b58e | ||
|
|
b7c2c3448e | ||
|
|
f577345b14 | ||
|
|
bf46da7c14 | ||
|
|
d2f5b9ea65 | ||
|
|
e8052f0505 | ||
|
|
be373f88d4 | ||
|
|
ceffa10ab7 | ||
|
|
b36f3c98ca | ||
|
|
f459982560 | ||
|
|
56104566fc | ||
|
|
85463f049c | ||
|
|
30acfc1869 | ||
|
|
2ce0049ce4 | ||
|
|
e82ecf695d | ||
|
|
dc9a00809c | ||
|
|
31418b3936 | ||
|
|
db14a3fd05 | ||
|
|
de0e108d27 | ||
|
|
b8cd52aa07 | ||
|
|
16403950d5 | ||
|
|
8ba444141e | ||
|
|
fb3e44ecc4 | ||
|
|
8107162540 | ||
|
|
ee096569c4 | ||
|
|
81e1fd53e2 | ||
|
|
07237f8eb9 | ||
|
|
9442e23fd9 | ||
|
|
fe82d7dc05 | ||
|
|
915fcf9b92 | ||
|
|
31e8d58b1d | ||
|
|
87b85e5b93 | ||
|
|
823ac04abb | ||
|
|
0cf1c3c74a | ||
|
|
fd602af180 | ||
|
|
048bea6249 | ||
|
|
601a519cb6 | ||
|
|
f1f9805a01 | ||
|
|
62d28ebca5 | ||
|
|
c46f3f9ee4 | ||
|
|
f008b75e99 | ||
|
|
38204b2237 | ||
|
|
d71785470b | ||
|
|
b5a4d5be04 | ||
|
|
f085860eb1 | ||
|
|
8323fdf8e8 | ||
|
|
0c3f06604d | ||
|
|
e782ea2c05 | ||
|
|
9062016bf0 | ||
|
|
2301e604b3 | ||
|
|
34eab98ce4 | ||
|
|
00c1018d79 | ||
|
|
c36e5a96fe | ||
|
|
c024a4c099 | ||
|
|
92e5574ec1 | ||
|
|
cdf8648d3b | ||
|
|
de56f76284 | ||
|
|
ae1d43dc84 | ||
|
|
531e2d7032 | ||
|
|
32fe6b0333 | ||
|
|
75714ac518 | ||
|
|
8262d30202 | ||
|
|
d332cdf200 | ||
|
|
f6c18cd50f | ||
|
|
ab8d62214a | ||
|
|
a149bb9120 | ||
|
|
02283fae46 | ||
|
|
c82b31aa61 | ||
|
|
37303745df | ||
|
|
e5357df67a | ||
|
|
c109c11bea | ||
|
|
3a8c798596 | ||
|
|
9311bdf972 | ||
|
|
925caa223a | ||
|
|
95e7265bd7 | ||
|
|
93afc3bd95 | ||
|
|
cbdb31048e | ||
|
|
6b1f176a66 | ||
|
|
f2ee9b39e9 | ||
|
|
b6e5c55817 | ||
|
|
963d92e23f | ||
|
|
081757c592 | ||
|
|
ac78c15fbf | ||
|
|
dd78de1ed8 | ||
|
|
64fbcb6045 | ||
|
|
86c6892eb6 | ||
|
|
9cfbd8bde0 | ||
|
|
1e1d193556 | ||
|
|
f8a5e900f8 | ||
|
|
d0dcb2fb43 | ||
|
|
bb45790375 | ||
|
|
369689d001 | ||
|
|
df39fe5d08 | ||
|
|
b73340ab83 | ||
|
|
a1d02785af | ||
|
|
4f32e9dbff | ||
|
|
b6ca69f57a | ||
|
|
62992c2de1 | ||
|
|
b2da6dc8a2 | ||
|
|
c96853d5aa | ||
|
|
c215d8ab91 | ||
|
|
46d1950fbd | ||
|
|
03b764d404 | ||
|
|
a8aebec9ba | ||
|
|
fd72ff56bf | ||
|
|
ebec85fd54 | ||
|
|
fd792ef180 | ||
|
|
486186e042 | ||
|
|
8111d4e909 | ||
|
|
fc9d632522 | ||
|
|
d580d294b6 | ||
|
|
e9227ad7e5 | ||
|
|
156ec2a2dd | ||
|
|
186310b553 | ||
|
|
bcdee4e038 | ||
|
|
6bc8de1230 | ||
|
|
b8166f283a | ||
|
|
ad7a5967ff | ||
|
|
a0dc2097eb | ||
|
|
24842d4a29 | ||
|
|
0854ca5ce5 | ||
|
|
6ca34e362d | ||
|
|
470ba201d8 | ||
|
|
fc52ab972b | ||
|
|
7aca1cfb3f | ||
|
|
d9b247f302 | ||
|
|
c1e45a5931 | ||
|
|
4748af4d59 | ||
|
|
575967b5de | ||
|
|
6c57d6a76e | ||
|
|
56ff34dc47 | ||
|
|
5b72653d7f | ||
|
|
0a949e26f0 | ||
|
|
5347915c12 | ||
|
|
d0edb836ac | ||
|
|
c75cd55e2c | ||
|
|
911be4360a | ||
|
|
939b4c713d | ||
|
|
e6abc2a881 | ||
|
|
b2977cd29b | ||
|
|
da6f0eec84 | ||
|
|
7555dda2bf | ||
|
|
941f6e7757 | ||
|
|
1887170dad | ||
|
|
b2cfb77222 | ||
|
|
5d77321dca | ||
|
|
f20522a586 | ||
|
|
17435212ed | ||
|
|
6207c2b5e9 | ||
|
|
b6f7f85baa | ||
|
|
9c77742046 | ||
|
|
e9d0619358 | ||
|
|
7c23eedf07 | ||
|
|
27c6af3491 | ||
|
|
dc5ee9dcf5 | ||
|
|
07ff6a2278 | ||
|
|
dce9a81536 | ||
|
|
156055fdd5 | ||
|
|
3a5c03c778 | ||
|
|
9ce4156e4c | ||
|
|
f82afe0026 | ||
|
|
c3bb458ed9 | ||
|
|
5c2c8e1d76 | ||
|
|
ced95d658f | ||
|
|
a724cd0780 | ||
|
|
6b823b88d9 | ||
|
|
8fb180133a | ||
|
|
e877abf153 | ||
|
|
dd0ccff58a | ||
|
|
a793d5c6cc | ||
|
|
d313d4da3f | ||
|
|
dfc8f7c60f | ||
|
|
c15ac0b6d4 | ||
|
|
f9a16d856c | ||
|
|
5713dce00a | ||
|
|
23e848b437 | ||
|
|
5b01e78a72 | ||
|
|
eb68d0bdbd | ||
|
|
05297e05a5 | ||
|
|
1a0d2d19f5 | ||
|
|
292fc99bd5 | ||
|
|
b339db65be | ||
|
|
e5c70d5961 | ||
|
|
69be95d586 | ||
|
|
c82dfa3a64 | ||
|
|
4fd4c17036 | ||
|
|
4bd227271a | ||
|
|
5c31d68fee | ||
|
|
bfc1ed3081 | ||
|
|
1c7c39c1ab | ||
|
|
4ce0a65ad5 | ||
|
|
784afee7b7 | ||
|
|
f89e04d210 | ||
|
|
12531943d0 | ||
|
|
3061cd8277 | ||
|
|
686f3656c5 | ||
|
|
9ae106affd | ||
|
|
2550539495 | ||
|
|
06164cdc51 | ||
|
|
583a932fba | ||
|
|
fdd485608f | ||
|
|
0307d3818a | ||
|
|
9a473ceae6 | ||
|
|
12365b9591 | ||
|
|
c832889db8 | ||
|
|
39487d9917 | ||
|
|
aa37542411 | ||
|
|
279f43d697 | ||
|
|
fee6de5974 | ||
|
|
5fa98b12b8 | ||
|
|
ff94196295 | ||
|
|
0195749f3b | ||
|
|
577aad3364 | ||
|
|
05c6cc756c | ||
|
|
bd91922072 | ||
|
|
ec995838fb | ||
|
|
4198779b5b | ||
|
|
711d2c8cf4 | ||
|
|
42ad403e5e | ||
|
|
527fca5a8b | ||
|
|
60bd56b91c |
@@ -1,3 +1,4 @@
|
||||
sudo: false
|
||||
language: java
|
||||
script: mvn verify
|
||||
jdk:
|
||||
|
||||
89
README.md
89
README.md
@@ -16,9 +16,9 @@ Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additi
|
||||
## Compatability
|
||||
The Swagger Specification has undergone 3 revisions since initial creation in 2010. The swagger-codegen project has the following compatibilies with the swagger specification:
|
||||
|
||||
Swagger Codegen Version | Release Date | Swagger Spec compatability | Notes
|
||||
Swagger Codegen Version | Release Date | Swagger Spec compatibility | Notes
|
||||
----------------------- | ------------ | -------------------------- | -----
|
||||
2.1.0-M1 | 2015-02-16 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.0-M1](https://github.com/swagger-api/swagger-codegen/tree/v2.1.0-M1)
|
||||
2.1.0-M2 | 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)
|
||||
|
||||
@@ -46,29 +46,47 @@ You can build a client against the swagger sample [petstore](http://petstore.swa
|
||||
This will run the generator with this command:
|
||||
|
||||
```
|
||||
java -jar modules/swagger-codegen-distribution/target/swagger-codegen-distribution-2.1.0-M1.jar \
|
||||
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
|
||||
-i http://petstore.swagger.io/v2/swagger.json \
|
||||
-l java \
|
||||
-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, java, jaxrs, nodejs, objc, scalatra,
|
||||
scala, dynamic-html, html, swagger, tizen, php,
|
||||
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,7 +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 `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 -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.
|
||||
|
||||
### Where is Javascript???
|
||||
See our [javascript library](http://github.com/swagger-api/swagger-js)--it's completely dynamic and doesn't require
|
||||
@@ -116,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
|
||||
```
|
||||
|
||||
@@ -149,7 +182,7 @@ public class MyObjcCodegen extends ObjcClientCodegen {
|
||||
and specify the `classname` when running the generator:
|
||||
|
||||
```
|
||||
-i com.mycompany.swagger.codegen.MyObjcCodegen
|
||||
-l com.mycompany.swagger.codegen.MyObjcCodegen
|
||||
```
|
||||
|
||||
Your subclass will now be loaded and overrides the `PREFIX` value in the superclass.
|
||||
@@ -189,7 +222,7 @@ You can also use the codegen to generate a server for a couple different framewo
|
||||
|
||||
### node.js
|
||||
```
|
||||
java -jar modules/swagger-codegen-distribution/target/swagger-codegen-distribution-2.1.0-M1.jar \
|
||||
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
|
||||
-i http://petstore.swagger.io/v2/swagger.json \
|
||||
-l nodejs \
|
||||
-o samples/server/petstore/nodejs
|
||||
@@ -201,7 +234,7 @@ java -jar modules/swagger-codegen-distribution/target/swagger-codegen-distributi
|
||||
|
||||
### scala scalatra
|
||||
```
|
||||
java -jar modules/swagger-codegen-distribution/target/swagger-codegen-distribution-2.1.0-M1.jar \
|
||||
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
|
||||
-i http://petstore.swagger.io/v2/swagger.json \
|
||||
-l scalatra \
|
||||
-o samples/server/petstore/scalatra
|
||||
@@ -210,12 +243,20 @@ java -jar modules/swagger-codegen-distribution/target/swagger-codegen-distributi
|
||||
### java jax-rs
|
||||
|
||||
```
|
||||
java -jar modules/swagger-codegen-distribution/target/swagger-codegen-distribution-2.1.0-M1.jar \
|
||||
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
|
||||
-i http://petstore.swagger.io/v2/swagger.json \
|
||||
-l jaxrs \
|
||||
-o samples/server/petstore/jaxrs
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
val version = scala.util.Properties.scalaPropOrElse("version.number", "unknown").toString match {
|
||||
case s if s startsWith "2.10" => "2.10"
|
||||
case s if s startsWith "2.11" => "2.11"
|
||||
case e: String => e
|
||||
}
|
||||
println(version)
|
||||
@@ -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
|
||||
|
||||
@@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
root=./modules/swagger-codegen-distribution/pom.xml
|
||||
|
||||
# gets version of swagger-codegen
|
||||
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
|
||||
|
||||
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
@@ -31,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="$@ -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
|
||||
|
||||
@@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
root=./modules/swagger-codegen-distribution/pom.xml
|
||||
|
||||
# gets version of swagger-codegen
|
||||
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
|
||||
|
||||
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
@@ -31,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="$@ -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l android -o samples/client/wordnik/android-java"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l android -o samples/client/wordnik/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
|
||||
@@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
root=./modules/swagger-codegen-distribution/pom.xml
|
||||
|
||||
# gets version of swagger-codegen
|
||||
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
|
||||
|
||||
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
@@ -31,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="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l dynamic-html -o samples/dynamic-html"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l dynamic-html -o samples/dynamic-html"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
||||
@@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
root=./modules/swagger-codegen-distribution/pom.xml
|
||||
|
||||
# gets version of swagger-codegen
|
||||
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
|
||||
|
||||
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
@@ -31,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="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l html -o samples/html"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l html -o samples/html"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
||||
@@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
root=./modules/swagger-codegen-distribution/pom.xml
|
||||
|
||||
# gets version of swagger-codegen
|
||||
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
|
||||
|
||||
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
@@ -31,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="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -o samples/client/petstore/java"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -o samples/client/petstore/java"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
||||
@@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
root=./modules/swagger-codegen-distribution/pom.xml
|
||||
|
||||
# gets version of swagger-codegen
|
||||
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
|
||||
|
||||
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
@@ -31,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="$@ -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l java -o samples/client/wordnik/java"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l java -o samples/client/wordnik/java"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
||||
@@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
root=./modules/swagger-codegen-distribution/pom.xml
|
||||
|
||||
# gets version of swagger-codegen
|
||||
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
|
||||
|
||||
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
@@ -31,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="$@ -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
|
||||
|
||||
@@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
root=./modules/swagger-codegen-distribution/pom.xml
|
||||
|
||||
# gets version of swagger-codegen
|
||||
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
|
||||
|
||||
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
@@ -31,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="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l nodejs -o samples/server/petstore/nodejs"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l nodejs -o samples/server/petstore/nodejs"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
java $JAVA_OPTS -Dservice -jar $executable $ags
|
||||
|
||||
@@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
root=./modules/swagger-codegen-distribution/pom.xml
|
||||
|
||||
# gets version of swagger-codegen
|
||||
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
|
||||
|
||||
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
@@ -31,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="$@ -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 $JAVA_OPTS -jar $executable $ags
|
||||
java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags
|
||||
|
||||
@@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
root=./modules/swagger-codegen-distribution/pom.xml
|
||||
|
||||
# gets version of swagger-codegen
|
||||
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
|
||||
|
||||
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
@@ -31,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="$@ -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l objc -o samples/client/wordnik/objc"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l objc -o samples/client/wordnik/objc"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
||||
@@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
root=./modules/swagger-codegen-distribution/pom.xml
|
||||
|
||||
# gets version of swagger-codegen
|
||||
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
|
||||
|
||||
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
@@ -31,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="$@ -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
|
||||
|
||||
@@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
root=./modules/swagger-codegen-distribution/pom.xml
|
||||
|
||||
# gets version of swagger-codegen
|
||||
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
|
||||
|
||||
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
@@ -31,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="$@ -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/ruby-petstore.sh
Executable file
31
bin/ruby-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/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
|
||||
31
bin/scala-async-petstore.sh
Executable file
31
bin/scala-async-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/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
|
||||
@@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
root=./modules/swagger-codegen-distribution/pom.xml
|
||||
|
||||
# gets version of swagger-codegen
|
||||
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
|
||||
|
||||
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
@@ -31,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="$@ -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
|
||||
|
||||
@@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
root=./modules/swagger-codegen-distribution/pom.xml
|
||||
|
||||
# gets version of swagger-codegen
|
||||
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
|
||||
|
||||
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
@@ -31,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="$@ -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l scala -o samples/client/wordnik/scala"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l scala -o samples/client/wordnik/scala"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
||||
@@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
root=./modules/swagger-codegen-distribution/pom.xml
|
||||
|
||||
# gets version of swagger-codegen
|
||||
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
|
||||
|
||||
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
@@ -31,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="$@ -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
|
||||
@@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
root=./modules/swagger-codegen-distribution/pom.xml
|
||||
|
||||
# gets version of swagger-codegen
|
||||
version=$(sed '/<project>/,/<\/project>/d;/<version>/!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*<version>\([^<]*\)</version>.*,\1,g')
|
||||
|
||||
executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar"
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
@@ -31,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="$@ -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
|
||||
|
||||
95
modules/swagger-codegen-cli/pom.xml
Normal file
95
modules/swagger-codegen-cli/pom.xml
Normal file
@@ -0,0 +1,95 @@
|
||||
<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">
|
||||
<parent>
|
||||
<groupId>com.wordnik</groupId>
|
||||
<artifactId>swagger-codegen-project</artifactId>
|
||||
<version>2.1.0-M2</version>
|
||||
<relativePath>../..</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>swagger-codegen-cli</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>swagger-codegen (executable)</name>
|
||||
|
||||
<build>
|
||||
<finalName>swagger-codegen-cli</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>com.wordnik.swagger.codegen.SwaggerCodegen</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>2.3</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>reduced-pom</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<minimizeJar>false</minimizeJar>
|
||||
<createDependencyReducedPom>true</createDependencyReducedPom>
|
||||
<dependencyReducedPomLocation>
|
||||
${java.io.tmpdir}/dependency-reduced-pom.xml
|
||||
</dependencyReducedPomLocation>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>process-resources</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.wordnik</groupId>
|
||||
<artifactId>swagger-codegen</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--https://github.com/airlift/airline-->
|
||||
<dependency>
|
||||
<groupId>io.airlift</groupId>
|
||||
<artifactId>airline</artifactId>
|
||||
<version>0.7</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.googlecode.lambdaj</groupId>
|
||||
<artifactId>lambdaj</artifactId>
|
||||
<version>2.3.3</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>${slf4j-version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.wordnik.swagger.codegen;
|
||||
|
||||
import com.wordnik.swagger.codegen.cmd.Generate;
|
||||
import com.wordnik.swagger.codegen.cmd.Langs;
|
||||
import com.wordnik.swagger.codegen.cmd.Meta;
|
||||
import io.airlift.airline.Cli;
|
||||
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 {
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
Cli.CliBuilder<Runnable> builder = Cli.<Runnable>builder("swagger")
|
||||
.withDescription("Swagger code generator CLI. More info on swagger.io")
|
||||
.withDefaultCommand(Langs.class)
|
||||
.withCommands(
|
||||
Generate.class,
|
||||
Meta.class,
|
||||
Langs.class,
|
||||
Help.class
|
||||
);
|
||||
|
||||
builder.build().parse(args).run();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.wordnik.swagger.codegen.cmd;
|
||||
|
||||
import com.wordnik.swagger.codegen.ClientOptInput;
|
||||
import com.wordnik.swagger.codegen.ClientOpts;
|
||||
import com.wordnik.swagger.codegen.CodegenConfig;
|
||||
import com.wordnik.swagger.codegen.DefaultGenerator;
|
||||
import com.wordnik.swagger.models.Swagger;
|
||||
import io.airlift.airline.Command;
|
||||
import io.airlift.airline.Option;
|
||||
import io.swagger.parser.SwaggerParser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ServiceLoader;
|
||||
|
||||
import static java.util.ServiceLoader.load;
|
||||
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
|
||||
|
||||
/**
|
||||
* User: lanwen
|
||||
* Date: 24.03.15
|
||||
* Time: 20:22
|
||||
*/
|
||||
|
||||
@Command(name = "generate", description = "Generate code with chosen lang")
|
||||
public class Generate implements Runnable {
|
||||
|
||||
public static final Logger LOG = LoggerFactory.getLogger(Generate.class);
|
||||
|
||||
public static final String TEMPLATE_DIR_PARAM = "templateDir";
|
||||
|
||||
@Option(name = {"-v", "--verbose"}, description = "verbose mode")
|
||||
private boolean verbose;
|
||||
|
||||
@Option(name = {"-l", "--lang"}, title = "language", required = true,
|
||||
description = "client language to generate (maybe class name in classpath, required)")
|
||||
private String lang;
|
||||
|
||||
@Option(name = {"-o", "--output"}, title = "output directory",
|
||||
description = "where to write the generated files (current dir by default)")
|
||||
private String output = "";
|
||||
|
||||
@Option(name = {"-i", "--input-spec"}, title = "spec file", required = true,
|
||||
description = "location of the swagger spec, as URL or file (required)")
|
||||
private String spec;
|
||||
|
||||
@Option(name = {"-t", "--template-dir"}, title = "template directory",
|
||||
description = "folder containing the template files")
|
||||
private String templateDir;
|
||||
|
||||
@Option(name = {"-a", "--auth"}, title = "authorization",
|
||||
description = "adds authorization headers when fetching the swagger definitions remotely. " +
|
||||
"Pass in a URL-encoded string of name:header with a comma separating multiple values")
|
||||
private String auth;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
verbosed(verbose);
|
||||
|
||||
ClientOptInput input = new ClientOptInput();
|
||||
|
||||
if (isNotEmpty(auth)) {
|
||||
input.setAuth(auth);
|
||||
}
|
||||
|
||||
CodegenConfig config = forName(lang);
|
||||
config.setOutputDir(new File(output).getAbsolutePath());
|
||||
|
||||
if (null != templateDir) {
|
||||
config.additionalProperties().put(TEMPLATE_DIR_PARAM, new File(templateDir).getAbsolutePath());
|
||||
}
|
||||
|
||||
input.setConfig(config);
|
||||
|
||||
Swagger swagger = new SwaggerParser().read(spec, input.getAuthorizationValues(), true);
|
||||
new DefaultGenerator().opts(input.opts(new ClientOpts()).swagger(swagger)).generate();
|
||||
}
|
||||
|
||||
/**
|
||||
* If true parameter, adds system properties which enables debug mode in generator
|
||||
* @param verbose - if true, enables debug mode
|
||||
*/
|
||||
private void verbosed(boolean verbose) {
|
||||
if (!verbose) {
|
||||
return;
|
||||
}
|
||||
LOG.info("\nVERBOSE MODE: ON. Additional debug options are injected" +
|
||||
"\n - [debugSwagger] prints the swagger specification as interpreted by the codegen" +
|
||||
"\n - [debugModels] prints models passed to the template engine" +
|
||||
"\n - [debugOperations] prints operations passed to the template engine" +
|
||||
"\n - [debugSupportingFiles] prints additional data passed to the template engine");
|
||||
|
||||
System.setProperty("debugSwagger", "");
|
||||
System.setProperty("debugModels", "");
|
||||
System.setProperty("debugOperations", "");
|
||||
System.setProperty("debugSupportingFiles", "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to load config class with SPI first, then with class name directly from classpath
|
||||
* @param name name of config, or full qualified class name in classpath
|
||||
* @return config class
|
||||
*/
|
||||
private static CodegenConfig forName(String name) {
|
||||
ServiceLoader<CodegenConfig> loader = load(CodegenConfig.class);
|
||||
for (CodegenConfig config : loader) {
|
||||
if (config.getName().equals(name)) {
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
||||
// else try to load directly
|
||||
try {
|
||||
return (CodegenConfig) Class.forName(name).newInstance();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Can't load config class with name ".concat(name), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.wordnik.swagger.codegen.cmd;
|
||||
|
||||
import ch.lambdaj.collection.LambdaIterable;
|
||||
import com.wordnik.swagger.codegen.CodegenConfig;
|
||||
import io.airlift.airline.Command;
|
||||
|
||||
import static ch.lambdaj.Lambda.on;
|
||||
import static ch.lambdaj.collection.LambdaCollections.with;
|
||||
import static java.util.ServiceLoader.load;
|
||||
|
||||
/**
|
||||
* User: lanwen
|
||||
* Date: 24.03.15
|
||||
* Time: 20:25
|
||||
*/
|
||||
@Command(name = "langs", description = "Shows available langs")
|
||||
public class Langs implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
LambdaIterable<String> langs = with(load(CodegenConfig.class)).extract(on(CodegenConfig.class).getName());
|
||||
System.out.printf("Available languages: %s%n", langs);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package com.wordnik.swagger.codegen.cmd;
|
||||
|
||||
import ch.lambdaj.function.convert.Converter;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.samskivert.mustache.Mustache;
|
||||
import com.wordnik.swagger.codegen.DefaultGenerator;
|
||||
import com.wordnik.swagger.codegen.SupportingFile;
|
||||
import io.airlift.airline.Command;
|
||||
import io.airlift.airline.Option;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static ch.lambdaj.collection.LambdaCollections.with;
|
||||
import static com.google.common.base.Joiner.on;
|
||||
|
||||
/**
|
||||
* User: lanwen
|
||||
* Date: 24.03.15
|
||||
* Time: 20:22
|
||||
*/
|
||||
|
||||
@Command(name = "meta", description = "MetaGenerator. Generator for creating a new template set " +
|
||||
"and configuration for Codegen. The output will be based on the language you " +
|
||||
"specify, and includes default templates to include.")
|
||||
public class Meta implements Runnable {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(Meta.class);
|
||||
|
||||
private static final String TEMPLATE_DIR_CLASSPATH = "codegen";
|
||||
private static final String MUSTACHE_EXTENSION = ".mustache";
|
||||
|
||||
@Option(name = {"-o", "--output"}, title = "output directory",
|
||||
description = "where to write the generated files (current dir by default)")
|
||||
private String outputFolder = "";
|
||||
|
||||
@Option(name = {"-n", "--name"}, title = "name",
|
||||
description = "the human-readable name of the generator")
|
||||
private String name = "default";
|
||||
|
||||
@Option(name = {"-p", "--package"}, title = "package",
|
||||
description = "the package to put the main class into (defaults to com.wordnik.swagger.codegen)")
|
||||
private String targetPackage = "com.wordnik.swagger.codegen";
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
final File targetDir = new File(outputFolder);
|
||||
LOG.info("writing to folder [{}]", targetDir.getAbsolutePath());
|
||||
|
||||
String mainClass = StringUtils.capitalize(name) + "Generator";
|
||||
|
||||
List<SupportingFile> supportingFiles = ImmutableList.of(
|
||||
new SupportingFile("pom.mustache", "", "pom.xml"),
|
||||
new SupportingFile("generatorClass.mustache",
|
||||
on(File.separator).join("src/main/java", asPath(targetPackage)), mainClass.concat(".java")),
|
||||
new SupportingFile("README.mustache", "", "README.md"),
|
||||
new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache"),
|
||||
new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache"),
|
||||
new SupportingFile("services.mustache",
|
||||
"src/main/resources/META-INF/services", "com.wordnik.swagger.codegen.CodegenConfig")
|
||||
);
|
||||
|
||||
Map<String, Object> data = new ImmutableMap.Builder<String, Object>()
|
||||
.put("generatorPackage", targetPackage)
|
||||
.put("generatorClass", mainClass)
|
||||
.put("name", name)
|
||||
.put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass).build();
|
||||
|
||||
|
||||
with(supportingFiles).convert(processFiles(targetDir, data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Converter method to process supporting files: execute with mustache,
|
||||
* or simply copy to destination directory
|
||||
* @param targetDir - destination directory
|
||||
* @param data - map with additional params needed to process templates
|
||||
* @return converter object to pass to lambdaj
|
||||
*/
|
||||
private Converter<SupportingFile, File> processFiles(final File targetDir, final Map<String, Object> data) {
|
||||
return new Converter<SupportingFile, File>() {
|
||||
private DefaultGenerator generator = new DefaultGenerator();
|
||||
|
||||
@Override
|
||||
public File convert(SupportingFile support) {
|
||||
try {
|
||||
File destinationFolder = new File(new File(targetDir.getAbsolutePath()), support.folder);
|
||||
File outputFile = new File(destinationFolder, support.destinationFilename);
|
||||
|
||||
String template = generator
|
||||
.readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.templateFile).getPath());
|
||||
String formatted = template;
|
||||
|
||||
if (support.templateFile.endsWith(MUSTACHE_EXTENSION)) {
|
||||
LOG.info("writing file to {}", outputFile.getAbsolutePath());
|
||||
formatted = Mustache.compiler().withLoader(loader(generator))
|
||||
.defaultValue("")
|
||||
.compile(template)
|
||||
.execute(data);
|
||||
} else {
|
||||
LOG.info("copying file to {}", outputFile.getAbsolutePath());
|
||||
}
|
||||
|
||||
FileUtils.writeStringToFile(outputFile, formatted);
|
||||
return outputFile;
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Can't generate project", e);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates mustache loader for template using classpath loader
|
||||
* @param generator - class with reader getter
|
||||
* @return loader for template
|
||||
*/
|
||||
private Mustache.TemplateLoader loader(final DefaultGenerator generator) {
|
||||
return new Mustache.TemplateLoader() {
|
||||
public Reader getTemplate(String name) {
|
||||
return generator.getTemplateReader(TEMPLATE_DIR_CLASSPATH
|
||||
+ File.separator + name.concat(MUSTACHE_EXTENSION));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts package name to path on file system
|
||||
* @param packageName - package name to convert
|
||||
* @return relative path
|
||||
*/
|
||||
private String asPath(String packageName) {
|
||||
return packageName.replace(".", File.separator);
|
||||
}
|
||||
}
|
||||
12
modules/swagger-codegen-cli/src/main/resources/logback.xml
Normal file
12
modules/swagger-codegen-cli/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<layout class="ch.qos.logback.classic.PatternLayout">
|
||||
<Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
|
||||
</layout>
|
||||
</appender>
|
||||
<logger name="com.wordnik" level="debug"/>
|
||||
<root level="error">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -1,62 +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">
|
||||
<parent>
|
||||
<groupId>com.wordnik</groupId>
|
||||
<artifactId>swagger-codegen-project</artifactId>
|
||||
<version>2.1.0-M1</version>
|
||||
<relativePath>../..</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.wordnik</groupId>
|
||||
<artifactId>swagger-codegen-distribution</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<name>swagger-codegen (executable)</name>
|
||||
<version>2.1.0-M1</version>
|
||||
<build>
|
||||
<testSourceDirectory>src/test/scala</testSourceDirectory>
|
||||
<outputDirectory>target/classes</outputDirectory>
|
||||
<testOutputDirectory>target/test-classes</testOutputDirectory>
|
||||
<defaultGoal>install</defaultGoal>
|
||||
<directory>target</directory>
|
||||
<finalName>${project.artifactId}-${project.version}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>2.3</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<minimizeJar>false</minimizeJar>
|
||||
<createDependencyReducedPom>true</createDependencyReducedPom>
|
||||
<dependencyReducedPomLocation>
|
||||
${java.io.tmpdir}/dependency-reduced-pom.xml
|
||||
</dependencyReducedPomLocation>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>com.wordnik.swagger.codegen.Codegen</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.wordnik</groupId>
|
||||
<artifactId>swagger-codegen</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.wordnik.swagger.codegen;
|
||||
|
||||
public class Readme {
|
||||
public String getInfo() {
|
||||
return "See the documentation for swagger-codegen";
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
<parent>
|
||||
<groupId>com.wordnik</groupId>
|
||||
<artifactId>swagger-codegen-project</artifactId>
|
||||
<version>2.1.0-M1</version>
|
||||
<version>2.1.0-M2</version>
|
||||
<relativePath>../..</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
@@ -10,7 +10,7 @@
|
||||
<artifactId>swagger-codegen</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<name>swagger-codegen (core library)</name>
|
||||
<version>2.1.0-M1</version>
|
||||
<version>2.1.0-M2</version>
|
||||
<build>
|
||||
<sourceDirectory>src/main/java</sourceDirectory>
|
||||
<defaultGoal>install</defaultGoal>
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.wordnik.swagger.codegen;
|
||||
|
||||
import com.samskivert.mustache.*;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
import java.io.*;
|
||||
|
||||
public abstract class AbstractGenerator {
|
||||
|
||||
public File writeToFile(String filename, String contents) throws IOException {
|
||||
System.out.println("writing file " + filename);
|
||||
File output = new File(filename);
|
||||
|
||||
if(output.getParent() != null && !new File(output.getParent()).exists()) {
|
||||
File parent = new File(output.getParent());
|
||||
parent.mkdirs();
|
||||
}
|
||||
Writer out = new BufferedWriter(new OutputStreamWriter(
|
||||
new FileOutputStream(output), "UTF-8"));
|
||||
|
||||
out.write(contents);
|
||||
out.close();
|
||||
return output;
|
||||
}
|
||||
|
||||
public String readTemplate(String name) {
|
||||
try{
|
||||
Reader reader = getTemplateReader(name);
|
||||
if(reader == null)
|
||||
throw new RuntimeException("no file found");
|
||||
java.util.Scanner s = new java.util.Scanner(reader).useDelimiter("\\A");
|
||||
return s.hasNext() ? s.next() : "";
|
||||
}
|
||||
catch(Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
throw new RuntimeException("can't load template " + name);
|
||||
}
|
||||
|
||||
public Reader getTemplateReader(String name) {
|
||||
try{
|
||||
InputStream is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name));
|
||||
if(is == null)
|
||||
is = new FileInputStream(new File(name));
|
||||
if(is == null)
|
||||
throw new RuntimeException("no file found");
|
||||
return new InputStreamReader(is);
|
||||
}
|
||||
catch(Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
throw new RuntimeException("can't load template " + name);
|
||||
}
|
||||
|
||||
private String getCPResourcePath(String name) {
|
||||
if (!"/".equals(File.separator))
|
||||
return name.replaceAll(Pattern.quote(File.separator), "/");
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -44,7 +49,7 @@ public class Codegen extends DefaultGenerator {
|
||||
options.addOption("i", "input-spec", true, "location of the swagger spec, as URL or file");
|
||||
options.addOption("t", "template-dir", true, "folder containing the template files");
|
||||
options.addOption("d", "debug-info", false, "prints additional info for debugging");
|
||||
options.addOption("a", "auth", false, "addes authorization headers when fetching the swagger definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values");
|
||||
options.addOption("a", "auth", true, "adds authorization headers when fetching the swagger definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values");
|
||||
|
||||
ClientOptInput clientOptInput = new ClientOptInput();
|
||||
ClientOpts clientOpts = new ClientOpts();
|
||||
@@ -84,7 +89,7 @@ public class Codegen extends DefaultGenerator {
|
||||
return;
|
||||
}
|
||||
if (cmd.hasOption("i"))
|
||||
swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues());
|
||||
swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true);
|
||||
if (cmd.hasOption("t"))
|
||||
clientOpts.getProperties().put("templateDir", String.valueOf(cmd.getOptionValue("t")));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.wordnik.swagger.codegen;
|
||||
|
||||
import com.wordnik.swagger.models.*;
|
||||
import com.wordnik.swagger.models.auth.SecuritySchemeDefinition;
|
||||
import com.wordnik.swagger.models.properties.*;
|
||||
|
||||
import java.util.*;
|
||||
@@ -18,12 +19,15 @@ public interface CodegenConfig {
|
||||
String modelFileFolder();
|
||||
String modelPackage();
|
||||
String toApiName(String name);
|
||||
String toApiVarName(String name);
|
||||
String toModelName(String name);
|
||||
String toParamName(String name);
|
||||
String escapeText(String text);
|
||||
String escapeReservedWord(String name);
|
||||
String getTypeDeclaration(Property p);
|
||||
String getTypeDeclaration(String name);
|
||||
void processOpts();
|
||||
String generateExamplePath(String path, Operation operation);
|
||||
|
||||
Set<String> reservedWords();
|
||||
|
||||
@@ -33,7 +37,9 @@ public interface CodegenConfig {
|
||||
String getOutputDir();
|
||||
|
||||
CodegenModel fromModel(String name, Model model);
|
||||
CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation);
|
||||
CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Model> definitions);
|
||||
List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes);
|
||||
|
||||
Set<String> defaultIncludes();
|
||||
Map<String, String> typeMapping();
|
||||
Map<String, String> instantiationTypes();
|
||||
|
||||
@@ -6,7 +6,8 @@ public enum CodegenModelType {
|
||||
OPERATION(CodegenOperation.class),
|
||||
PARAMETER(CodegenParameter.class),
|
||||
PROPERTY(CodegenProperty.class),
|
||||
RESPONSE(CodegenResponse.class);
|
||||
RESPONSE(CodegenResponse.class),
|
||||
SECURITY(CodegenSecurity.class);
|
||||
|
||||
private final Class<?> defaultImplementation;
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@ import java.util.*;
|
||||
|
||||
public class CodegenOperation {
|
||||
public Boolean hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive,
|
||||
returnSimpleType, subresourceOperation, isMapContainer, isListContainer;
|
||||
returnSimpleType, subresourceOperation, isMapContainer, isListContainer,
|
||||
hasMore = Boolean.TRUE;
|
||||
public String path, operationId, returnType, httpMethod, returnBaseType,
|
||||
returnContainer, summary, notes, baseName, defaultResponse;
|
||||
|
||||
@@ -18,6 +19,7 @@ public class CodegenOperation {
|
||||
public List<CodegenParameter> queryParams = new ArrayList<CodegenParameter>();
|
||||
public List<CodegenParameter> headerParams = new ArrayList<CodegenParameter>();
|
||||
public List<CodegenParameter> formParams = new ArrayList<CodegenParameter>();
|
||||
public List<CodegenSecurity> authMethods;
|
||||
public List<String> tags;
|
||||
public List<CodegenResponse> responses = new ArrayList<CodegenResponse>();
|
||||
public final List<CodegenProperty> responseHeaders = new ArrayList<CodegenProperty>();
|
||||
|
||||
@@ -4,6 +4,8 @@ public class CodegenParameter {
|
||||
public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
|
||||
isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer, secondaryParam;
|
||||
public String baseName, paramName, dataType, collectionFormat, description, baseType;
|
||||
public String jsonSchema;
|
||||
|
||||
/**
|
||||
* Determines whether this parameter is mandatory. If the parameter is in "path",
|
||||
* this property is required and its value MUST be true. Otherwise, the property
|
||||
@@ -31,6 +33,7 @@ public class CodegenParameter {
|
||||
output.isCookieParam = this.isCookieParam;
|
||||
output.isBodyParam = this.isBodyParam;
|
||||
output.required = this.required;
|
||||
output.jsonSchema = this.jsonSchema;
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ public class CodegenProperty {
|
||||
/** A free-form property to include an example of an instance for this schema. */
|
||||
public String example;
|
||||
|
||||
public String jsonSchema;
|
||||
public Double minimum, maximum, exclusiveMinimum, exclusiveMaximum;
|
||||
public Boolean hasMore = null, required = null, secondaryParam = null;
|
||||
public Boolean isPrimitiveType, isContainer, isNotContainer;
|
||||
|
||||
@@ -6,5 +6,12 @@ public class CodegenResponse {
|
||||
public String code, message;
|
||||
public Boolean hasMore;
|
||||
public List<Map<String, String>> examples;
|
||||
Object schema;
|
||||
public final List<CodegenProperty> headers = new ArrayList<CodegenProperty>();
|
||||
public String dataType, baseType, containerType;
|
||||
public Boolean simpleType;
|
||||
public Boolean primitiveType;
|
||||
public Boolean isMapContainer;
|
||||
public Boolean isListContainer;
|
||||
public Object schema;
|
||||
public String jsonSchema;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.wordnik.swagger.codegen;
|
||||
|
||||
public class CodegenSecurity {
|
||||
String name;
|
||||
String type;
|
||||
Boolean hasMore, isBasic, isOAuth, isApiKey;
|
||||
// ApiKey specific
|
||||
String keyParamName;
|
||||
Boolean isKeyInQuery, isKeyInHeader;
|
||||
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
package com.wordnik.swagger.codegen;
|
||||
|
||||
import com.wordnik.swagger.codegen.examples.ExampleGenerator;
|
||||
import com.wordnik.swagger.models.*;
|
||||
import com.wordnik.swagger.models.auth.ApiKeyAuthDefinition;
|
||||
import com.wordnik.swagger.models.auth.BasicAuthDefinition;
|
||||
import com.wordnik.swagger.models.auth.In;
|
||||
import com.wordnik.swagger.models.auth.SecuritySchemeDefinition;
|
||||
import com.wordnik.swagger.models.parameters.*;
|
||||
import com.wordnik.swagger.models.properties.*;
|
||||
import com.wordnik.swagger.util.Json;
|
||||
@@ -10,8 +15,12 @@ import org.apache.commons.lang.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.*;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class DefaultCodegen {
|
||||
Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class);
|
||||
|
||||
@@ -56,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;
|
||||
}
|
||||
@@ -101,11 +110,11 @@ public class DefaultCodegen {
|
||||
}
|
||||
|
||||
public String apiFileFolder() {
|
||||
return outputFolder + "/" + apiPackage().replaceAll("\\.", "/");
|
||||
return outputFolder + "/" + apiPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
public String modelFileFolder() {
|
||||
return outputFolder + "/" + modelPackage().replaceAll("\\.", "/");
|
||||
return outputFolder + "/" + modelPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
public Map<String, Object> additionalProperties() {
|
||||
@@ -130,13 +139,19 @@ public class DefaultCodegen {
|
||||
}
|
||||
|
||||
public String toApiFilename(String name) {
|
||||
return initialCaps(name) + "Api";
|
||||
return toApiName(name);
|
||||
}
|
||||
|
||||
public String toApiVarName(String name) {
|
||||
return snakeCase(name);
|
||||
}
|
||||
|
||||
public String toModelFilename(String name) {
|
||||
return name;
|
||||
return initialCaps(name);
|
||||
}
|
||||
|
||||
public String toOperationId(String operationId) { return operationId; }
|
||||
|
||||
public String toVarName(String name) {
|
||||
if(reservedWords.contains(name))
|
||||
return escapeReservedWord(name);
|
||||
@@ -151,6 +166,7 @@ public class DefaultCodegen {
|
||||
return name;
|
||||
}
|
||||
|
||||
|
||||
public String escapeReservedWord(String name) {
|
||||
throw new RuntimeException("reserved word " + name + " not allowed");
|
||||
}
|
||||
@@ -223,6 +239,55 @@ public class DefaultCodegen {
|
||||
importMapping.put("LocalTime", "org.joda.time.*");
|
||||
}
|
||||
|
||||
|
||||
public String generateExamplePath(String path, Operation operation) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(path);
|
||||
|
||||
if(operation.getParameters() != null) {
|
||||
int count = 0;
|
||||
|
||||
for(Parameter param : operation.getParameters()) {
|
||||
if(param instanceof QueryParameter) {
|
||||
StringBuilder paramPart = new StringBuilder();
|
||||
QueryParameter qp = (QueryParameter) param;
|
||||
|
||||
if(count == 0)
|
||||
paramPart.append("?");
|
||||
else
|
||||
paramPart.append(",");
|
||||
count += 1;
|
||||
if(!param.getRequired())
|
||||
paramPart.append("[");
|
||||
paramPart.append(param.getName()).append("=");
|
||||
paramPart.append("{");
|
||||
if(qp.getCollectionFormat() != null) {
|
||||
paramPart.append(param.getName() + "1");
|
||||
if("csv".equals(qp.getCollectionFormat()))
|
||||
paramPart.append(",");
|
||||
else if("pipes".equals(qp.getCollectionFormat()))
|
||||
paramPart.append("|");
|
||||
else if("tsv".equals(qp.getCollectionFormat()))
|
||||
paramPart.append("\t");
|
||||
else if("multi".equals(qp.getCollectionFormat())) {
|
||||
paramPart.append("&").append(param.getName()).append("=");
|
||||
paramPart.append(param.getName() + "2");
|
||||
}
|
||||
}
|
||||
else {
|
||||
paramPart.append(param.getName());
|
||||
}
|
||||
paramPart.append("}");
|
||||
if(!param.getRequired())
|
||||
paramPart.append("]");
|
||||
sb.append(paramPart.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public String toInstantiationType(Property p) {
|
||||
if (p instanceof MapProperty) {
|
||||
MapProperty ap = (MapProperty) p;
|
||||
@@ -247,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());
|
||||
@@ -306,8 +391,12 @@ public class DefaultCodegen {
|
||||
return datatype;
|
||||
}
|
||||
|
||||
public String snakeCase(String name) {
|
||||
return (name.length() > 0) ? (Character.toLowerCase(name.charAt(0)) + name.substring(1)) : "";
|
||||
}
|
||||
|
||||
public String initialCaps(String name) {
|
||||
return Character.toUpperCase(name.charAt(0)) + name.substring(1);
|
||||
return StringUtils.capitalize(name);
|
||||
}
|
||||
|
||||
public String getTypeDeclaration(String name) {
|
||||
@@ -337,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);
|
||||
@@ -388,8 +477,15 @@ public class DefaultCodegen {
|
||||
LOGGER.warn("null property for " + key);
|
||||
}
|
||||
else {
|
||||
CodegenProperty cp = fromProperty(key, prop);
|
||||
cp.required = false;
|
||||
CodegenProperty cp;
|
||||
try{
|
||||
cp = fromProperty(key, prop);
|
||||
}
|
||||
catch(Exception e) {
|
||||
System.out.println("failed to process model " + name);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
cp.required = null;
|
||||
if(impl.getRequired() != null) {
|
||||
for(String req : impl.getRequired()) {
|
||||
if(key.equals(req))
|
||||
@@ -430,6 +526,15 @@ public class DefaultCodegen {
|
||||
return m;
|
||||
}
|
||||
|
||||
public String getterAndSetterCapitalize(String name) {
|
||||
if (name == null || name.length() == 0) {
|
||||
return name;
|
||||
}
|
||||
|
||||
return camelize(toVarName(name));
|
||||
|
||||
}
|
||||
|
||||
public CodegenProperty fromProperty(String name, Property p) {
|
||||
if(p == null) {
|
||||
LOGGER.error("unexpected missing property for name " + null);
|
||||
@@ -440,13 +545,13 @@ public class DefaultCodegen {
|
||||
property.name = toVarName(name);
|
||||
property.baseName = name;
|
||||
property.description = escapeText(p.getDescription());
|
||||
property.getter = "get" + initialCaps(name);
|
||||
property.setter = "set" + initialCaps(name);
|
||||
property.getter = "get" + getterAndSetterCapitalize(name);
|
||||
property.setter = "set" + getterAndSetterCapitalize(name);
|
||||
property.example = p.getExample();
|
||||
property.defaultValue = toDefaultValue(p);
|
||||
property.jsonSchema = Json.pretty(p);
|
||||
|
||||
String type = getSwaggerType(p);
|
||||
|
||||
if(p instanceof AbstractNumericProperty) {
|
||||
AbstractNumericProperty np = (AbstractNumericProperty) p;
|
||||
property.minimum = np.getMinimum();
|
||||
@@ -519,16 +624,35 @@ public class DefaultCodegen {
|
||||
property.isPrimitiveType = true;
|
||||
}
|
||||
else {
|
||||
property.isNotContainer = true;
|
||||
setNonArrayMapProperty(property, type);
|
||||
}
|
||||
return property;
|
||||
}
|
||||
|
||||
protected void setNonArrayMapProperty(CodegenProperty property, String type) {
|
||||
property.isNotContainer = true;
|
||||
if(languageSpecificPrimitives().contains(type))
|
||||
property.isPrimitiveType = true;
|
||||
else
|
||||
property.complexType = property.baseType;
|
||||
}
|
||||
return property;
|
||||
|
||||
private Response findMethodResponse(Map<String, Response> responses) {
|
||||
|
||||
String code = null;
|
||||
for(String responseCode : responses.keySet()) {
|
||||
if (responseCode.startsWith("2") || responseCode.equals("default")) {
|
||||
if (code == null || code.compareTo(responseCode) > 0) {
|
||||
code = responseCode;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (code == null)
|
||||
return null;
|
||||
return responses.get(code);
|
||||
}
|
||||
|
||||
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation){
|
||||
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions) {
|
||||
CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION);
|
||||
Set<String> imports = new HashSet<String>();
|
||||
|
||||
@@ -557,22 +681,22 @@ public class DefaultCodegen {
|
||||
LOGGER.warn("generated operationId " + operationId);
|
||||
}
|
||||
op.path = path;
|
||||
op.operationId = operationId;
|
||||
op.operationId = toOperationId(operationId);
|
||||
op.summary = escapeText(operation.getSummary());
|
||||
op.notes = escapeText(operation.getDescription());
|
||||
op.tags = operation.getTags();
|
||||
|
||||
Response methodResponse = null;
|
||||
|
||||
if(operation.getConsumes() != null && operation.getConsumes().size() > 0) {
|
||||
List<Map<String, String>> c = new ArrayList<Map<String, String>>();
|
||||
int count = 0;
|
||||
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;
|
||||
@@ -588,82 +712,71 @@ public class DefaultCodegen {
|
||||
count += 1;
|
||||
if (count < operation.getProduces().size())
|
||||
mediaType.put("hasMore", "true");
|
||||
else
|
||||
mediaType.put("hasMore", null);
|
||||
c.add(mediaType);
|
||||
}
|
||||
op.produces = c;
|
||||
op.hasProduces = true;
|
||||
}
|
||||
|
||||
if(operation.getResponses() != null) {
|
||||
for(String responseCode: new TreeSet<String>(operation.getResponses().keySet())) {
|
||||
Response response = operation.getResponses().get(responseCode);
|
||||
if (responseCode.startsWith("2")) {
|
||||
// use the first, i.e. the smallest 2xx response status as methodResponse
|
||||
methodResponse = response;
|
||||
break;
|
||||
}
|
||||
if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
|
||||
Response methodResponse = findMethodResponse(operation.getResponses());
|
||||
CodegenResponse methodCodegenResponse = null;
|
||||
|
||||
for (Map.Entry<String, Response> entry : operation.getResponses().entrySet()) {
|
||||
Response response = entry.getValue();
|
||||
CodegenResponse r = fromResponse(entry.getKey(), response);
|
||||
r.hasMore = true;
|
||||
if(r.baseType != null &&
|
||||
!defaultIncludes.contains(r.baseType) &&
|
||||
!languageSpecificPrimitives.contains(r.baseType))
|
||||
imports.add(r.baseType);
|
||||
|
||||
if (response == methodResponse)
|
||||
methodCodegenResponse = r;
|
||||
op.responses.add(r);
|
||||
}
|
||||
if(methodResponse == null && operation.getResponses().keySet().contains("default")) {
|
||||
methodResponse = operation.getResponses().get("default");
|
||||
}
|
||||
for(String responseCode: operation.getResponses().keySet()) {
|
||||
Response response = operation.getResponses().get(responseCode);
|
||||
if(response != methodResponse) {
|
||||
CodegenResponse r = fromResponse(responseCode, response);
|
||||
op.responses.add(r);
|
||||
}
|
||||
for(int i = 0; i < op.responses.size() - 1; i++) {
|
||||
CodegenResponse r = op.responses.get(i);
|
||||
r.hasMore = new Boolean(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
op.responses.get(op.responses.size() - 1).hasMore = false;
|
||||
|
||||
if(methodResponse != null) {
|
||||
if (methodResponse.getSchema() != null) {
|
||||
CodegenProperty cm = fromProperty("response", methodResponse.getSchema());
|
||||
if (methodResponse.getSchema() != null) {
|
||||
CodegenProperty cm = fromProperty("response", methodResponse.getSchema());
|
||||
|
||||
Property responseProperty = methodResponse.getSchema();
|
||||
Property responseProperty = methodResponse.getSchema();
|
||||
|
||||
if(responseProperty instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) responseProperty;
|
||||
CodegenProperty innerProperty = fromProperty("response", ap.getItems());
|
||||
op.returnBaseType = innerProperty.baseType;
|
||||
}
|
||||
else {
|
||||
if(cm.complexType != null)
|
||||
op.returnBaseType = cm.complexType;
|
||||
if(responseProperty instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) responseProperty;
|
||||
CodegenProperty innerProperty = fromProperty("response", ap.getItems());
|
||||
op.returnBaseType = innerProperty.baseType;
|
||||
}
|
||||
else {
|
||||
if(cm.complexType != null)
|
||||
op.returnBaseType = cm.complexType;
|
||||
else
|
||||
op.returnBaseType = cm.baseType;
|
||||
}
|
||||
op.examples = new ExampleGenerator(definitions).generate(methodResponse.getExamples(), operation.getProduces(), responseProperty);
|
||||
op.defaultResponse = toDefaultValue(responseProperty);
|
||||
op.returnType = cm.datatype;
|
||||
if(cm.isContainer != null) {
|
||||
op.returnContainer = cm.containerType;
|
||||
if("map".equals(cm.containerType))
|
||||
op.isMapContainer = Boolean.TRUE;
|
||||
else if ("list".equalsIgnoreCase(cm.containerType))
|
||||
op.isListContainer = Boolean.TRUE;
|
||||
else if ("array".equalsIgnoreCase(cm.containerType))
|
||||
op.isListContainer = Boolean.TRUE;
|
||||
}
|
||||
else
|
||||
op.returnBaseType = cm.baseType;
|
||||
op.returnSimpleType = true;
|
||||
if (languageSpecificPrimitives().contains(op.returnBaseType) || op.returnBaseType == null)
|
||||
op.returnTypeIsPrimitive = true;
|
||||
}
|
||||
op.examples = toExamples(methodResponse.getExamples());
|
||||
op.defaultResponse = toDefaultValue(responseProperty);
|
||||
op.returnType = cm.datatype;
|
||||
if(cm.isContainer != null) {
|
||||
op.returnContainer = cm.containerType;
|
||||
if("map".equals(cm.containerType))
|
||||
op.isMapContainer = Boolean.TRUE;
|
||||
else if ("list".equalsIgnoreCase(cm.containerType))
|
||||
op.isListContainer = Boolean.TRUE;
|
||||
}
|
||||
else
|
||||
op.returnSimpleType = true;
|
||||
if (languageSpecificPrimitives().contains(op.returnBaseType) || op.returnBaseType == null)
|
||||
op.returnTypeIsPrimitive = true;
|
||||
}
|
||||
addHeaders(methodResponse, op.responseHeaders);
|
||||
addHeaders(methodResponse, op.responseHeaders);
|
||||
}
|
||||
|
||||
if(op.returnBaseType == null) {
|
||||
op.returnTypeIsPrimitive = true;
|
||||
op.returnSimpleType = true;
|
||||
}
|
||||
|
||||
if(op.returnBaseType != null &&
|
||||
!defaultIncludes.contains(op.returnBaseType) &&
|
||||
!languageSpecificPrimitives.contains(op.returnBaseType))
|
||||
imports.add(op.returnBaseType);
|
||||
|
||||
List<Parameter> parameters = operation.getParameters();
|
||||
CodegenParameter bodyParam = null;
|
||||
List<CodegenParameter> allParams = new ArrayList<CodegenParameter>();
|
||||
@@ -743,14 +856,52 @@ public class DefaultCodegen {
|
||||
r.message = response.getDescription();
|
||||
r.schema = response.getSchema();
|
||||
r.examples = toExamples(response.getExamples());
|
||||
r.jsonSchema = Json.pretty(response);
|
||||
addHeaders(response, r.headers);
|
||||
|
||||
if (r.schema != null) {
|
||||
Property responseProperty = response.getSchema();
|
||||
responseProperty.setRequired(true);
|
||||
CodegenProperty cm = fromProperty("response", responseProperty);
|
||||
|
||||
if(responseProperty instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) responseProperty;
|
||||
CodegenProperty innerProperty = fromProperty("response", ap.getItems());
|
||||
r.baseType = innerProperty.baseType;
|
||||
}
|
||||
else {
|
||||
if(cm.complexType != null)
|
||||
r.baseType = cm.complexType;
|
||||
else
|
||||
r.baseType = cm.baseType;
|
||||
}
|
||||
r.dataType = cm.datatype;
|
||||
if(cm.isContainer != null) {
|
||||
r.simpleType = false;
|
||||
r.containerType = cm.containerType;
|
||||
r.isMapContainer = "map".equals(cm.containerType);
|
||||
r.isListContainer = "list".equals(cm.containerType);
|
||||
}
|
||||
else
|
||||
r.simpleType = true;
|
||||
r.primitiveType = (r.baseType == null ||languageSpecificPrimitives().contains(r.baseType));
|
||||
}
|
||||
if (r.baseType == null) {
|
||||
r.isMapContainer = false;
|
||||
r.isListContainer = false;
|
||||
r.primitiveType = true;
|
||||
r.simpleType = true;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
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) {
|
||||
SerializableParameter qp = (SerializableParameter) param;
|
||||
@@ -840,6 +991,38 @@ public class DefaultCodegen {
|
||||
return p;
|
||||
}
|
||||
|
||||
public List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes) {
|
||||
if(schemes == null)
|
||||
return null;
|
||||
|
||||
List<CodegenSecurity> secs = new ArrayList<CodegenSecurity>();
|
||||
for(Iterator entries = schemes.entrySet().iterator(); entries.hasNext(); ) {
|
||||
Map.Entry<String, SecuritySchemeDefinition> entry = (Map.Entry<String, SecuritySchemeDefinition>) entries.next();
|
||||
final SecuritySchemeDefinition schemeDefinition = entry.getValue();
|
||||
|
||||
CodegenSecurity sec = CodegenModelFactory.newInstance(CodegenModelType.SECURITY);
|
||||
sec.name = entry.getKey();
|
||||
sec.type = schemeDefinition.getType();
|
||||
|
||||
if (schemeDefinition instanceof ApiKeyAuthDefinition) {
|
||||
final ApiKeyAuthDefinition apiKeyDefinition = (ApiKeyAuthDefinition) schemeDefinition;
|
||||
sec.isBasic = sec.isOAuth = false;
|
||||
sec.isApiKey = true;
|
||||
sec.keyParamName = apiKeyDefinition.getName();
|
||||
sec.isKeyInHeader = apiKeyDefinition.getIn() == In.HEADER;
|
||||
sec.isKeyInQuery = !sec.isKeyInHeader;
|
||||
} else {
|
||||
sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = false;
|
||||
sec.isBasic = schemeDefinition instanceof BasicAuthDefinition;
|
||||
sec.isOAuth = !sec.isBasic;
|
||||
}
|
||||
|
||||
sec.hasMore = entries.hasNext();
|
||||
secs.add(sec);
|
||||
}
|
||||
return secs;
|
||||
}
|
||||
|
||||
protected List<Map<String, String>> toExamples(Map<String, String> examples) {
|
||||
if(examples == null)
|
||||
return null;
|
||||
@@ -898,4 +1081,91 @@ public class DefaultCodegen {
|
||||
opList.add(co);
|
||||
co.baseName = tag;
|
||||
}
|
||||
}
|
||||
|
||||
/* underscore and camelize are copied from Twitter elephant bird
|
||||
* https://github.com/twitter/elephant-bird/blob/master/core/src/main/java/com/twitter/elephantbird/util/Strings.java
|
||||
*/
|
||||
|
||||
/**
|
||||
* Underscore the given word.
|
||||
* @param word The word
|
||||
* @return The underscored version of the word
|
||||
*/
|
||||
public static String underscore(String word) {
|
||||
String firstPattern = "([A-Z]+)([A-Z][a-z])";
|
||||
String secondPattern = "([a-z\\d])([A-Z])";
|
||||
String replacementPattern = "$1_$2";
|
||||
// Replace package separator with slash.
|
||||
word = word.replaceAll("\\.", "/");
|
||||
// Replace $ with two underscores for inner classes.
|
||||
word = word.replaceAll("\\$", "__");
|
||||
// Replace capital letter with _ plus lowercase letter.
|
||||
word = word.replaceAll(firstPattern, replacementPattern);
|
||||
word = word.replaceAll(secondPattern, replacementPattern);
|
||||
word = word.replace('-', '_');
|
||||
word = word.toLowerCase();
|
||||
return word;
|
||||
}
|
||||
|
||||
public static String camelize(String word) {
|
||||
return camelize(word, false);
|
||||
}
|
||||
|
||||
public static String camelize(String word, boolean lowercaseFirstLetter) {
|
||||
// Replace all slashes with dots (package separator)
|
||||
Pattern p = Pattern.compile("\\/(.?)");
|
||||
Matcher m = p.matcher(word);
|
||||
while (m.find()) {
|
||||
word = m.replaceFirst("." + m.group(1)/*.toUpperCase()*/);
|
||||
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);
|
||||
if (m.find()) {
|
||||
String rep = m.group(1) + m.group(2).toUpperCase() + m.group(3);
|
||||
rep = rep.replaceAll("\\$", "\\\\\\$");
|
||||
word = m.replaceAll(rep);
|
||||
}
|
||||
|
||||
// Replace two underscores with $ to support inner classes.
|
||||
p = Pattern.compile("(__)(.)");
|
||||
m = p.matcher(word);
|
||||
while (m.find()) {
|
||||
word = m.replaceFirst("\\$" + m.group(2).toUpperCase());
|
||||
m = p.matcher(word);
|
||||
}
|
||||
|
||||
// Remove all underscores
|
||||
p = Pattern.compile("(_)(.)");
|
||||
m = p.matcher(word);
|
||||
while (m.find()) {
|
||||
word = m.replaceFirst(m.group(2).toUpperCase());
|
||||
m = p.matcher(word);
|
||||
}
|
||||
|
||||
if (lowercaseFirstLetter) {
|
||||
word = word.substring(0, 1).toLowerCase() + word.substring(1);
|
||||
}
|
||||
|
||||
return word;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,16 +1,39 @@
|
||||
package com.wordnik.swagger.codegen;
|
||||
|
||||
import com.wordnik.swagger.models.*;
|
||||
import com.wordnik.swagger.util.*;
|
||||
import com.samskivert.mustache.*;
|
||||
import com.samskivert.mustache.Mustache;
|
||||
import com.samskivert.mustache.Template;
|
||||
import com.wordnik.swagger.models.Contact;
|
||||
import com.wordnik.swagger.models.Info;
|
||||
import com.wordnik.swagger.models.License;
|
||||
import com.wordnik.swagger.models.Model;
|
||||
import com.wordnik.swagger.models.Operation;
|
||||
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.util.*;
|
||||
import java.util.regex.*;
|
||||
import java.io.*;
|
||||
import java.io.File;
|
||||
import java.io.Reader;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
|
||||
public class DefaultGenerator implements Generator {
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.apache.commons.lang3.StringUtils.capitalize;
|
||||
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
|
||||
|
||||
public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
protected CodegenConfig config;
|
||||
protected ClientOptInput opts = null;
|
||||
protected Swagger swagger = null;
|
||||
@@ -19,124 +42,156 @@ public class DefaultGenerator implements Generator {
|
||||
this.opts = opts;
|
||||
|
||||
this.swagger = opts.getSwagger();
|
||||
ClientOpts clientOpts = opts.getOpts();
|
||||
this.config = opts.getConfig();
|
||||
this.config.additionalProperties().putAll(clientOpts.getProperties());
|
||||
this.config.additionalProperties().putAll(opts.getOpts().getProperties());
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<File> generate() {
|
||||
if(swagger == null || config == null) {
|
||||
if (swagger == null || config == null) {
|
||||
throw new RuntimeException("missing swagger input or config!");
|
||||
}
|
||||
if(System.getProperty("debugSwagger") != null) {
|
||||
if (System.getProperty("debugSwagger") != null) {
|
||||
Json.prettyPrint(swagger);
|
||||
}
|
||||
List<File> files = new ArrayList<File>();
|
||||
try {
|
||||
config.processOpts();
|
||||
if(swagger.getInfo() != null) {
|
||||
if (swagger.getInfo() != null) {
|
||||
Info info = swagger.getInfo();
|
||||
if(info.getTitle() != null)
|
||||
if (info.getTitle() != null) {
|
||||
config.additionalProperties().put("appName", info.getTitle());
|
||||
if(info.getDescription() != null)
|
||||
config.additionalProperties().put("appDescription", info.getDescription());
|
||||
if(info.getContact() != null) {
|
||||
}
|
||||
if (info.getVersion() != null) {
|
||||
config.additionalProperties().put("appVersion", info.getVersion());
|
||||
}
|
||||
if (info.getDescription() != null) {
|
||||
config.additionalProperties().put("appDescription",
|
||||
config.escapeText(info.getDescription()));
|
||||
}
|
||||
if (info.getContact() != null) {
|
||||
Contact contact = info.getContact();
|
||||
config.additionalProperties().put("infoUrl", contact.getUrl());
|
||||
if(contact.getEmail() != null)
|
||||
if (contact.getEmail() != null) {
|
||||
config.additionalProperties().put("infoEmail", contact.getEmail());
|
||||
}
|
||||
}
|
||||
if(info.getLicense() != null) {
|
||||
if (info.getLicense() != null) {
|
||||
License license = info.getLicense();
|
||||
if(license.getName() != null)
|
||||
if (license.getName() != null) {
|
||||
config.additionalProperties().put("licenseInfo", license.getName());
|
||||
if(license.getUrl() != null)
|
||||
}
|
||||
if (license.getUrl() != null) {
|
||||
config.additionalProperties().put("licenseUrl", license.getUrl());
|
||||
}
|
||||
}
|
||||
if (info.getVersion() != null) {
|
||||
config.additionalProperties().put("version", info.getVersion());
|
||||
}
|
||||
}
|
||||
|
||||
StringBuilder hostBuilder = new StringBuilder();
|
||||
if(swagger.getSchemes() != null && swagger.getSchemes().size() > 0) {
|
||||
if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) {
|
||||
hostBuilder.append(swagger.getSchemes().get(0).toValue());
|
||||
hostBuilder.append("://");
|
||||
}
|
||||
else
|
||||
} else {
|
||||
hostBuilder.append("https://");
|
||||
hostBuilder.append(swagger.getHost()).append(swagger.getBasePath());
|
||||
}
|
||||
if (swagger.getHost() != null) {
|
||||
hostBuilder.append(swagger.getHost());
|
||||
} else {
|
||||
hostBuilder.append("localhost");
|
||||
}
|
||||
if (swagger.getBasePath() != null) {
|
||||
hostBuilder.append(swagger.getBasePath());
|
||||
} else {
|
||||
hostBuilder.append("/");
|
||||
}
|
||||
String contextPath = swagger.getBasePath() == null ? "/" : swagger.getBasePath();
|
||||
String basePath = hostBuilder.toString();
|
||||
|
||||
|
||||
List<Object> allOperations = new ArrayList<Object>();
|
||||
List<Object> allModels = new ArrayList<Object>();
|
||||
|
||||
// models
|
||||
Map<String, Model> definitions = swagger.getDefinitions();
|
||||
if(definitions != null) {
|
||||
for(String name: definitions.keySet()) {
|
||||
if (definitions != null) {
|
||||
for (String name : definitions.keySet()) {
|
||||
Model model = definitions.get(name);
|
||||
Map<String, Model> modelMap = new HashMap<String, Model>();
|
||||
modelMap.put(name, model);
|
||||
Map<String, Object> models = processModels(config, modelMap);
|
||||
models.putAll(config.additionalProperties());
|
||||
|
||||
allModels.add(((List<Object>)models.get("models")).get(0));
|
||||
allModels.add(((List<Object>) models.get("models")).get(0));
|
||||
|
||||
for(String templateName : config.modelTemplateFiles().keySet()) {
|
||||
for (String templateName : config.modelTemplateFiles().keySet()) {
|
||||
String suffix = config.modelTemplateFiles().get(templateName);
|
||||
String filename = config.modelFileFolder() + File.separator + config.toModelFilename(name) + suffix;
|
||||
String template = readTemplate(config.templateDir() + File.separator + templateName);
|
||||
Template tmpl = Mustache.compiler()
|
||||
.withLoader(new Mustache.TemplateLoader() {
|
||||
public Reader getTemplate (String name) {
|
||||
return getTemplateReader(config.templateDir() + File.separator + name + ".mustache");
|
||||
};
|
||||
})
|
||||
.defaultValue("")
|
||||
.compile(template);
|
||||
.withLoader(new Mustache.TemplateLoader() {
|
||||
public Reader getTemplate(String name) {
|
||||
return getTemplateReader(config.templateDir() + File.separator + name + ".mustache");
|
||||
}
|
||||
})
|
||||
.defaultValue("")
|
||||
.compile(template);
|
||||
writeToFile(filename, tmpl.execute(models));
|
||||
files.add(new File(filename));
|
||||
}
|
||||
}
|
||||
}
|
||||
if(System.getProperty("debugModels") != null) {
|
||||
if (System.getProperty("debugModels") != null) {
|
||||
System.out.println("############ Model info ############");
|
||||
Json.prettyPrint(allModels);
|
||||
}
|
||||
|
||||
// apis
|
||||
Map<String, List<CodegenOperation>> paths = processPaths(swagger.getPaths());
|
||||
for(String tag : paths.keySet()) {
|
||||
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);
|
||||
operation.put("modelPackage", config.modelPackage());
|
||||
operation.putAll(config.additionalProperties());
|
||||
operation.put("classname", config.toApiName(tag));
|
||||
allOperations.add(operation);
|
||||
for(String templateName : config.apiTemplateFiles().keySet()) {
|
||||
operation.put("classVarName", config.toApiVarName(tag));
|
||||
|
||||
allOperations.add(new HashMap<String, Object>(operation));
|
||||
for (int i = 0; i < allOperations.size(); i++) {
|
||||
Map<String, Object> oo = (Map<String, Object>) allOperations.get(i);
|
||||
if (i < (allOperations.size() - 1)) {
|
||||
oo.put("hasMore", "true");
|
||||
}
|
||||
}
|
||||
|
||||
for (String templateName : config.apiTemplateFiles().keySet()) {
|
||||
String suffix = config.apiTemplateFiles().get(templateName);
|
||||
String filename = config.apiFileFolder() +
|
||||
File.separator +
|
||||
config.toApiFilename(tag) +
|
||||
suffix;
|
||||
File.separator +
|
||||
config.toApiFilename(tag) +
|
||||
suffix;
|
||||
|
||||
String template = readTemplate(config.templateDir() + File.separator + templateName);
|
||||
Template tmpl = Mustache.compiler()
|
||||
.withLoader(new Mustache.TemplateLoader() {
|
||||
public Reader getTemplate (String name) {
|
||||
return getTemplateReader(config.templateDir() + File.separator + name + ".mustache");
|
||||
};
|
||||
})
|
||||
.defaultValue("")
|
||||
.compile(template);
|
||||
.withLoader(new Mustache.TemplateLoader() {
|
||||
public Reader getTemplate(String name) {
|
||||
return getTemplateReader(config.templateDir() + File.separator + name + ".mustache");
|
||||
}
|
||||
})
|
||||
.defaultValue("")
|
||||
.compile(template);
|
||||
|
||||
writeToFile(filename, tmpl.execute(operation));
|
||||
files.add(new File(filename));
|
||||
}
|
||||
}
|
||||
if(System.getProperty("debugOperations") != null) {
|
||||
if (System.getProperty("debugOperations") != null) {
|
||||
System.out.println("############ Operation info ############");
|
||||
Json.prettyPrint(allOperations);
|
||||
}
|
||||
@@ -148,17 +203,19 @@ public class DefaultGenerator implements Generator {
|
||||
|
||||
Map<String, Object> apis = new HashMap<String, Object>();
|
||||
apis.put("apis", allOperations);
|
||||
if(swagger.getBasePath() != null) {
|
||||
bundle.put("basePath", swagger.getBasePath());
|
||||
if (swagger.getHost() != null) {
|
||||
bundle.put("host", swagger.getHost());
|
||||
}
|
||||
bundle.put("basePath", basePath);
|
||||
bundle.put("contextPath", contextPath);
|
||||
bundle.put("apiInfo", apis);
|
||||
bundle.put("models", allModels);
|
||||
bundle.put("apiFolder", config.apiPackage().replaceAll("\\.", "/"));
|
||||
bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar));
|
||||
bundle.put("modelPackage", config.modelPackage());
|
||||
if (swagger.getExternalDocs() != null) {
|
||||
bundle.put("externalDocs", swagger.getExternalDocs());
|
||||
}
|
||||
for(int i = 0; i < allModels.size() - 1; i++) {
|
||||
for (int i = 0; i < allModels.size() - 1; i++) {
|
||||
HashMap<String, CodegenModel> cm = (HashMap<String, CodegenModel>) allModels.get(i);
|
||||
CodegenModel m = cm.get("model");
|
||||
m.hasMoreModels = true;
|
||||
@@ -166,45 +223,64 @@ public class DefaultGenerator implements Generator {
|
||||
|
||||
config.postProcessSupportingFileData(bundle);
|
||||
|
||||
if(System.getProperty("debugSupportingFiles") != null) {
|
||||
if (System.getProperty("debugSupportingFiles") != null) {
|
||||
System.out.println("############ Supporting file info ############");
|
||||
Json.prettyPrint(bundle);
|
||||
}
|
||||
|
||||
for(SupportingFile support : config.supportingFiles()) {
|
||||
for (SupportingFile support : config.supportingFiles()) {
|
||||
String outputFolder = config.outputFolder();
|
||||
if(support.folder != null && !"".equals(support.folder))
|
||||
if (isNotEmpty(support.folder)) {
|
||||
outputFolder += File.separator + support.folder;
|
||||
}
|
||||
File of = new File(outputFolder);
|
||||
if(!of.isDirectory())
|
||||
if (!of.isDirectory()) {
|
||||
of.mkdirs();
|
||||
}
|
||||
String outputFilename = outputFolder + File.separator + support.destinationFilename;
|
||||
|
||||
if(support.templateFile.endsWith("mustache")) {
|
||||
if (support.templateFile.endsWith("mustache")) {
|
||||
String template = readTemplate(config.templateDir() + File.separator + support.templateFile);
|
||||
Template tmpl = Mustache.compiler()
|
||||
.withLoader(new Mustache.TemplateLoader() {
|
||||
public Reader getTemplate (String name) {
|
||||
return getTemplateReader(config.templateDir() + File.separator + name + ".mustache");
|
||||
};
|
||||
})
|
||||
.defaultValue("")
|
||||
.compile(template);
|
||||
.withLoader(new Mustache.TemplateLoader() {
|
||||
public Reader getTemplate(String name) {
|
||||
return getTemplateReader(config.templateDir() + File.separator + name + ".mustache");
|
||||
}
|
||||
})
|
||||
.defaultValue("")
|
||||
.compile(template);
|
||||
|
||||
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));
|
||||
} else {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
config.processSwagger(swagger);
|
||||
}
|
||||
catch (Exception e) {
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return files;
|
||||
@@ -212,9 +288,8 @@ public class DefaultGenerator implements Generator {
|
||||
|
||||
public Map<String, List<CodegenOperation>> processPaths(Map<String, Path> paths) {
|
||||
Map<String, List<CodegenOperation>> ops = new HashMap<String, List<CodegenOperation>>();
|
||||
List<String> tags = null;
|
||||
|
||||
for(String resourcePath : paths.keySet()) {
|
||||
for (String resourcePath : paths.keySet()) {
|
||||
Path path = paths.get(resourcePath);
|
||||
processOperation(resourcePath, "get", path.getGet(), ops);
|
||||
processOperation(resourcePath, "put", path.getPut(), ops);
|
||||
@@ -226,90 +301,65 @@ public class DefaultGenerator implements Generator {
|
||||
return ops;
|
||||
}
|
||||
|
||||
public SecuritySchemeDefinition fromSecurity(String name) {
|
||||
Map<String, SecuritySchemeDefinition> map = swagger.getSecurityDefinitions();
|
||||
if (map == null) {
|
||||
return null;
|
||||
}
|
||||
return map.get(name);
|
||||
}
|
||||
|
||||
|
||||
public void processOperation(String resourcePath, String httpMethod, Operation operation, Map<String, List<CodegenOperation>> operations) {
|
||||
if(operation != null) {
|
||||
if (operation != null) {
|
||||
List<String> tags = operation.getTags();
|
||||
if(tags == null) {
|
||||
if (tags == null) {
|
||||
tags = new ArrayList<String>();
|
||||
tags.add("default");
|
||||
}
|
||||
|
||||
for(String tag : tags) {
|
||||
CodegenOperation co = config.fromOperation(resourcePath, httpMethod, operation);
|
||||
for (String tag : tags) {
|
||||
CodegenOperation co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions());
|
||||
co.tags = new ArrayList<String>();
|
||||
co.tags.add(sanitizeTag(tag));
|
||||
|
||||
config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations);
|
||||
|
||||
List<Map<String, List<String>>> securities = operation.getSecurity();
|
||||
if (securities == null) {
|
||||
continue;
|
||||
}
|
||||
Map<String, SecuritySchemeDefinition> authMethods = new HashMap<String, SecuritySchemeDefinition>();
|
||||
for (Map<String, List<String>> security : securities) {
|
||||
if (security.size() != 1) {
|
||||
//Not sure what to do
|
||||
continue;
|
||||
}
|
||||
String securityName = security.keySet().iterator().next();
|
||||
SecuritySchemeDefinition securityDefinition = fromSecurity(securityName);
|
||||
if (securityDefinition != null) {
|
||||
authMethods.put(securityName, securityDefinition);
|
||||
}
|
||||
}
|
||||
if (!authMethods.isEmpty()) {
|
||||
co.authMethods = config.fromSecurity(authMethods);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected String sanitizeTag(String tag) {
|
||||
// remove spaces and make strong case
|
||||
String [] parts = tag.split(" ");
|
||||
StringBuffer buf = new StringBuffer();
|
||||
for(String part: parts) {
|
||||
if(!"".equals(part)) {
|
||||
buf.append(Character.toUpperCase(part.charAt(0)));
|
||||
if(part.length() > 1)
|
||||
buf.append(part.substring(1));
|
||||
String[] parts = tag.split(" ");
|
||||
StringBuilder buf = new StringBuilder();
|
||||
for (String part : parts) {
|
||||
if (isNotEmpty(part)) {
|
||||
buf.append(capitalize(part));
|
||||
}
|
||||
}
|
||||
return buf.toString().replaceAll("[^a-zA-Z ]", "");
|
||||
}
|
||||
|
||||
public File writeToFile(String filename, String contents) throws IOException {
|
||||
System.out.println("writing file " + filename);
|
||||
File output = new File(filename);
|
||||
|
||||
if(output.getParent() != null && !new File(output.getParent()).exists()) {
|
||||
File parent = new File(output.getParent());
|
||||
parent.mkdirs();
|
||||
}
|
||||
Writer out = new BufferedWriter(new OutputStreamWriter(
|
||||
new FileOutputStream(output), "UTF-8"));
|
||||
|
||||
out.write(contents);
|
||||
out.close();
|
||||
return output;
|
||||
}
|
||||
|
||||
public String readTemplate(String name) {
|
||||
try{
|
||||
Reader reader = getTemplateReader(name);
|
||||
if(reader == null)
|
||||
throw new RuntimeException("no file found");
|
||||
java.util.Scanner s = new java.util.Scanner(reader).useDelimiter("\\A");
|
||||
return s.hasNext() ? s.next() : "";
|
||||
}
|
||||
catch(Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
throw new RuntimeException("can't load template " + name);
|
||||
}
|
||||
|
||||
public Reader getTemplateReader(String name) {
|
||||
try{
|
||||
InputStream is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name));
|
||||
if(is == null)
|
||||
is = new FileInputStream(new File(name));
|
||||
if(is == null)
|
||||
throw new RuntimeException("no file found");
|
||||
return new InputStreamReader(is);
|
||||
}
|
||||
catch(Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
throw new RuntimeException("can't load template " + name);
|
||||
}
|
||||
|
||||
private String getCPResourcePath(String name) {
|
||||
if (!"/".equals(File.separator))
|
||||
return name.replaceAll(Pattern.quote(File.separator), "/");
|
||||
return name;
|
||||
}
|
||||
|
||||
public Map<String, Object> processOperations(CodegenConfig config, String tag, List<CodegenOperation> ops) {
|
||||
public Map<String, Object> processOperations(CodegenConfig config, String tag, List<CodegenOperation> ops) {
|
||||
Map<String, Object> operations = new HashMap<String, Object>();
|
||||
Map<String, Object> objs = new HashMap<String, Object>();
|
||||
objs.put("classname", config.toApiName(tag));
|
||||
@@ -318,24 +368,33 @@ public Map<String, Object> processOperations(CodegenConfig config, String tag, L
|
||||
operations.put("package", config.apiPackage());
|
||||
|
||||
Set<String> allImports = new LinkedHashSet<String>();
|
||||
for(CodegenOperation op: ops) {
|
||||
for (CodegenOperation op : ops) {
|
||||
allImports.addAll(op.imports);
|
||||
}
|
||||
|
||||
List<Map<String, String>> imports = new ArrayList<Map<String, String>>();
|
||||
for(String i: allImports) {
|
||||
for (String nextImport : allImports) {
|
||||
Map<String, String> im = new LinkedHashMap<String, String>();
|
||||
String m = config.importMapping().get(i);
|
||||
if(m == null)
|
||||
m = config.toModelImport(i);
|
||||
if(m != null) {
|
||||
im.put("import", m);
|
||||
String mapping = config.importMapping().get(nextImport);
|
||||
if (mapping == null) {
|
||||
mapping = config.toModelImport(nextImport);
|
||||
}
|
||||
if (mapping != null) {
|
||||
im.put("import", mapping);
|
||||
imports.add(im);
|
||||
}
|
||||
}
|
||||
|
||||
operations.put("imports", imports);
|
||||
config.postProcessOperations(operations);
|
||||
if (objs.size() > 0) {
|
||||
List<CodegenOperation> os = (List<CodegenOperation>) objs.get("operation");
|
||||
|
||||
if (os != null && os.size() > 0) {
|
||||
CodegenOperation op = os.get(os.size() - 1);
|
||||
op.hasMore = null;
|
||||
}
|
||||
}
|
||||
return operations;
|
||||
}
|
||||
|
||||
@@ -343,9 +402,8 @@ public Map<String, Object> processOperations(CodegenConfig config, String tag, L
|
||||
Map<String, Object> objs = new HashMap<String, Object>();
|
||||
objs.put("package", config.modelPackage());
|
||||
List<Object> models = new ArrayList<Object>();
|
||||
List<Object> model = new ArrayList<Object>();
|
||||
Set<String> allImports = new LinkedHashSet<String>();
|
||||
for(String key: definitions.keySet()) {
|
||||
for (String key : definitions.keySet()) {
|
||||
Model mm = definitions.get(key);
|
||||
CodegenModel cm = config.fromModel(key, mm);
|
||||
Map<String, Object> mo = new HashMap<String, Object>();
|
||||
@@ -356,19 +414,20 @@ public Map<String, Object> processOperations(CodegenConfig config, String tag, L
|
||||
objs.put("models", models);
|
||||
|
||||
List<Map<String, String>> imports = new ArrayList<Map<String, String>>();
|
||||
for(String i: allImports) {
|
||||
for (String nextImport : allImports) {
|
||||
Map<String, String> im = new LinkedHashMap<String, String>();
|
||||
String m = config.importMapping().get(i);
|
||||
if(m == null)
|
||||
m = config.toModelImport(i);
|
||||
if(m != null && !config.defaultIncludes().contains(m)) {
|
||||
im.put("import", m);
|
||||
String mapping = config.importMapping().get(nextImport);
|
||||
if (mapping == null) {
|
||||
mapping = config.toModelImport(nextImport);
|
||||
}
|
||||
if (mapping != null && !config.defaultIncludes().contains(mapping)) {
|
||||
im.put("import", mapping);
|
||||
imports.add(im);
|
||||
}
|
||||
// add instantiation types
|
||||
m = config.instantiationTypes().get(i);
|
||||
if(m != null && !config.defaultIncludes().contains(m)) {
|
||||
im.put("import", m);
|
||||
mapping = config.instantiationTypes().get(nextImport);
|
||||
if (mapping != null && !config.defaultIncludes().contains(mapping)) {
|
||||
im.put("import", mapping);
|
||||
imports.add(im);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
package com.wordnik.swagger.codegen;
|
||||
|
||||
import com.wordnik.swagger.codegen.languages.*;
|
||||
import com.wordnik.swagger.models.Swagger;
|
||||
import com.wordnik.swagger.models.auth.AuthorizationValue;
|
||||
import com.wordnik.swagger.util.*;
|
||||
|
||||
import io.swagger.parser.SwaggerParser;
|
||||
|
||||
import com.samskivert.mustache.*;
|
||||
|
||||
import org.apache.commons.cli.*;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
|
||||
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;
|
||||
static {
|
||||
List<CodegenConfig> extensions = getExtensions();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for(CodegenConfig config : extensions) {
|
||||
if(sb.toString().length() != 0)
|
||||
sb.append(", ");
|
||||
sb.append(config.getName());
|
||||
configs.put(config.getName(), config);
|
||||
configString = sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
new MetaGenerator().generate(args);
|
||||
}
|
||||
|
||||
protected void generate(String[] args) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String targetLanguage = null;
|
||||
String outputFolder = null;
|
||||
String name = null;
|
||||
String targetPackage = "com.wordnik.swagger.codegen";
|
||||
final String templateDir = "codegen";
|
||||
|
||||
Options options = new Options();
|
||||
options.addOption("h", "help", false, "shows this message");
|
||||
options.addOption("l", "lang", false, "client language to generate.\nAvailable languages include:\n\t[" + configString + "]");
|
||||
options.addOption("o", "output", true, "where to write the generated files");
|
||||
options.addOption("n", "name", true, "the human-readable name of the generator");
|
||||
options.addOption("p", "package", true, "the package to put the main class into (defaults to com.wordnik.swagger.codegen");
|
||||
|
||||
ClientOptInput clientOptInput = new ClientOptInput();
|
||||
Swagger swagger = null;
|
||||
CommandLine cmd = null;
|
||||
try {
|
||||
CommandLineParser parser = new BasicParser();
|
||||
|
||||
cmd = parser.parse(options, args);
|
||||
if (cmd.hasOption("h")) {
|
||||
usage(options);
|
||||
return;
|
||||
}
|
||||
if (cmd.hasOption("n"))
|
||||
name = cmd.getOptionValue("n");
|
||||
else {
|
||||
System.out.println("name is required");
|
||||
usage(options);
|
||||
return;
|
||||
}
|
||||
if (cmd.hasOption("l"))
|
||||
targetLanguage = cmd.getOptionValue("l");
|
||||
if (cmd.hasOption("p"))
|
||||
targetPackage = cmd.getOptionValue("p");
|
||||
if (cmd.hasOption("o"))
|
||||
outputFolder = cmd.getOptionValue("o");
|
||||
else {
|
||||
System.out.println("output folder is required");
|
||||
usage(options);
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
usage(options);
|
||||
return;
|
||||
}
|
||||
System.out.println("writing to folder " + outputFolder);
|
||||
File outputFolderLocation = new File(outputFolder);
|
||||
if(!outputFolderLocation.exists())
|
||||
outputFolderLocation.mkdirs();
|
||||
File sourceFolder = new File(outputFolder + File.separator + "src/main/java/" + targetPackage.replace('.', File.separatorChar));
|
||||
if(!sourceFolder.exists())
|
||||
sourceFolder.mkdirs();
|
||||
File resourcesFolder = new File(outputFolder + File.separator + "src/main/resources/META-INF/services");
|
||||
if(!resourcesFolder.exists())
|
||||
resourcesFolder.mkdirs();
|
||||
|
||||
String mainClass = Character.toUpperCase(name.charAt(0)) + name.substring(1) + "Generator";
|
||||
|
||||
List<SupportingFile> supportingFiles = new ArrayList<SupportingFile>();
|
||||
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
|
||||
supportingFiles.add(new SupportingFile("generatorClass.mustache",
|
||||
"src/main/java/" + File.separator + targetPackage.replace('.', File.separatorChar),
|
||||
mainClass + ".java"));
|
||||
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
|
||||
supportingFiles.add(new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache"));
|
||||
supportingFiles.add(new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache"));
|
||||
|
||||
supportingFiles.add(new SupportingFile("services.mustache", "src/main/resources/META-INF/services", "com.wordnik.swagger.codegen.CodegenConfig"));
|
||||
|
||||
List<File> files = new ArrayList<File>();
|
||||
|
||||
Map<String, Object> data = new HashMap<String, Object>();
|
||||
data.put("generatorPackage", targetPackage);
|
||||
data.put("generatorClass", mainClass);
|
||||
data.put("name", name);
|
||||
data.put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass);
|
||||
|
||||
for(SupportingFile support : supportingFiles) {
|
||||
try {
|
||||
String destinationFolder = outputFolder;
|
||||
if(support.folder != null && !"".equals(support.folder))
|
||||
destinationFolder += File.separator + support.folder;
|
||||
File of = new File(destinationFolder);
|
||||
if(!of.isDirectory())
|
||||
of.mkdirs();
|
||||
String outputFilename = destinationFolder + File.separator + support.destinationFilename;
|
||||
|
||||
if(support.templateFile.endsWith("mustache")) {
|
||||
String template = readTemplate(templateDir + File.separator + support.templateFile);
|
||||
Template tmpl = Mustache.compiler()
|
||||
.withLoader(new Mustache.TemplateLoader() {
|
||||
public Reader getTemplate (String name) {
|
||||
return getTemplateReader(templateDir + File.separator + name + ".mustache");
|
||||
};
|
||||
})
|
||||
.defaultValue("")
|
||||
.compile(template);
|
||||
|
||||
writeToFile(outputFilename, tmpl.execute(data));
|
||||
files.add(new File(outputFilename));
|
||||
}
|
||||
else {
|
||||
String template = readTemplate(templateDir + File.separator + support.templateFile);
|
||||
FileUtils.writeStringToFile(new File(outputFilename), template);
|
||||
System.out.println("copying file to " + outputFilename);
|
||||
files.add(new File(outputFilename));
|
||||
}
|
||||
}
|
||||
catch (java.io.IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static List<CodegenConfig> getExtensions() {
|
||||
ServiceLoader<CodegenConfig> loader = ServiceLoader.load(CodegenConfig.class);
|
||||
List<CodegenConfig> output = new ArrayList<CodegenConfig>();
|
||||
Iterator<CodegenConfig> itr = loader.iterator();
|
||||
while(itr.hasNext()) {
|
||||
output.add(itr.next());
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
static void usage(Options options) {
|
||||
HelpFormatter formatter = new HelpFormatter();
|
||||
formatter.printHelp( "MetaGenerator. Generator for creating a new template set " +
|
||||
"and configuration for Codegen. The output will be based on the language you " +
|
||||
"specify, and includes default templates to include.", options );
|
||||
}
|
||||
|
||||
public static CodegenConfig getConfig(String name) {
|
||||
if(configs.containsKey(name)) {
|
||||
return configs.get(name);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package com.wordnik.swagger.codegen.examples;
|
||||
|
||||
import com.wordnik.swagger.models.*;
|
||||
import com.wordnik.swagger.models.properties.*;
|
||||
import com.wordnik.swagger.util.Json;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
|
||||
import javax.xml.bind.JAXBContext;
|
||||
import javax.xml.bind.JAXBException;
|
||||
import javax.xml.bind.Marshaller;
|
||||
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
|
||||
public class ExampleGenerator {
|
||||
protected Map<String, Model> examples;
|
||||
|
||||
public ExampleGenerator(Map<String, Model> examples) {
|
||||
this.examples = examples;
|
||||
}
|
||||
|
||||
public List<Map<String, String>> generate(Map<String, String> examples, List<String> mediaTypes, Property property) {
|
||||
List<Map<String, String>> output = new ArrayList<Map<String, String>>();
|
||||
Set<String> processedModels = new HashSet<String>();
|
||||
if(examples == null ) {
|
||||
if(mediaTypes == null) {
|
||||
// assume application/json for this
|
||||
mediaTypes = Arrays.asList("application/json");
|
||||
}
|
||||
for(String mediaType : mediaTypes) {
|
||||
Map<String, String> kv = new HashMap<String, String>();
|
||||
kv.put("contentType", mediaType);
|
||||
if(property != null && mediaType.startsWith("application/json")) {
|
||||
String example = Json.pretty(resolvePropertyToExample(mediaType, property, processedModels));
|
||||
|
||||
if(example != null) {
|
||||
example = example.replaceAll("\n", "\\\\n");
|
||||
kv.put("example", example);
|
||||
output.add(kv);
|
||||
}
|
||||
}
|
||||
else if(property != null && mediaType.startsWith("application/xml")) {
|
||||
String example = new XmlExampleGenerator(this.examples).toXml(property);
|
||||
if(example != null) {
|
||||
example = example.replaceAll("\n", "\\\\n");
|
||||
kv.put("example", example);
|
||||
output.add(kv);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
for(String key: examples.keySet()) {
|
||||
String value = examples.get(key);
|
||||
|
||||
Map<String, String> kv = new HashMap<String, String>();
|
||||
kv.put("contentType", key);
|
||||
kv.put("example", value);
|
||||
output.add(kv);
|
||||
}
|
||||
}
|
||||
if(output.size() == 0) {
|
||||
Map<String, String> kv = new HashMap<String, String>();
|
||||
kv.put("output", "none");
|
||||
output.add(kv);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
protected Object resolvePropertyToExample(String mediaType, Property property, Set<String> processedModels) {
|
||||
if(property.getExample() != null) {
|
||||
return property.getExample();
|
||||
}
|
||||
else if(property instanceof StringProperty) {
|
||||
return "aeiou";
|
||||
}
|
||||
else if(property instanceof BooleanProperty) {
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
else if(property instanceof ArrayProperty) {
|
||||
Property innerType = ((ArrayProperty)property).getItems();
|
||||
if(innerType != null) {
|
||||
Object[] output = new Object[]{
|
||||
resolvePropertyToExample(mediaType, innerType, processedModels)
|
||||
};
|
||||
return output;
|
||||
}
|
||||
}
|
||||
else if(property instanceof DateProperty) {
|
||||
return new java.util.Date(System.currentTimeMillis());
|
||||
}
|
||||
else if(property instanceof DateTimeProperty) {
|
||||
return new java.util.Date(System.currentTimeMillis());
|
||||
}
|
||||
else if(property instanceof DecimalProperty) {
|
||||
return new BigDecimal(1.3579);
|
||||
}
|
||||
else if(property instanceof DoubleProperty) {
|
||||
return new Double(3.149);
|
||||
}
|
||||
else if(property instanceof FileProperty) {
|
||||
return ""; // TODO
|
||||
}
|
||||
else if(property instanceof FloatProperty) {
|
||||
return new Float(1.23);
|
||||
}
|
||||
else if(property instanceof IntegerProperty) {
|
||||
return new Integer(123);
|
||||
}
|
||||
else if(property instanceof LongProperty) {
|
||||
return new Long(123456789);
|
||||
}
|
||||
else if(property instanceof MapProperty) {
|
||||
Map<String, Object> mp = new HashMap<String, Object>();
|
||||
if(property.getName() != null) {
|
||||
mp.put(property.getName(),
|
||||
resolvePropertyToExample(mediaType, ((MapProperty)property).getAdditionalProperties(), processedModels));
|
||||
}
|
||||
else {
|
||||
mp.put("key",
|
||||
resolvePropertyToExample(mediaType, ((MapProperty)property).getAdditionalProperties(), processedModels));
|
||||
}
|
||||
return mp;
|
||||
}
|
||||
else if(property instanceof ObjectProperty) {
|
||||
return "{}";
|
||||
}
|
||||
else if(property instanceof RefProperty) {
|
||||
String simpleName = ((RefProperty)property).getSimpleRef();
|
||||
Model model = examples.get(simpleName);
|
||||
if(model != null)
|
||||
return resolveModelToExample(simpleName, mediaType, model, processedModels);
|
||||
}
|
||||
else if(property instanceof UUIDProperty) {
|
||||
return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
public Object resolveModelToExample(String name, String mediaType, Model model, Set<String> processedModels) {
|
||||
if(processedModels.contains(name)) {
|
||||
return "";
|
||||
}
|
||||
if(model instanceof ModelImpl) {
|
||||
processedModels.add(name);
|
||||
ModelImpl impl = (ModelImpl) model;
|
||||
Map<String, Object> values = new HashMap<String, Object>();
|
||||
|
||||
if(impl != null && impl.getProperties() != null) {
|
||||
for(String propertyName : impl.getProperties().keySet()) {
|
||||
Property property = impl.getProperties().get(propertyName);
|
||||
values.put(propertyName, resolvePropertyToExample(mediaType, property, processedModels));
|
||||
}
|
||||
}
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package com.wordnik.swagger.codegen.examples;
|
||||
|
||||
|
||||
import com.wordnik.swagger.util.Json;
|
||||
import com.wordnik.swagger.models.*;
|
||||
import com.wordnik.swagger.models.properties.*;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
|
||||
public class XmlExampleGenerator {
|
||||
public static String NEWLINE = "\n";
|
||||
public static String TAG_START = "<";
|
||||
public static String CLOSE_TAG = ">";
|
||||
public static String TAG_END = "</";
|
||||
protected Map<String, Model> examples;
|
||||
protected SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
|
||||
protected SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
|
||||
|
||||
public XmlExampleGenerator(Map<String, Model> examples) {
|
||||
this.examples = examples;
|
||||
if(examples == null)
|
||||
examples = new HashMap<String, Model>();
|
||||
}
|
||||
|
||||
public String toXml(Property property) {
|
||||
return toXml(null, property, 0);
|
||||
}
|
||||
|
||||
protected String toXml(Model model, int indent) {
|
||||
if(model instanceof RefModel) {
|
||||
RefModel ref = (RefModel) model;
|
||||
Model actualModel = examples.get(ref.getSimpleRef());
|
||||
if(actualModel instanceof ModelImpl)
|
||||
return modelImplToXml((ModelImpl)actualModel, indent);
|
||||
}
|
||||
else if(model instanceof ModelImpl) {
|
||||
return modelImplToXml((ModelImpl)model, indent);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected String modelImplToXml(ModelImpl model, int indent) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
// attributes
|
||||
Map<String, Property> attributes = new LinkedHashMap<String, Property>();
|
||||
Map<String, Property> elements = new LinkedHashMap<String, Property>();
|
||||
|
||||
String name = model.getName();
|
||||
String namespace;
|
||||
String prefix;
|
||||
Boolean wrapped;
|
||||
|
||||
Xml xml = model.getXml();
|
||||
if(xml != null) {
|
||||
if(xml.getName() != null)
|
||||
name = xml.getName();
|
||||
}
|
||||
for(String pName : model.getProperties().keySet()) {
|
||||
Property p = model.getProperties().get(pName);
|
||||
if(p != null && p.getXml() != null && p.getXml().getAttribute() != null && p.getXml().getAttribute())
|
||||
attributes.put(pName, p);
|
||||
else
|
||||
elements.put(pName, p);
|
||||
}
|
||||
sb.append(indent(indent)).append(TAG_START);
|
||||
sb.append(name);
|
||||
for(String pName : attributes.keySet()) {
|
||||
Property p = attributes.get(pName);
|
||||
sb.append(" ").append(pName).append("=").append(quote(toXml(null, p, 0)));
|
||||
}
|
||||
sb.append(CLOSE_TAG);
|
||||
sb.append(NEWLINE);
|
||||
for(String pName : elements.keySet()) {
|
||||
Property p = elements.get(pName);
|
||||
sb.append(toXml(pName, p, indent + 1));
|
||||
sb.append(NEWLINE);
|
||||
}
|
||||
sb.append(indent(indent)).append(TAG_END).append(name).append(CLOSE_TAG);
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
protected String quote(String string) {
|
||||
return "\"" + string + "\"";
|
||||
}
|
||||
|
||||
protected String toXml(String name, Property property, int indent) {
|
||||
if(property == null) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
if(property instanceof ArrayProperty) {
|
||||
ArrayProperty p = (ArrayProperty) property;
|
||||
Property inner = p.getItems();
|
||||
boolean wrapped = false;
|
||||
if(property.getXml() != null && property.getXml().getWrapped())
|
||||
wrapped = true;
|
||||
if(wrapped) {
|
||||
if(name != null) {
|
||||
sb.append(indent(indent));
|
||||
sb.append(openTag(name));
|
||||
sb.append(NEWLINE);
|
||||
}
|
||||
sb.append(toXml(name, inner, indent + 1));
|
||||
if(name != null) {
|
||||
sb.append(NEWLINE);
|
||||
sb.append(indent(indent));
|
||||
sb.append(closeTag(name));
|
||||
}
|
||||
}
|
||||
else
|
||||
sb.append(toXml(name, inner, indent));
|
||||
}
|
||||
else if(property instanceof RefProperty) {
|
||||
RefProperty ref = (RefProperty) property;
|
||||
Model actualModel = examples.get(ref.getSimpleRef());
|
||||
sb.append(toXml(actualModel, indent));
|
||||
}
|
||||
else {
|
||||
if(name != null) {
|
||||
sb.append(indent(indent));
|
||||
sb.append(openTag(name));
|
||||
}
|
||||
sb.append(getExample(property));
|
||||
if(name != null)
|
||||
sb.append(closeTag(name));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
protected String getExample(Property property) {
|
||||
if(property instanceof DateTimeProperty) {
|
||||
if(property.getExample() != null)
|
||||
return property.getExample();
|
||||
else
|
||||
return dtFormat.format(new Date());
|
||||
}
|
||||
else if(property instanceof StringProperty) {
|
||||
if(property.getExample() != null)
|
||||
return property.getExample();
|
||||
else
|
||||
return "string";
|
||||
}
|
||||
else if(property instanceof DateProperty) {
|
||||
if(property.getExample() != null)
|
||||
return property.getExample();
|
||||
else
|
||||
return dateFormat.format(new Date());
|
||||
}
|
||||
else if(property instanceof IntegerProperty) {
|
||||
if(property.getExample() != null)
|
||||
return property.getExample();
|
||||
else
|
||||
return "0";
|
||||
}
|
||||
else if(property instanceof BooleanProperty) {
|
||||
if(property.getExample() != null)
|
||||
return property.getExample();
|
||||
else
|
||||
return "true";
|
||||
}
|
||||
else if(property instanceof LongProperty) {
|
||||
if(property.getExample() != null)
|
||||
return property.getExample();
|
||||
else
|
||||
return "123456";
|
||||
}
|
||||
return "not implemented " + property;
|
||||
}
|
||||
|
||||
protected String openTag(String name) {
|
||||
return "<" + name + ">";
|
||||
}
|
||||
|
||||
protected String closeTag(String name) {
|
||||
return "</" + name + ">";
|
||||
}
|
||||
|
||||
protected String indent(int indent) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for(int i = 0; i < indent; i++) {
|
||||
sb.append(" ");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
#---------------------------------------------------------------------
|
||||
# Global settings
|
||||
#---------------------------------------------------------------------
|
||||
global
|
||||
log 127.0.0.1 local2
|
||||
chroot /var/lib/haproxy
|
||||
pidfile /var/run/haproxy.pid
|
||||
maxconn 4000
|
||||
user haproxy
|
||||
group haproxy
|
||||
daemon
|
||||
|
||||
#---------------------------------------------------------------------
|
||||
# common defaults that all the 'listen' and 'backend' sections will
|
||||
# use if not designated in their block
|
||||
#---------------------------------------------------------------------
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option dontlognull
|
||||
option httpclose
|
||||
option httplog
|
||||
option forwardfor
|
||||
option redispatch
|
||||
timeout connect 10000 # default 10 second time out if a backend is not found
|
||||
timeout client 300000
|
||||
timeout server 300000
|
||||
maxconn 60000
|
||||
retries 3
|
||||
|
||||
#---------------------------------------------------------------------
|
||||
# main frontend which proxys to the backends
|
||||
#---------------------------------------------------------------------
|
||||
frontend main *:80
|
||||
default_backend app
|
||||
|
||||
acl is_swagger_online hdr_beg(host) -i online.swagger.io
|
||||
acl is_swagger_io hdr_beg(host) -i swagger.io
|
||||
acl is_old hdr_beg(host) -i swagger.wordnik.com
|
||||
acl is_old_editor hdr_beg(host) -i editor.swagger.wordnik.com
|
||||
acl is_validator_swagger path_beg /swagger.json
|
||||
|
||||
# online spec validator
|
||||
reqrep ([^\ ]*)\ /validator/(.*) \1\ /validator/validator/\2 if is_swagger_online
|
||||
|
||||
# something that didn't work
|
||||
reqrep ([^\ ]*)\ /swagger.json(.*) \1\ /validator/swagger.json if is_validator_swagger
|
||||
|
||||
# swagger schema
|
||||
reqrep ^([^\ :]*)\ /v2/schema.json(.*) \1\ /swagger-api/swagger-spec/master/schemas/v2.0/schema.json\2
|
||||
acl is_swagger_spec path_beg /swagger-api/swagger-spec
|
||||
|
||||
# swagger docs
|
||||
reqrep ^([^\ :]*)\ /swagger-core/documentation/annotations/apidocs/current(.*) \1\ /swagger-core/apidocs/\2
|
||||
acl is_swagger_docs path_beg /swagger-core/apidocs
|
||||
|
||||
use_backend github_swagger_io if is_swagger_docs
|
||||
use_backend validator if is_swagger_online
|
||||
use_backend validator if is_validator_swagger
|
||||
use_backend github_swagger_io if is_swagger_io !is_swagger_spec
|
||||
use_backend github_swagger_spec if is_swagger_spec
|
||||
|
||||
redirect location http://editor.swagger.io if is_old_editor
|
||||
redirect location http://swagger.io if is_old
|
||||
|
||||
#---------------------------------------------------------------------
|
||||
# round robin balancing between the various backends
|
||||
#---------------------------------------------------------------------
|
||||
backend github_swagger_io
|
||||
balance roundrobin
|
||||
server gh1 swagger-api.github.io:80 check
|
||||
|
||||
backend github_swagger_spec
|
||||
http-request set-header Host raw.githubusercontent.com
|
||||
rspirep ^Content-type:(.*) Content-Type:\ application/json
|
||||
rspirep ^Access-Control-Allow-Origin:(.*) Access-Control-Allow-Origin:*
|
||||
balance roundrobin
|
||||
server gh2 raw.githubusercontent.com:443 check ssl verify none
|
||||
|
||||
backend validator
|
||||
balance roundrobin
|
||||
server app1 127.0.0.1:8000 check
|
||||
|
||||
backend app
|
||||
balance roundrobin
|
||||
server app1 127.0.0.1:8000 check
|
||||
@@ -9,7 +9,7 @@ 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";
|
||||
|
||||
@@ -34,6 +34,17 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
apiPackage = "io.swagger.client.api";
|
||||
modelPackage = "io.swagger.client.model";
|
||||
|
||||
reservedWords = new HashSet<String> (
|
||||
Arrays.asList(
|
||||
"abstract", "continue", "for", "new", "switch", "assert",
|
||||
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private",
|
||||
"this", "break", "double", "implements", "protected", "throw", "byte", "else",
|
||||
"import", "public", "throws", "case", "enum", "instanceof", "return", "transient",
|
||||
"catch", "extends", "int", "short", "try", "char", "final", "interface", "static",
|
||||
"void", "class", "finally", "long", "strictfp", "volatile", "const", "float",
|
||||
"native", "super", "while")
|
||||
);
|
||||
|
||||
additionalProperties.put("invokerPackage", invokerPackage);
|
||||
additionalProperties.put("groupId", groupId);
|
||||
additionalProperties.put("artifactId", artifactId);
|
||||
@@ -71,11 +82,11 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
|
||||
@Override
|
||||
public String apiFileFolder() {
|
||||
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replaceAll("\\.", "/");
|
||||
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
public String modelFileFolder() {
|
||||
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replaceAll("\\.", "/");
|
||||
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -107,4 +118,49 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
type = swaggerType;
|
||||
return toModelName(type);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toVarName(String name) {
|
||||
// replace - with _ e.g. created-at => created_at
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// if it's all uppper case, do nothing
|
||||
if (name.matches("^[A-Z_]*$"))
|
||||
return name;
|
||||
|
||||
// camelize (lower first character) the variable name
|
||||
// pet_id => petId
|
||||
name = camelize(name, true);
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
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 AsyncScalaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.client";
|
||||
protected String groupId = "com.wordnik";
|
||||
protected String artifactId = "swagger-async-scala-client";
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String sourceFolder = "src/main/scala";
|
||||
protected String clientName = "SwaggerClient";
|
||||
protected String authScheme = "";
|
||||
protected boolean authPreemptive = false;
|
||||
protected boolean asyncHttpClient = !authScheme.isEmpty();
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "async-scala";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates an Asynchronous Scala client library.";
|
||||
}
|
||||
|
||||
public AsyncScalaClientCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code/async-scala";
|
||||
modelTemplateFiles.put("model.mustache", ".scala");
|
||||
apiTemplateFiles.put("api.mustache", ".scala");
|
||||
templateDir = "asyncscala";
|
||||
apiPackage = "io.swagger.client.api";
|
||||
modelPackage = "io.swagger.client.model";
|
||||
|
||||
reservedWords = new HashSet<String> (
|
||||
Arrays.asList(
|
||||
"abstract", "case", "catch", "class", "def", "do", "else", "extends",
|
||||
"false", "final", "finally", "for", "forSome", "if", "implicit",
|
||||
"import", "lazy", "match", "new", "null", "object", "override", "package",
|
||||
"private", "protected", "return", "sealed", "super", "this", "throw",
|
||||
"trait", "try", "true", "type", "val", "var", "while", "with", "yield")
|
||||
);
|
||||
|
||||
additionalProperties.put("invokerPackage", invokerPackage);
|
||||
additionalProperties.put("groupId", groupId);
|
||||
additionalProperties.put("artifactId", artifactId);
|
||||
additionalProperties.put("artifactVersion", artifactVersion);
|
||||
additionalProperties.put("asyncHttpClient", asyncHttpClient);
|
||||
additionalProperties.put("authScheme", authScheme);
|
||||
additionalProperties.put("authPreemptive", authPreemptive);
|
||||
additionalProperties.put("clientName", clientName);
|
||||
|
||||
supportingFiles.add(new SupportingFile("sbt.mustache", "", "build.sbt"));
|
||||
supportingFiles.add(new SupportingFile("client.mustache",
|
||||
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), clientName + ".scala"));
|
||||
|
||||
importMapping.remove("List");
|
||||
importMapping.remove("Set");
|
||||
importMapping.remove("Map");
|
||||
|
||||
importMapping.put("DateTime", "org.joda.time.DateTime");
|
||||
importMapping.put("ListBuffer", "scala.collections.mutable.ListBuffer");
|
||||
|
||||
typeMapping = new HashMap<String, String>();
|
||||
typeMapping.put("enum", "NSString");
|
||||
typeMapping.put("array", "List");
|
||||
typeMapping.put("set", "Set");
|
||||
typeMapping.put("boolean", "Boolean");
|
||||
typeMapping.put("string", "String");
|
||||
typeMapping.put("int", "Int");
|
||||
typeMapping.put("long", "Long");
|
||||
typeMapping.put("float", "Float");
|
||||
typeMapping.put("byte", "Byte");
|
||||
typeMapping.put("short", "Short");
|
||||
typeMapping.put("char", "Char");
|
||||
typeMapping.put("long", "Long");
|
||||
typeMapping.put("double", "Double");
|
||||
typeMapping.put("object", "Any");
|
||||
typeMapping.put("file", "File");
|
||||
|
||||
languageSpecificPrimitives = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"String",
|
||||
"boolean",
|
||||
"Boolean",
|
||||
"Double",
|
||||
"Int",
|
||||
"Long",
|
||||
"Float",
|
||||
"Object",
|
||||
"List",
|
||||
"Map")
|
||||
);
|
||||
instantiationTypes.put("array", "ListBuffer");
|
||||
instantiationTypes.put("map", "HashMap");
|
||||
}
|
||||
|
||||
@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 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 toModelName(type);
|
||||
}
|
||||
else
|
||||
type = swaggerType;
|
||||
return toModelName(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toInstantiationType(Property p) {
|
||||
if (p instanceof MapProperty) {
|
||||
MapProperty ap = (MapProperty) p;
|
||||
String inner = getSwaggerType(ap.getAdditionalProperties());
|
||||
return instantiationTypes.get("map") + "[String, " + inner + "]";
|
||||
}
|
||||
else if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
String inner = getSwaggerType(ap.getItems());
|
||||
return instantiationTypes.get("array") + "[" + inner + "]";
|
||||
}
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
public String toDefaultValue(Property p) {
|
||||
if(p instanceof StringProperty)
|
||||
return "null";
|
||||
else if (p instanceof BooleanProperty)
|
||||
return "null";
|
||||
else if(p instanceof DateProperty)
|
||||
return "null";
|
||||
else if(p instanceof DateTimeProperty)
|
||||
return "null";
|
||||
else if (p instanceof DoubleProperty)
|
||||
return "null";
|
||||
else if (p instanceof FloatProperty)
|
||||
return "null";
|
||||
else if (p instanceof IntegerProperty)
|
||||
return "null";
|
||||
else if (p instanceof LongProperty)
|
||||
return "null";
|
||||
else if (p instanceof MapProperty) {
|
||||
MapProperty ap = (MapProperty) p;
|
||||
String inner = getSwaggerType(ap.getAdditionalProperties());
|
||||
return "new HashMap[String, " + inner + "]() ";
|
||||
}
|
||||
else if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
String inner = getSwaggerType(ap.getItems());
|
||||
return "new ListBuffer[" + inner + "]() ";
|
||||
}
|
||||
else
|
||||
return "null";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
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",
|
||||
"boolean",
|
||||
"Boolean",
|
||||
"Double",
|
||||
"Integer",
|
||||
"Long",
|
||||
"Float",
|
||||
"Object")
|
||||
);
|
||||
instantiationTypes.put("array", "List");
|
||||
instantiationTypes.put("map", "Dictionary");
|
||||
|
||||
typeMapping = new HashMap<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 type;
|
||||
}
|
||||
}
|
||||
@@ -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";
|
||||
|
||||
@@ -80,13 +80,57 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
@Override
|
||||
public String apiFileFolder() {
|
||||
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replaceAll("\\.", "/");
|
||||
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
public String modelFileFolder() {
|
||||
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replaceAll("\\.", "/");
|
||||
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 (lower first character) the variable name
|
||||
// pet_id => petId
|
||||
name = camelize(name, true);
|
||||
|
||||
// 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) {
|
||||
@@ -116,4 +160,4 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
type = swaggerType;
|
||||
return toModelName(type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -1,110 +1,192 @@
|
||||
package com.wordnik.swagger.codegen.languages;
|
||||
|
||||
import com.wordnik.swagger.codegen.*;
|
||||
import com.wordnik.swagger.models.Model;
|
||||
import com.wordnik.swagger.models.properties.*;
|
||||
import com.wordnik.swagger.util.Json;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.*;
|
||||
import com.wordnik.swagger.models.properties.*;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
|
||||
public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "com.wordnik.client";
|
||||
protected String groupId = "com.wordnik";
|
||||
protected String artifactId = "swagger-client";
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String apiVersion = "1.0.0";
|
||||
protected int serverPort = 8080;
|
||||
protected String projectName = "swagger-server";
|
||||
|
||||
public String apiPackage() {
|
||||
return "controllers";
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the type of generator.
|
||||
*
|
||||
* @return the CodegenType for this generator
|
||||
* @see com.wordnik.swagger.codegen.CodegenType
|
||||
*/
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.SERVER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures a friendly name for the generator. This will be used by the generator
|
||||
* to select the library with the -l flag.
|
||||
*
|
||||
* @return the friendly name for the generator
|
||||
*/
|
||||
public String getName() {
|
||||
return "nodejs";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns human-friendly help for the generator. Provide the consumer with help
|
||||
* tips, parameters here
|
||||
*
|
||||
* @return A string value for the help message
|
||||
*/
|
||||
public String getHelp() {
|
||||
return "Generates a node.js server application compatible with the 1.2 swagger specification.";
|
||||
return "Generates a nodejs server library using the swagger-tools project. By default, " +
|
||||
"it will also generate service classes--which you can disable with the `-Dnoservice` environment variable.";
|
||||
}
|
||||
|
||||
public NodeJSServerCodegen() {
|
||||
super();
|
||||
|
||||
// set the output folder here
|
||||
outputFolder = "generated-code/nodejs";
|
||||
apiTemplateFiles.put("api.mustache", ".js");
|
||||
|
||||
/**
|
||||
* Models. You can write model files using the modelTemplateFiles map.
|
||||
* if you want to create one template for file, you can do so here.
|
||||
* for multiple files for model, just put another entry in the `modelTemplateFiles` with
|
||||
* a different extension
|
||||
*/
|
||||
modelTemplateFiles.clear();
|
||||
|
||||
/**
|
||||
* Api classes. You can write classes for each Api file with the apiTemplateFiles map.
|
||||
* as with models, add multiple entries with different extensions for multiple files per
|
||||
* class
|
||||
*/
|
||||
apiTemplateFiles.put(
|
||||
"controller.mustache", // the template to use
|
||||
".js"); // the extension for each file to write
|
||||
|
||||
/**
|
||||
* Template Location. This is the location which templates will be read from. The generator
|
||||
* will use the resource stream to attempt to read the templates.
|
||||
*/
|
||||
templateDir = "nodejs";
|
||||
apiPackage = "app.apis";
|
||||
modelPackage = "app";
|
||||
|
||||
additionalProperties.put("invokerPackage", invokerPackage);
|
||||
additionalProperties.put("groupId", groupId);
|
||||
additionalProperties.put("artifactId", artifactId);
|
||||
additionalProperties.put("artifactVersion", artifactVersion);
|
||||
|
||||
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
|
||||
supportingFiles.add(new SupportingFile("models.mustache", modelPackage, "models.js"));
|
||||
supportingFiles.add(new SupportingFile("main.mustache", "", "main.js"));
|
||||
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
|
||||
|
||||
languageSpecificPrimitives = new HashSet<String>(
|
||||
/**
|
||||
* Reserved words. Override this with reserved words specific to your language
|
||||
*/
|
||||
reservedWords = new HashSet<String> (
|
||||
Arrays.asList(
|
||||
"String",
|
||||
"boolean",
|
||||
"Boolean",
|
||||
"Double",
|
||||
"Integer",
|
||||
"Long",
|
||||
"Float")
|
||||
);
|
||||
typeMapping.put("array", "array");
|
||||
"break", "case", "class", "catch", "const", "continue", "debugger",
|
||||
"default", "delete", "do", "else", "export", "extends", "finally",
|
||||
"for", "function", "if", "import", "in", "instanceof", "let", "new",
|
||||
"return", "super", "switch", "this", "throw", "try", "typeof", "var",
|
||||
"void", "while", "with", "yield")
|
||||
);
|
||||
|
||||
/**
|
||||
* Additional Properties. These values can be passed to the templates and
|
||||
* are available in models, apis, and supporting files
|
||||
*/
|
||||
additionalProperties.put("apiVersion", apiVersion);
|
||||
additionalProperties.put("serverPort", serverPort);
|
||||
|
||||
/**
|
||||
* Supporting Files. You can write single files for the generator with the
|
||||
* entire object tree available. If the input file has a suffix of `.mustache
|
||||
* it will be processed by the template engine. Otherwise, it will be copied
|
||||
*/
|
||||
// supportingFiles.add(new SupportingFile("controller.mustache",
|
||||
// "controllers",
|
||||
// "controller.js")
|
||||
// );
|
||||
supportingFiles.add(new SupportingFile("swagger.mustache",
|
||||
"api",
|
||||
"swagger.json")
|
||||
);
|
||||
supportingFiles.add(new SupportingFile("index.mustache",
|
||||
"",
|
||||
"index.js")
|
||||
);
|
||||
supportingFiles.add(new SupportingFile("package.mustache",
|
||||
"",
|
||||
"package.json")
|
||||
);
|
||||
if(System.getProperty("noservice") == null) {
|
||||
apiTemplateFiles.put(
|
||||
"service.mustache", // the template to use
|
||||
"Service.js"); // the extension for each file to write
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiName(String name) {
|
||||
if(name.length() == 0)
|
||||
return "DefaultController";
|
||||
return initialCaps(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiFilename(String name) {
|
||||
return toApiName(name);
|
||||
}
|
||||
/**
|
||||
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
|
||||
* those terms here. This logic is only called if a variable matches the reseved words
|
||||
*
|
||||
* @return the escaped term
|
||||
*/
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
return "_" + name; // add an underscore to the name
|
||||
}
|
||||
|
||||
/**
|
||||
* Location to write api files. You can use the apiPackage() as defined when the class is
|
||||
* instantiated
|
||||
*/
|
||||
@Override
|
||||
public String apiFileFolder() {
|
||||
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
|
||||
List<Map<String, Object>> o = (List<Map<String, Object>>)objs.get("models");
|
||||
|
||||
for(Map<String, Object> modelMap : o) {
|
||||
try {
|
||||
CodegenModel m = (CodegenModel) modelMap.get("model");
|
||||
ObjectNode on = (ObjectNode) Json.mapper().readTree(m.modelJson);
|
||||
// inject the id field
|
||||
on.put("id", m.name);
|
||||
|
||||
// remove the definitions qualifier with this nasty hack
|
||||
m.modelJson = Json.pretty(on).replaceAll("\"#/definitions/", "\"");
|
||||
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
|
||||
Map<String, Object> objectMap = (Map<String, Object>)objs.get("operations");
|
||||
List<CodegenOperation> operations = (List<CodegenOperation>)objectMap.get("operation");
|
||||
for(CodegenOperation operation : operations) {
|
||||
operation.httpMethod = operation.httpMethod.toLowerCase();
|
||||
List<CodegenParameter> params = operation.allParams;
|
||||
if(params != null && params.size() == 0)
|
||||
operation.allParams = null;
|
||||
List<CodegenResponse> responses = operation.responses;
|
||||
if(responses != null) {
|
||||
for(CodegenResponse resp : responses) {
|
||||
if("0".equals(resp.code))
|
||||
resp.code = "default";
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
// skip conversion
|
||||
if(operation.examples != null && operation.examples.size() > 0) {
|
||||
List<Map<String, String>> examples = operation.examples;
|
||||
for(int i = examples.size() - 1; i >= 0; i--) {
|
||||
Map<String, String> example = examples.get(i);
|
||||
String contentType = example.get("contentType");
|
||||
if(contentType != null && contentType.indexOf("application/json") == 0) {
|
||||
String jsonExample = example.get("example");
|
||||
if(jsonExample != null) {
|
||||
jsonExample = jsonExample.replaceAll("\\\\n", "\n");
|
||||
example.put("example", jsonExample);
|
||||
}
|
||||
}
|
||||
else
|
||||
examples.remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
return objs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String apiFileFolder() {
|
||||
return outputFolder + File.separator + apiPackage().replaceAll("\\.", File.separator);
|
||||
}
|
||||
|
||||
public String modelFileFolder() {
|
||||
return outputFolder + File.separator + modelPackage().replaceAll("\\.", File.separator);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
return typeMapping.get(swaggerType);
|
||||
}
|
||||
else
|
||||
type = swaggerType;
|
||||
return toModelName(type);
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
templateDir = "objc";
|
||||
modelPackage = "";
|
||||
|
||||
additionalProperties.put("projectName", "swaggerClient");
|
||||
String appName = System.getProperty("appName");
|
||||
if(appName == null) {
|
||||
appName = "swaggerClient";
|
||||
}
|
||||
additionalProperties.put("projectName", appName);
|
||||
|
||||
defaultIncludes = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
@@ -44,6 +48,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
"NSObject",
|
||||
"NSArray",
|
||||
"NSNumber",
|
||||
"NSDate",
|
||||
"NSDictionary",
|
||||
"NSMutableArray",
|
||||
"NSMutableDictionary")
|
||||
@@ -53,6 +58,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
"NSNumber",
|
||||
"NSString",
|
||||
"NSObject",
|
||||
"NSDate",
|
||||
"bool")
|
||||
);
|
||||
|
||||
@@ -66,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");
|
||||
@@ -83,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")
|
||||
);
|
||||
|
||||
@@ -98,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"));
|
||||
@@ -147,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
|
||||
@@ -168,7 +209,18 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
protected void setNonArrayMapProperty(CodegenProperty property, String type) {
|
||||
super.setNonArrayMapProperty(property, type);
|
||||
if("NSDictionary".equals(type)) {
|
||||
property.setter = "initWithDictionary";
|
||||
}
|
||||
else {
|
||||
property.setter = "initWithValues";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toModelImport(String name) {
|
||||
if("".equals(modelPackage()))
|
||||
return name;
|
||||
@@ -218,4 +270,4 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,14 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
public PhpClientCodegen() {
|
||||
super();
|
||||
modelPackage = "models";
|
||||
|
||||
//TODO determine hte package name from host name
|
||||
invokerPackage = camelize("SwaggerPetstore");
|
||||
|
||||
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");
|
||||
@@ -38,7 +45,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
reservedWords = new HashSet<String> (
|
||||
Arrays.asList(
|
||||
"int")
|
||||
"__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor")
|
||||
);
|
||||
|
||||
additionalProperties.put("invokerPackage", invokerPackage);
|
||||
@@ -59,21 +66,24 @@ 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
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String apiFileFolder() {
|
||||
return outputFolder + "/" + apiPackage().replaceAll("\\.", "/");
|
||||
return outputFolder + "/" + apiPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
public String modelFileFolder() {
|
||||
return outputFolder + "/" + modelPackage().replaceAll("\\.", "/");
|
||||
return outputFolder + "/" + modelPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -111,4 +121,42 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
public String toDefaultValue(Property p) {
|
||||
return "null";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toVarName(String name) {
|
||||
// parameter name starting with number won't compile
|
||||
// need to escape it by appending _ at the beginning
|
||||
if (name.matches("^[0-9]")) {
|
||||
name = "_" + name;
|
||||
}
|
||||
|
||||
// return the name in underscore style
|
||||
// PhoneNumber => phone_number
|
||||
return underscore(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
|
||||
if(reservedWords.contains(name))
|
||||
escapeReservedWord(name); // e.g. return => _return
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ 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";
|
||||
@@ -50,11 +51,18 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
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"));
|
||||
supportingFiles.add(new SupportingFile("__init__.mustache", modelPackage.replaceAll("\\.", File.separator), "__init__.py"));
|
||||
supportingFiles.add(new SupportingFile("__init__.mustache", modelPackage.replace('.', File.separatorChar), "__init__.py"));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -64,11 +72,11 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
|
||||
@Override
|
||||
public String apiFileFolder() {
|
||||
return outputFolder + "/" + apiPackage().replaceAll("\\.", "/");
|
||||
return outputFolder + "/" + apiPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
public String modelFileFolder() {
|
||||
return outputFolder + "/" + modelPackage().replaceAll("\\.", "/");
|
||||
return outputFolder + "/" + modelPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
package com.wordnik.swagger.codegen.languages;
|
||||
|
||||
import com.wordnik.swagger.codegen.*;
|
||||
import com.wordnik.swagger.util.Json;
|
||||
import com.wordnik.swagger.models.properties.*;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
|
||||
public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "com.wordnik.client";
|
||||
protected String groupId = "com.wordnik";
|
||||
protected String artifactId = "swagger-client";
|
||||
protected String artifactVersion = "1.0.0";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "ruby";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Ruby client library.";
|
||||
}
|
||||
|
||||
public RubyClientCodegen() {
|
||||
super();
|
||||
modelPackage = "models";
|
||||
apiPackage = "lib";
|
||||
outputFolder = "generated-code/ruby";
|
||||
modelTemplateFiles.put("model.mustache", ".rb");
|
||||
apiTemplateFiles.put("api.mustache", ".rb");
|
||||
templateDir = "ruby";
|
||||
|
||||
typeMapping.clear();
|
||||
languageSpecificPrimitives.clear();
|
||||
|
||||
reservedWords = new HashSet<String> (
|
||||
Arrays.asList(
|
||||
"__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__",
|
||||
"begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN",
|
||||
"break", "do", "false", "next", "rescue", "then", "when", "END", "case",
|
||||
"else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif",
|
||||
"if", "not", "return", "undef", "yield")
|
||||
);
|
||||
|
||||
additionalProperties.put("invokerPackage", invokerPackage);
|
||||
additionalProperties.put("groupId", groupId);
|
||||
additionalProperties.put("artifactId", artifactId);
|
||||
additionalProperties.put("artifactVersion", artifactVersion);
|
||||
|
||||
languageSpecificPrimitives.add("int");
|
||||
languageSpecificPrimitives.add("array");
|
||||
languageSpecificPrimitives.add("map");
|
||||
languageSpecificPrimitives.add("string");
|
||||
languageSpecificPrimitives.add("DateTime");
|
||||
|
||||
typeMapping.put("long", "int");
|
||||
typeMapping.put("integer", "int");
|
||||
typeMapping.put("Array", "array");
|
||||
typeMapping.put("String", "string");
|
||||
typeMapping.put("List", "array");
|
||||
typeMapping.put("map", "map");
|
||||
|
||||
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"));
|
||||
supportingFiles.add(new SupportingFile("swagger/response.mustache", "", "lib/swagger/response.rb"));
|
||||
supportingFiles.add(new SupportingFile("swagger/version.mustache", "", "lib/swagger/version.rb"));
|
||||
supportingFiles.add(new SupportingFile("swagger/configuration.mustache", "", "lib/swagger/configuration.rb"));
|
||||
}
|
||||
|
||||
@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;
|
||||
if(type == null)
|
||||
return null;
|
||||
return type;
|
||||
}
|
||||
|
||||
public String toDefaultValue(Property p) {
|
||||
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";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -9,9 +9,9 @@ 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/java";
|
||||
protected String sourceFolder = "src/main/scala";
|
||||
protected String authScheme = "";
|
||||
protected boolean authPreemptive = false;
|
||||
protected boolean asyncHttpClient = !authScheme.isEmpty();
|
||||
@@ -106,11 +106,11 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
|
||||
@Override
|
||||
public String apiFileFolder() {
|
||||
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replaceAll("\\.", "/");
|
||||
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
public String modelFileFolder() {
|
||||
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replaceAll("\\.", "/");
|
||||
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -128,11 +128,11 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
|
||||
|
||||
@Override
|
||||
public String apiFileFolder() {
|
||||
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replaceAll("\\.", "/");
|
||||
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
public String modelFileFolder() {
|
||||
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replaceAll("\\.", "/");
|
||||
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
package com.wordnik.swagger.codegen.languages;
|
||||
|
||||
import com.wordnik.swagger.models.Operation;
|
||||
import com.wordnik.swagger.models.Path;
|
||||
import com.wordnik.swagger.util.Json;
|
||||
import com.wordnik.swagger.codegen.*;
|
||||
import com.wordnik.swagger.models.properties.*;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
|
||||
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 = "Petstore Server";
|
||||
|
||||
protected String configPackage = "";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.SERVER;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "spring-mvc";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Java Spring-MVC Server application using the SpringFox integration.";
|
||||
}
|
||||
|
||||
public SpringMVCServerCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code/javaSpringMVC";
|
||||
modelTemplateFiles.put("model.mustache", ".java");
|
||||
apiTemplateFiles.put("api.mustache", ".java");
|
||||
templateDir = "JavaSpringMVC";
|
||||
apiPackage = "io.swagger.api";
|
||||
modelPackage = "io.swagger.model";
|
||||
configPackage = "io.swagger.configuration";
|
||||
|
||||
|
||||
additionalProperties.put("invokerPackage", invokerPackage);
|
||||
additionalProperties.put("groupId", groupId);
|
||||
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",
|
||||
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
|
||||
supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
|
||||
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
|
||||
supportingFiles.add(new SupportingFile("apiResponseMessage.mustache",
|
||||
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
|
||||
supportingFiles.add(new SupportingFile("notFoundException.mustache",
|
||||
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
|
||||
|
||||
supportingFiles.add(new SupportingFile("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")
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
return getTypeDeclaration(inner);
|
||||
}
|
||||
return super.getTypeDeclaration(p);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
|
||||
String basePath = resourcePath;
|
||||
if(basePath.startsWith("/"))
|
||||
basePath = basePath.substring(1);
|
||||
int pos = basePath.indexOf("/");
|
||||
if(pos > 0)
|
||||
basePath = basePath.substring(0, pos);
|
||||
|
||||
if(basePath == "")
|
||||
basePath = "default";
|
||||
else {
|
||||
if(co.path.startsWith("/" + basePath))
|
||||
co.path = co.path.substring(("/" + basePath).length());
|
||||
co.subresourceOperation = !co.path.isEmpty();
|
||||
}
|
||||
List<CodegenOperation> opList = operations.get(basePath);
|
||||
if(opList == null) {
|
||||
opList = new ArrayList<CodegenOperation>();
|
||||
operations.put(basePath, opList);
|
||||
}
|
||||
opList.add(co);
|
||||
co.baseName = basePath;
|
||||
}
|
||||
|
||||
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
|
||||
Map<String, Object> operations = (Map<String, Object>)objs.get("operations");
|
||||
if(operations != null) {
|
||||
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
|
||||
for(CodegenOperation operation : ops) {
|
||||
if(operation.returnType == null)
|
||||
operation.returnType = "Void";
|
||||
else if(operation.returnType.startsWith("List")) {
|
||||
String rt = operation.returnType;
|
||||
int end = rt.lastIndexOf(">");
|
||||
if(end > 0) {
|
||||
operation.returnType = rt.substring("List<".length(), end);
|
||||
operation.returnContainer = "List";
|
||||
}
|
||||
}
|
||||
else if(operation.returnType.startsWith("Map")) {
|
||||
String rt = operation.returnType;
|
||||
int end = rt.lastIndexOf(">");
|
||||
if(end > 0) {
|
||||
operation.returnType = rt.substring("Map<".length(), end);
|
||||
operation.returnContainer = "Map";
|
||||
}
|
||||
}
|
||||
else if(operation.returnType.startsWith("Set")) {
|
||||
String rt = operation.returnType;
|
||||
int end = rt.lastIndexOf(">");
|
||||
if(end > 0) {
|
||||
operation.returnType = rt.substring("Set<".length(), end);
|
||||
operation.returnContainer = "Set";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return objs;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,12 +33,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");
|
||||
|
||||
@@ -23,7 +23,10 @@ public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
public SwaggerGenerator() {
|
||||
super();
|
||||
templateDir = "swagger";
|
||||
outputFolder = "generated-code/swagger";
|
||||
|
||||
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.wordnik.swagger.codegen.languages;
|
||||
|
||||
import com.wordnik.swagger.codegen.*;
|
||||
import com.wordnik.swagger.util.*;
|
||||
import com.wordnik.swagger.models.Swagger;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.DOCUMENTATION;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "swagger-yaml";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Creates a static swagger.yaml file.";
|
||||
}
|
||||
|
||||
public SwaggerYamlGenerator() {
|
||||
super();
|
||||
templateDir = "swagger";
|
||||
outputFolder = "generated-code/swagger";
|
||||
|
||||
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processSwagger(Swagger swagger) {
|
||||
try{
|
||||
String swaggerString = Yaml.mapper().writeValueAsString(swagger);
|
||||
String outputFile = outputFolder + File.separator + "swagger.yaml";
|
||||
FileUtils.writeStringToFile(new File(outputFile), swaggerString);
|
||||
System.out.println("wrote file to " + outputFile);
|
||||
}
|
||||
catch(Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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}}
|
||||
@@ -58,10 +61,10 @@ public class {{classname}} {
|
||||
Map<String, String> headerParams = new HashMap<String, String>();
|
||||
Map<String, String> formParams = new HashMap<String, String>();
|
||||
|
||||
{{#queryParams}}if(!"null".equals(String.valueOf({{paramName}})))
|
||||
queryParams.put("{{baseName}}", String.valueOf({{paramName}}));
|
||||
{{#queryParams}}if ({{paramName}} != null)
|
||||
queryParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));
|
||||
{{/queryParams}}
|
||||
{{#headerParams}}headerParams.put("{{baseName}}", {{paramName}});
|
||||
{{#headerParams}}headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));
|
||||
{{/headerParams}}
|
||||
String[] contentTypes = {
|
||||
{{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}}
|
||||
@@ -74,16 +77,17 @@ public class {{classname}} {
|
||||
FormDataMultiPart mp = new FormDataMultiPart();
|
||||
{{#formParams}}{{#notFile}}
|
||||
hasFields = true;
|
||||
mp.field("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE);
|
||||
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;
|
||||
}
|
||||
else {
|
||||
{{#formParams}}{{#notFile}}formParams.put("{{baseName}}", {{paramName}});{{/notFile}}
|
||||
{{#formParams}}{{#notFile}}formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}}
|
||||
{{/formParams}}
|
||||
}
|
||||
|
||||
@@ -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,19 +16,94 @@ 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;
|
||||
import java.io.IOException;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.text.ParseException;
|
||||
|
||||
public class ApiInvoker {
|
||||
private static ApiInvoker INSTANCE = new ApiInvoker();
|
||||
private Map<String, Client> hostMap = new HashMap<String, Client>();
|
||||
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
|
||||
private boolean isDebug = false;
|
||||
|
||||
/**
|
||||
* 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:ss.SSSZ");
|
||||
|
||||
/**
|
||||
* ISO 8601 date format.
|
||||
* @see https://en.wikipedia.org/wiki/ISO_8601
|
||||
*/
|
||||
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
|
||||
|
||||
static {
|
||||
// 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) {
|
||||
try {
|
||||
return DATE_TIME_FORMAT.parse(str);
|
||||
} catch (java.text.ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static Date parseDate(String str) {
|
||||
try {
|
||||
return DATE_FORMAT.parse(str);
|
||||
} catch (java.text.ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static String formatDateTime(Date datetime) {
|
||||
return DATE_TIME_FORMAT.format(datetime);
|
||||
}
|
||||
|
||||
public static String formatDate(Date date) {
|
||||
return DATE_FORMAT.format(date);
|
||||
}
|
||||
|
||||
public static String parameterToString(Object param) {
|
||||
if (param == null) {
|
||||
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;
|
||||
}
|
||||
@@ -51,8 +126,11 @@ public class ApiInvoker {
|
||||
}
|
||||
|
||||
public static Object deserialize(String json, String containerType, Class cls) throws ApiException {
|
||||
if(null != containerType) {
|
||||
containerType = containerType.toLowerCase();
|
||||
}
|
||||
try{
|
||||
if("List".equals(containerType)) {
|
||||
if("list".equals(containerType) || "array".equals(containerType)) {
|
||||
JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls);
|
||||
List response = (List<?>) JsonUtil.getJsonMapper().readValue(json, typeInfo);
|
||||
return response;
|
||||
@@ -103,12 +181,12 @@ public class ApiInvoker {
|
||||
|
||||
Builder builder = client.resource(host + path + querystring).accept("application/json");
|
||||
for(String key : headerParams.keySet()) {
|
||||
builder.header(key, headerParams.get(key));
|
||||
builder = builder.header(key, headerParams.get(key));
|
||||
}
|
||||
|
||||
for(String key : defaultHeaderMap.keySet()) {
|
||||
if(!headerParams.containsKey(key)) {
|
||||
builder.header(key, defaultHeaderMap.get(key));
|
||||
builder = builder.header(key, defaultHeaderMap.get(key));
|
||||
}
|
||||
}
|
||||
ClientResponse response = null;
|
||||
@@ -155,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));
|
||||
}
|
||||
@@ -166,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,8 +26,8 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
|
||||
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
|
||||
* maximum: {{maximum}}{{/maximum}}
|
||||
**/
|
||||
@ApiModelProperty(required = {{required}}, value = "{{{description}}}")
|
||||
@JsonProperty("{{name}}")
|
||||
@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>
|
||||
|
||||
@@ -2,7 +2,8 @@ package {{package}};
|
||||
|
||||
import {{modelPackage}}.*;
|
||||
|
||||
import com.wordnik.swagger.annotations.*;
|
||||
import com.wordnik.swagger.annotations.ApiParam;
|
||||
|
||||
import com.sun.jersey.multipart.FormDataParam;
|
||||
|
||||
{{#imports}}import {{import}};
|
||||
@@ -20,7 +21,7 @@ import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.*;
|
||||
|
||||
@Path("/{{baseName}}")
|
||||
@Api(value = "/{{baseName}}", description = "the {{baseName}} API")
|
||||
@com.wordnik.swagger.annotations.Api(value = "/{{baseName}}", description = "the {{baseName}} API")
|
||||
{{#operations}}
|
||||
public class {{classname}} {
|
||||
{{#operation}}
|
||||
@@ -28,10 +29,9 @@ public class {{classname}} {
|
||||
{{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}}
|
||||
{{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}}
|
||||
{{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
|
||||
// {{returnType}}
|
||||
@ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}})
|
||||
@ApiResponses(value = { {{#responses}}
|
||||
@ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},
|
||||
@com.wordnik.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}})
|
||||
@com.wordnik.swagger.annotations.ApiResponses(value = { {{#responses}}
|
||||
@com.wordnik.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},
|
||||
{{/hasMore}}{{/responses}} })
|
||||
|
||||
public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
|
||||
|
||||
@@ -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>{{^basePath}}/{{/basePath}}{{#basePath}}{{basePath}}{{/basePath}}</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>
|
||||
@@ -123,9 +119,18 @@
|
||||
<version>${servlet-api-version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>sonatype-snapshots</id>
|
||||
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
<properties>
|
||||
<swagger-core-version>1.5.1-M1</swagger-core-version>
|
||||
<jetty-version>8.1.11.v20130520</jetty-version>
|
||||
<swagger-core-version>2.1.0-M2</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,9 @@
|
||||
package {{apiPackage}};
|
||||
|
||||
public class ApiException extends Exception{
|
||||
private int code;
|
||||
public ApiException (int code, String msg) {
|
||||
super(msg);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package {{apiPackage}};
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.*;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
public class ApiOriginFilter implements javax.servlet.Filter {
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response,
|
||||
FilterChain chain) throws IOException, ServletException {
|
||||
HttpServletResponse res = (HttpServletResponse) response;
|
||||
res.addHeader("Access-Control-Allow-Origin", "*");
|
||||
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
|
||||
res.addHeader("Access-Control-Allow-Headers", "Content-Type");
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package {{apiPackage}};
|
||||
|
||||
import javax.xml.bind.annotation.XmlTransient;
|
||||
|
||||
@javax.xml.bind.annotation.XmlRootElement
|
||||
public class ApiResponseMessage {
|
||||
public static final int ERROR = 1;
|
||||
public static final int WARNING = 2;
|
||||
public static final int INFO = 3;
|
||||
public static final int OK = 4;
|
||||
public static final int TOO_BUSY = 5;
|
||||
|
||||
int code;
|
||||
String type;
|
||||
String message;
|
||||
|
||||
public ApiResponseMessage(){}
|
||||
|
||||
public ApiResponseMessage(int code, String message){
|
||||
this.code = code;
|
||||
switch(code){
|
||||
case ERROR:
|
||||
setType("error");
|
||||
break;
|
||||
case WARNING:
|
||||
setType("warning");
|
||||
break;
|
||||
case INFO:
|
||||
setType("info");
|
||||
break;
|
||||
case OK:
|
||||
setType("ok");
|
||||
break;
|
||||
case TOO_BUSY:
|
||||
setType("too busy");
|
||||
break;
|
||||
default:
|
||||
setType("unknown");
|
||||
break;
|
||||
}
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@XmlTransient
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isBodyParam}}
|
||||
@@ -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}}
|
||||
@@ -0,0 +1 @@
|
||||
{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@RequestHeader("{{paramName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}}
|
||||
@@ -0,0 +1,51 @@
|
||||
package {{package}};
|
||||
|
||||
{{#imports}}import {{import}};
|
||||
{{/imports}}
|
||||
|
||||
import com.wordnik.swagger.annotations.*;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
{{#models}}
|
||||
|
||||
{{#model}}{{#description}}
|
||||
/**
|
||||
* {{description}}
|
||||
**/{{/description}}
|
||||
@ApiModel(description = "{{{description}}}")
|
||||
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
|
||||
{{#vars}}{{#isEnum}}
|
||||
public enum {{datatypeWithEnum}} {
|
||||
{{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}}
|
||||
};
|
||||
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}}
|
||||
private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}}
|
||||
|
||||
{{#vars}}
|
||||
/**{{#description}}
|
||||
* {{{description}}}{{/description}}{{#minimum}}
|
||||
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
|
||||
* maximum: {{maximum}}{{/maximum}}
|
||||
**/
|
||||
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
|
||||
@JsonProperty("{{name}}")
|
||||
public {{{datatypeWithEnum}}} {{getter}}() {
|
||||
return {{name}};
|
||||
}
|
||||
public void {{setter}}({{{datatypeWithEnum}}} {{name}}) {
|
||||
this.{{name}} = {{name}};
|
||||
}
|
||||
|
||||
{{/vars}}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class {{classname}} {\n");
|
||||
{{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}}
|
||||
{{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n");
|
||||
{{/vars}}sb.append("}\n");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
{{/model}}
|
||||
{{/models}}
|
||||
@@ -0,0 +1,9 @@
|
||||
package {{apiPackage}};
|
||||
|
||||
public class NotFoundException extends ApiException {
|
||||
private int code;
|
||||
public NotFoundException (int code, String msg) {
|
||||
super(code, msg);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{{#isPathParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathVariable("{{paramName}}") {{{dataType}}} {{paramName}}{{/isPathParam}}
|
||||
@@ -0,0 +1,229 @@
|
||||
<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>
|
||||
<build>
|
||||
<sourceDirectory>src/main/java</sourceDirectory>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>2.1.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>2.6</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>integration-test</goal>
|
||||
<goal>verify</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<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>
|
||||
<webDefaultXml>${project.basedir}/conf/jetty/webdefault.xml</webDefaultXml>
|
||||
<stopPort>8079</stopPort>
|
||||
<stopKey>stopit</stopKey>
|
||||
<httpConnector>
|
||||
<port>8002</port>
|
||||
<idleTimeout>60000</idleTimeout>
|
||||
</httpConnector>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>start-jetty</id>
|
||||
<phase>pre-integration-test</phase>
|
||||
<goals>
|
||||
<goal>start</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<scanIntervalSeconds>0</scanIntervalSeconds>
|
||||
<daemon>true</daemon>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>stop-jetty</id>
|
||||
<phase>post-integration-test</phase>
|
||||
<goals>
|
||||
<goal>stop</goal>
|
||||
</goals>
|
||||
</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>
|
||||
<dependency>
|
||||
<groupId>com.wordnik</groupId>
|
||||
<artifactId>swagger-jersey-jaxrs</artifactId>
|
||||
<version>${swagger-core-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-log4j12</artifactId>
|
||||
<version>${slf4j-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey</groupId>
|
||||
<artifactId>jersey-core</artifactId>
|
||||
<version>${jersey-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey</groupId>
|
||||
<artifactId>jersey-json</artifactId>
|
||||
<version>${jersey-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey</groupId>
|
||||
<artifactId>jersey-servlet</artifactId>
|
||||
<version>${jersey-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey.contribs</groupId>
|
||||
<artifactId>jersey-multipart</artifactId>
|
||||
<version>${jersey-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.jersey</groupId>
|
||||
<artifactId>jersey-server</artifactId>
|
||||
<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>
|
||||
<version>${scala-test-version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit-version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>servlet-api</artifactId>
|
||||
<version>${servlet-api-version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<repositories>
|
||||
<repository>
|
||||
<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>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 @@
|
||||
sbt.version=0.12.0
|
||||
@@ -0,0 +1,9 @@
|
||||
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.8.4")
|
||||
|
||||
libraryDependencies <+= sbtVersion(v => v match {
|
||||
case "0.11.0" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.0-0.2.8"
|
||||
case "0.11.1" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.1-0.2.10"
|
||||
case "0.11.2" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.2-0.2.11"
|
||||
case "0.11.3" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.3-0.2.11.1"
|
||||
case x if (x.startsWith("0.12")) => "com.github.siasia" %% "xsbt-web-plugin" % "0.12.0-0.2.11.1"
|
||||
})
|
||||
@@ -0,0 +1 @@
|
||||
{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestParam("{{paramName}}") {{{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,13 +1,18 @@
|
||||
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.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.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.TizenClientCodegen
|
||||
com.wordnik.swagger.codegen.languages.PhpClientCodegen
|
||||
com.wordnik.swagger.codegen.languages.PythonClientCodegen
|
||||
com.wordnik.swagger.codegen.languages.SwaggerYamlGenerator
|
||||
com.wordnik.swagger.codegen.languages.TizenClientCodegen
|
||||
@@ -10,6 +10,9 @@ import java.util.*;
|
||||
{{#imports}}import {{import}};
|
||||
{{/imports}}
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.entity.mime.MultipartEntityBuilder;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.io.File;
|
||||
@@ -55,19 +58,46 @@ public class {{classname}} {
|
||||
|
||||
// query params
|
||||
Map<String, String> queryParams = new HashMap<String, String>();
|
||||
// header params
|
||||
Map<String, String> headerParams = new HashMap<String, String>();
|
||||
// form params
|
||||
Map<String, String> formParams = new HashMap<String, String>();
|
||||
|
||||
{{#queryParams}}if(!"null".equals(String.valueOf({{paramName}})))
|
||||
queryParams.put("{{baseName}}", String.valueOf({{paramName}}));
|
||||
{{#queryParams}}if ({{paramName}} != null)
|
||||
queryParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));
|
||||
{{/queryParams}}
|
||||
|
||||
{{#headerParams}}headerParams.put("{{baseName}}", {{paramName}});
|
||||
{{#headerParams}}headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));
|
||||
{{/headerParams}}
|
||||
|
||||
String contentType = "application/json";
|
||||
String[] contentTypes = {
|
||||
{{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}}
|
||||
};
|
||||
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
|
||||
|
||||
if (contentType.startsWith("multipart/form-data")) {
|
||||
// file uploading
|
||||
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
{{#formParams}}{{#notFile}}
|
||||
if ({{paramName}} != null) {
|
||||
builder.addTextBody("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), ApiInvoker.TEXT_PLAIN_UTF8);
|
||||
}
|
||||
{{/notFile}}{{#isFile}}
|
||||
if ({{paramName}} != null) {
|
||||
builder.addBinaryBody("{{baseName}}", {{paramName}});
|
||||
}
|
||||
{{/isFile}}{{/formParams}}
|
||||
|
||||
HttpEntity httpEntity = builder.build();
|
||||
postBody = httpEntity;
|
||||
} else {
|
||||
// normal form params
|
||||
{{#formParams}}{{#notFile}}formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}}
|
||||
{{/formParams}}
|
||||
}
|
||||
|
||||
try {
|
||||
String response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, contentType);
|
||||
String response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType);
|
||||
if(response != null){
|
||||
return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}};
|
||||
}
|
||||
@@ -75,12 +105,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}}
|
||||
|
||||
@@ -12,9 +12,11 @@ import org.apache.http.client.methods.*;
|
||||
import org.apache.http.conn.*;
|
||||
import org.apache.http.conn.scheme.*;
|
||||
import org.apache.http.conn.ssl.*;
|
||||
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;
|
||||
|
||||
@@ -23,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;
|
||||
@@ -40,6 +43,7 @@ import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
import java.util.Random;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
@@ -61,6 +65,77 @@ public class ApiInvoker {
|
||||
|
||||
private ClientConnectionManager ignoreSSLConnectionManager;
|
||||
|
||||
/** Content type "text/plain" with UTF-8 encoding. */
|
||||
public static final ContentType TEXT_PLAIN_UTF8 = ContentType.create("text/plain", Consts.UTF_8);
|
||||
|
||||
/**
|
||||
* 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:ss.SSSZ");
|
||||
|
||||
/**
|
||||
* ISO 8601 date format.
|
||||
* @see https://en.wikipedia.org/wiki/ISO_8601
|
||||
*/
|
||||
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
|
||||
|
||||
static {
|
||||
// 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) {
|
||||
try {
|
||||
return DATE_TIME_FORMAT.parse(str);
|
||||
} catch (java.text.ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static Date parseDate(String str) {
|
||||
try {
|
||||
return DATE_FORMAT.parse(str);
|
||||
} catch (java.text.ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static String formatDateTime(Date datetime) {
|
||||
return DATE_TIME_FORMAT.format(datetime);
|
||||
}
|
||||
|
||||
public static String formatDate(Date date) {
|
||||
return DATE_FORMAT.format(date);
|
||||
}
|
||||
|
||||
public static String parameterToString(Object param) {
|
||||
if (param == null) {
|
||||
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 ApiInvoker() {
|
||||
initConnectionManager();
|
||||
}
|
||||
@@ -83,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;
|
||||
@@ -91,7 +166,7 @@ public class ApiInvoker {
|
||||
else if(String.class.equals(cls)) {
|
||||
if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
|
||||
return json.substring(1, json.length() - 2);
|
||||
else
|
||||
else
|
||||
return json;
|
||||
}
|
||||
else {
|
||||
@@ -105,9 +180,9 @@ public class ApiInvoker {
|
||||
|
||||
public static String serialize(Object obj) throws ApiException {
|
||||
try {
|
||||
if (obj != null)
|
||||
if (obj != null)
|
||||
return JsonUtil.getJsonMapper().writeValueAsString(obj);
|
||||
else
|
||||
else
|
||||
return null;
|
||||
}
|
||||
catch (Exception e) {
|
||||
@@ -115,7 +190,7 @@ public class ApiInvoker {
|
||||
}
|
||||
}
|
||||
|
||||
public String invokeAPI(String host, String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, String contentType) throws ApiException {
|
||||
public String invokeAPI(String host, String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType) throws ApiException {
|
||||
HttpClient client = getClient(host);
|
||||
|
||||
StringBuilder b = new StringBuilder();
|
||||
@@ -136,7 +211,7 @@ public class ApiInvoker {
|
||||
for(String key : headerParams.keySet()) {
|
||||
headers.put(key, headerParams.get(key));
|
||||
}
|
||||
|
||||
|
||||
for(String key : defaultHeaderMap.keySet()) {
|
||||
if(!headerParams.containsKey(key)) {
|
||||
headers.put(key, defaultHeaderMap.get(key));
|
||||
@@ -144,9 +219,34 @@ public class ApiInvoker {
|
||||
}
|
||||
headers.put("Accept", "application/json");
|
||||
|
||||
// URL encoded string from form parameters
|
||||
String formParamStr = null;
|
||||
|
||||
// for form data
|
||||
if ("application/x-www-form-urlencoded".equals(contentType)) {
|
||||
StringBuilder formParamBuilder = new StringBuilder();
|
||||
|
||||
// encode the form params
|
||||
for (String key : formParams.keySet()) {
|
||||
String value = formParams.get(key);
|
||||
if (value != null && !"".equals(value.trim())) {
|
||||
if (formParamBuilder.length() > 0) {
|
||||
formParamBuilder.append("&");
|
||||
}
|
||||
try {
|
||||
formParamBuilder.append(URLEncoder.encode(key, "utf8")).append("=").append(URLEncoder.encode(value, "utf8"));
|
||||
}
|
||||
catch (Exception e) {
|
||||
// move on to next
|
||||
}
|
||||
}
|
||||
}
|
||||
formParamStr = formParamBuilder.toString();
|
||||
}
|
||||
|
||||
HttpResponse response = null;
|
||||
try{
|
||||
if("GET".equals(method)) {
|
||||
try {
|
||||
if ("GET".equals(method)) {
|
||||
HttpGet get = new HttpGet(url);
|
||||
get.addHeader("Accept", "application/json");
|
||||
for(String key : headers.keySet()) {
|
||||
@@ -156,10 +256,17 @@ public class ApiInvoker {
|
||||
}
|
||||
else if ("POST".equals(method)) {
|
||||
HttpPost post = new HttpPost(url);
|
||||
|
||||
if (body != null) {
|
||||
if (formParamStr != null) {
|
||||
post.setHeader("Content-Type", contentType);
|
||||
post.setEntity(new StringEntity(serialize(body), "UTF-8"));
|
||||
post.setEntity(new StringEntity(formParamStr, "UTF-8"));
|
||||
} else if (body != null) {
|
||||
if (body instanceof HttpEntity) {
|
||||
// this is for file uploading
|
||||
post.setEntity((HttpEntity) body);
|
||||
} else {
|
||||
post.setHeader("Content-Type", contentType);
|
||||
post.setEntity(new StringEntity(serialize(body), "UTF-8"));
|
||||
}
|
||||
}
|
||||
for(String key : headers.keySet()) {
|
||||
post.setHeader(key, headers.get(key));
|
||||
@@ -168,7 +275,10 @@ public class ApiInvoker {
|
||||
}
|
||||
else if ("PUT".equals(method)) {
|
||||
HttpPut put = new HttpPut(url);
|
||||
if(body != null) {
|
||||
if (formParamStr != null) {
|
||||
put.setHeader("Content-Type", contentType);
|
||||
put.setEntity(new StringEntity(formParamStr, "UTF-8"));
|
||||
} else if (body != null) {
|
||||
put.setHeader("Content-Type", contentType);
|
||||
put.setEntity(new StringEntity(serialize(body), "UTF-8"));
|
||||
}
|
||||
@@ -186,8 +296,10 @@ public class ApiInvoker {
|
||||
}
|
||||
else if ("PATCH".equals(method)) {
|
||||
HttpPatch patch = new HttpPatch(url);
|
||||
|
||||
if (body != null) {
|
||||
if (formParamStr != null) {
|
||||
patch.setHeader("Content-Type", contentType);
|
||||
patch.setEntity(new StringEntity(formParamStr, "UTF-8"));
|
||||
} else if (body != null) {
|
||||
patch.setHeader("Content-Type", contentType);
|
||||
patch.setEntity(new StringEntity(serialize(body), "UTF-8"));
|
||||
}
|
||||
@@ -199,13 +311,14 @@ public class ApiInvoker {
|
||||
|
||||
int code = response.getStatusLine().getStatusCode();
|
||||
String responseString = null;
|
||||
if(code == 204)
|
||||
if(code == 204)
|
||||
responseString = "";
|
||||
else if(code >= 200 && code < 300) {
|
||||
if(response.getEntity() != null) {
|
||||
HttpEntity resEntity = response.getEntity();
|
||||
responseString = EntityUtils.toString(resEntity);
|
||||
}
|
||||
return responseString;
|
||||
}
|
||||
else {
|
||||
if(response.getEntity() != null) {
|
||||
@@ -214,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());
|
||||
@@ -270,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) {
|
||||
|
||||
@@ -26,8 +26,8 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
|
||||
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
|
||||
* maximum: {{maximum}}{{/maximum}}
|
||||
**/
|
||||
@ApiModelProperty(required = {{required}}, value = "{{{description}}}")
|
||||
@JsonProperty("{{name}}")
|
||||
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
|
||||
@JsonProperty("{{baseName}}")
|
||||
public {{{datatypeWithEnum}}} {{getter}}() {
|
||||
return {{name}};
|
||||
}
|
||||
|
||||
@@ -136,6 +136,12 @@
|
||||
<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>
|
||||
@@ -157,6 +163,6 @@
|
||||
<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.0</httpclient-version>
|
||||
<httpclient-version>4.3.6</httpclient-version>
|
||||
</properties>
|
||||
</project>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user