Compare commits

..

173 Commits

Author SHA1 Message Date
ShubhamRwt
c2597a585e Publish of Github pages from Gradle. 2022-03-01 00:38:53 +05:30
Travis CI User
4df779b4cc Publish of Github pages from Gradle. 2019-03-21 14:46:25 +00:00
Travis CI User
8b9d3fe588 Publish of Github pages from Gradle. 2019-03-21 14:45:30 +00:00
Travis CI User
4d4f4ad7d2 Publish of Github pages from Gradle. 2018-11-21 12:08:28 +00:00
Travis CI User
40467c0186 Publish of Github pages from Gradle. 2018-11-05 09:47:30 +00:00
Travis CI User
a2dc4080d5 Publish of Github pages from Gradle. 2018-10-22 18:25:29 +00:00
Travis CI User
76dced1209 Publish of Github pages from Gradle. 2018-10-18 07:25:26 +00:00
Travis CI User
1060b78622 Publish of Github pages from Gradle. 2018-10-15 08:19:24 +00:00
Travis CI User
23d3f336d5 Publish of Github pages from Gradle. 2018-08-06 10:54:24 +00:00
Travis CI User
5a70512c23 Publish of Github pages from Gradle. 2018-08-06 08:34:24 +00:00
Travis CI User
3c94b8605f Publish of Github pages from Gradle. 2018-07-12 13:28:18 +00:00
Travis CI User
e17311bd7e Publish of Github pages from Gradle. 2018-05-01 19:39:44 +00:00
Travis CI User
fecb5e2e61 Publish of Github pages from Gradle. 2018-04-29 09:46:16 +00:00
Travis CI User
79629d11ae Publish of Github pages from Gradle. 2018-04-27 11:47:33 +00:00
Robert Winkler
6f1efabf94 Publish of Github pages from Gradle. 2018-04-27 11:39:52 +00:00
Travis CI User
393bbe10fd Publish of Github pages from Gradle. 2017-10-09 09:00:12 +00:00
Travis CI User
ab0ce79172 Publish of Github pages from Gradle. 2017-10-05 17:44:55 +00:00
travis
1311ce90b9 Publish of Github pages from Gradle. 2017-07-20 14:37:35 +00:00
travis
e19ed182ff Publish of Github pages from Gradle. 2017-07-17 07:18:40 +00:00
travis
8797e00321 Publish of Github pages from Gradle. 2017-07-17 07:17:54 +00:00
travis
1721a95e07 Publish of Github pages from Gradle. 2017-07-11 07:09:07 +00:00
travis
dac7550bcc Publish of Github pages from Gradle. 2017-05-15 11:08:59 +00:00
travis
44c0507b4e Publish of Github pages from Gradle. 2017-05-15 06:49:19 +00:00
travis
e69b8295dd Publish of Github pages from Gradle. 2017-03-20 11:36:59 +00:00
travis
e8cec2467b Publish of Github pages from Gradle. 2017-03-20 11:33:58 +00:00
Robert Winkler
2cf2593e96 Publish of Github pages from Gradle. 2017-03-20 12:33:47 +01:00
travis
f1a1e52988 Publish of Github pages from Gradle. 2017-03-20 11:32:21 +00:00
travis
820d6dcb47 Publish of Github pages from Gradle. 2017-03-17 08:28:47 +00:00
travis
ea7643fc67 Publish of Github pages from Gradle. 2017-03-16 08:04:55 +00:00
travis
72b84a184e Publish of Github pages from Gradle. 2017-03-14 15:46:39 +00:00
travis
42b0cf8cf0 Publish of Github pages from Gradle. 2017-02-20 07:45:53 +00:00
travis
b0390b1f9a Publish of Github pages from Gradle. 2017-02-20 07:43:57 +00:00
travis
634598c5d4 Publish of Github pages from Gradle. 2017-02-20 07:42:15 +00:00
travis
e08de663d5 Publish of Github pages from Gradle. 2017-02-20 07:41:36 +00:00
Robert Winkler
76347aa49e Publish of Github pages from Gradle. 2017-02-20 08:36:53 +01:00
travis
b0d6183de3 Publish of Github pages from Gradle. 2017-02-03 08:37:29 +00:00
travis
67fe8f70b3 Publish of Github pages from Gradle. 2017-02-03 08:11:18 +00:00
travis
8bcbb5fcfa Publish of Github pages from Gradle. 2017-02-02 08:00:52 +00:00
travis
972497a9a5 Publish of Github pages from Gradle. 2017-01-21 09:37:50 +00:00
travis
fbb98fb446 Publish of Github pages from Gradle. 2017-01-19 13:28:45 +00:00
travis
27a34c519b Publish of Github pages from Gradle. 2017-01-19 13:21:53 +00:00
travis
8ab88d95c8 Publish of Github pages from Gradle. 2017-01-19 09:27:37 +00:00
travis
ca60025907 Publish of Github pages from Gradle. 2017-01-18 11:01:05 +00:00
travis
184b0222a3 Publish of Github pages from Gradle. 2017-01-18 10:55:07 +00:00
travis
b6f4cec736 Publish of Github pages from Gradle. 2017-01-17 09:46:43 +00:00
travis
66fad7ea30 Publish of Github pages from Gradle. 2017-01-13 13:16:54 +00:00
travis
57fa494b95 Publish of Github pages from Gradle. 2017-01-13 13:16:12 +00:00
travis
5ec39bba49 Publish of Github pages from Gradle. 2017-01-13 13:15:29 +00:00
travis
9ecad42092 Publish of Github pages from Gradle. 2017-01-13 13:15:23 +00:00
travis
8914176db0 Publish of Github pages from Gradle. 2017-01-13 12:56:11 +00:00
travis
66757a39fd Publish of Github pages from Gradle. 2017-01-13 12:55:55 +00:00
travis
05818f8abf Publish of Github pages from Gradle. 2017-01-09 11:23:23 +00:00
travis
f6edc96b49 Publish of Github pages from Gradle. 2017-01-05 13:33:25 +00:00
travis
5818025e65 Publish of Github pages from Gradle. 2017-01-05 13:33:07 +00:00
Robert Winkler
cd4a65c3d8 Publish of Github pages from Gradle. 2017-01-05 14:28:10 +01:00
travis
6f0e33c6d5 Publish of Github pages from Gradle. 2017-01-03 15:04:35 +00:00
travis
8a4ec35d47 Publish of Github pages from Gradle. 2017-01-03 14:31:53 +00:00
travis
319a8b68a8 Publish of Github pages from Gradle. 2017-01-03 10:25:50 +00:00
travis
109710b94e Publish of Github pages from Gradle. 2017-01-02 12:50:46 +00:00
travis
f02606abfc Publish of Github pages from Gradle. 2016-12-20 13:10:53 +00:00
travis
324f9a719c Publish of Github pages from Gradle. 2016-12-19 15:08:47 +00:00
travis
ac8332f1ed Publish of Github pages from Gradle. 2016-12-13 09:48:01 +00:00
travis
0cc153d896 Publish of Github pages from Gradle. 2016-12-13 09:02:35 +00:00
travis
9652d91723 Publish of Github pages from Gradle. 2016-12-09 08:21:39 +00:00
travis
dfab76f1c2 Publish of Github pages from Gradle. 2016-11-30 08:22:40 +00:00
Robert Winkler
711886bb90 Publish of Github pages from Gradle. 2016-11-30 09:17:48 +01:00
Robert Winkler
4f001e104f Publish of Github pages from Gradle. 2016-11-30 09:16:40 +01:00
travis
2befad39d0 Publish of Github pages from Gradle. 2016-11-30 08:12:17 +00:00
travis
223250693c Publish of Github pages from Gradle. 2016-11-18 11:41:40 +00:00
travis
8e6737fe79 Publish of Github pages from Gradle. 2016-11-16 11:58:01 +00:00
travis
667bd30dfd Publish of Github pages from Gradle. 2016-11-15 13:54:25 +00:00
travis
4a6c1a6e32 Publish of Github pages from Gradle. 2016-11-15 10:16:09 +00:00
travis
b365766cb4 Publish of Github pages from Gradle. 2016-11-14 15:21:40 +00:00
travis
7279daf5df Publish of Github pages from Gradle. 2016-11-11 13:26:54 +00:00
travis
5af951598d Publish of Github pages from Gradle. 2016-11-10 11:48:01 +00:00
travis
ffa27aa177 Publish of Github pages from Gradle. 2016-11-09 15:35:07 +00:00
travis
57a61ce839 Publish of Github pages from Gradle. 2016-11-04 14:38:15 +00:00
travis
a6576761c7 Publish of Github pages from Gradle. 2016-11-02 07:52:04 +00:00
travis
c427efaca3 Publish of Github pages from Gradle. 2016-11-01 13:51:22 +00:00
travis
ff2e3654c1 Publish of Github pages from Gradle. 2016-11-01 08:01:19 +00:00
travis
86b7577fd0 Publish of Github pages from Gradle. 2016-11-01 06:10:51 +00:00
travis
dd04f559d5 Publish of Github pages from Gradle. 2016-10-28 07:14:15 +00:00
travis
d828ab31f9 Publish of Github pages from Gradle. 2016-10-25 13:33:40 +00:00
travis
586596c5a1 Publish of Github pages from Gradle. 2016-10-18 13:47:49 +00:00
travis
00e723fbb8 Publish of Github pages from Gradle. 2016-10-18 13:35:44 +00:00
travis
5f844db4c5 Publish of Github pages from Gradle. 2016-10-18 13:26:17 +00:00
travis
fe93add209 Publish of Github pages from Gradle. 2016-10-14 05:17:51 +00:00
travis
753ad57059 Publish of Github pages from Gradle. 2016-10-12 06:53:21 +00:00
travis
c2a8d0d5eb Publish of Github pages from Gradle. 2016-10-03 11:52:30 +00:00
travis
36958d78aa Publish of Github pages from Gradle. 2016-09-23 08:37:11 +00:00
travis
704e20ef5c Publish of Github pages from Gradle. 2016-09-23 08:27:38 +00:00
travis
0104b8cfe8 Publish of Github pages from Gradle. 2016-09-23 07:00:22 +00:00
travis
43292024b6 Publish of Github pages from Gradle. 2016-09-14 08:02:58 +00:00
travis
ca8cc35004 Publish of Github pages from Gradle. 2016-09-12 08:08:19 +00:00
travis
f427e77b78 Publish of Github pages from Gradle. 2016-09-12 07:56:01 +00:00
travis
4d876c33a6 Publish of Github pages from Gradle. 2016-08-31 08:29:02 +00:00
travis
04f6239fd3 Publish of Github pages from Gradle. 2016-08-25 11:56:37 +00:00
travis
156f1ce880 Publish of Github pages from Gradle. 2016-08-12 18:06:22 +00:00
travis
836fcd6829 Publish of Github pages from Gradle. 2016-08-04 10:16:16 +00:00
travis
4a741acda2 Publish of Github pages from Gradle. 2016-08-04 08:37:40 +00:00
travis
857dd34992 Publish of Github pages from Gradle. 2016-08-04 08:20:52 +00:00
travis
84ad0ccaa7 Publish of Github pages from Gradle. 2016-08-04 08:15:23 +00:00
travis
128710cf50 Publish of Github pages from Gradle. 2016-08-04 08:14:44 +00:00
Robert Winkler
26cd23941a Publish of Github pages from Gradle. 2016-08-04 10:06:56 +02:00
Robert Winkler
d51684196d Publish of Github pages from Gradle. 2016-08-04 09:55:43 +02:00
travis
3f2f91f134 Publish of Github pages from Gradle. 2016-08-03 08:18:53 +00:00
travis
c62bcb02c2 Publish of Github pages from Gradle. 2016-07-30 18:37:46 +00:00
travis
de76eac12e Publish of Github pages from Gradle. 2016-06-01 13:05:39 +00:00
travis
dee68deb4d Publish of Github pages from Gradle. 2016-05-29 05:16:30 +00:00
travis
df4b6b8684 Publish of Github pages from Gradle. 2016-05-28 19:23:56 +00:00
travis
b49b7e01b9 Publish of Github pages from Gradle. 2016-05-28 18:55:43 +00:00
travis
12d3a5569a Publish of Github pages from Gradle. 2016-05-28 18:54:01 +00:00
travis
839a67aa18 Publish of Github pages from Gradle. 2016-05-28 18:53:07 +00:00
travis
c9a4e174db Publish of Github pages from Gradle. 2016-05-28 18:40:39 +00:00
travis
92adc61544 Publish of Github pages from Gradle. 2016-05-28 18:31:39 +00:00
travis
de24d5811c Publish of Github pages from Gradle. 2016-05-28 18:30:21 +00:00
travis
35e953d6b2 Publish of Github pages from Gradle. 2016-05-28 18:26:24 +00:00
travis
2728708af3 Publish of Github pages from Gradle. 2016-05-26 14:28:17 +00:00
travis
6f75fb6649 Publish of Github pages from Gradle. 2016-05-26 11:28:28 +00:00
travis
19dc822316 Publish of Github pages from Gradle. 2016-05-26 09:30:26 +00:00
travis
94d08b24d1 Publish of Github pages from Gradle. 2016-05-26 06:29:44 +00:00
travis
0a92457e41 Publish of Github pages from Gradle. 2016-05-24 12:26:44 +00:00
travis
03f19e7c25 Publish of Github pages from Gradle. 2016-05-12 08:01:55 +00:00
travis
4ddab7c8be Publish of Github pages from Gradle. 2016-05-04 19:11:52 +00:00
travis
101883f3b3 Publish of Github pages from Gradle. 2016-05-02 11:29:16 +00:00
travis
49da3d0fef Publish of Github pages from Gradle. 2016-05-02 11:13:15 +00:00
travis
6858dcd424 Publish of Github pages from Gradle. 2016-04-19 11:14:15 +00:00
travis
21e37a8cb3 Publish of Github pages from Gradle. 2016-04-19 08:58:24 +00:00
travis
7f116674b5 Publish of Github pages from Gradle. 2016-04-19 08:44:28 +00:00
travis
9c31fc416c Publish of Github pages from Gradle. 2016-04-15 10:29:41 +00:00
travis
0da081c0b4 Publish of Github pages from Gradle. 2016-04-14 15:57:42 +00:00
travis
d4973918f6 Publish of Github pages from Gradle. 2016-04-14 14:52:22 +00:00
travis
0ecda51555 Publish of Github pages from Gradle. 2016-04-14 14:47:54 +00:00
travis
de26a4fec3 Publish of Github pages from Gradle. 2016-04-14 13:59:44 +00:00
travis
f6481a7f21 Publish of Github pages from Gradle. 2016-04-14 13:39:05 +00:00
travis
f5291e3450 Publish of Github pages from Gradle. 2016-04-14 10:43:33 +00:00
Robert Winkler
ddf3265d4b Publish of Github pages from Gradle. 2016-04-13 14:23:51 +02:00
Robert Winkler
653420fa02 Publish of Github pages from Gradle. 2016-04-13 14:07:15 +02:00
Robert Winkler
a98247adb4 Publish of Github pages from Gradle. 2016-04-12 16:06:31 +02:00
Robert Winkler
f26ba312a7 Publish of Github pages from Gradle. 2016-04-06 13:05:42 +02:00
Robert Winkler
447c4ca3c2 Publish of Github pages from Gradle. 2016-04-06 09:31:48 +02:00
Robert Winkler
6189f710e1 Publish of Github pages from Gradle. 2016-04-06 09:29:37 +02:00
Robert Winkler
5dcb0a3549 Publish of Github pages from Gradle. 2016-04-06 09:22:13 +02:00
Robert Winkler
060f3f859b Publish of Github pages from Gradle. 2016-04-06 09:04:53 +02:00
Robert Winkler
e465c7ff26 Publish of Github pages from Gradle. 2016-04-06 09:01:57 +02:00
Robert Winkler
152083bfa6 Publish of Github pages from Gradle. 2016-04-06 08:55:35 +02:00
Robert Winkler
5b2c34657e Publish of Github pages from Gradle. 2016-04-06 08:20:04 +02:00
Robert Winkler
d0fba73012 Publish of Github pages from Gradle. 2016-04-06 08:12:44 +02:00
Robert Winkler
1703b26626 Publish of Github pages from Gradle. 2016-04-06 08:01:49 +02:00
Robert Winkler
08e445c579 Publish of Github pages from Gradle. 2016-04-05 15:56:09 +02:00
Robert Winkler
da792f6fb8 Publish of Github pages from Gradle. 2016-04-05 15:54:50 +02:00
Robert Winkler
dd606d65ad Publish of Github pages from Gradle. 2016-04-05 15:53:40 +02:00
Robert Winkler
416aefdaf0 Publish of Github pages from Gradle. 2016-04-05 15:51:30 +02:00
Robert Winkler
b725e7324f Publish of Github pages from Gradle. 2016-04-05 15:47:36 +02:00
Robert Winkler
ffb53aac33 Publish of Github pages from Gradle. 2016-04-05 15:37:14 +02:00
Robert Winkler
cbf1b50107 Publish of Github pages from Gradle. 2016-04-05 15:21:09 +02:00
Robert Winkler
92438b20db Publish of Github pages from Gradle. 2016-04-05 15:14:04 +02:00
Robert Winkler
4134a78185 Publish of Github pages from Gradle. 2016-04-05 15:06:46 +02:00
Robert Winkler
ea8829a288 Publish of Github pages from Gradle. 2016-04-05 15:03:20 +02:00
Robert Winkler
268815ac10 Publish of Github pages from Gradle. 2016-04-05 14:57:10 +02:00
Robert Winkler
4ebfda1e94 Publish of Github pages from Gradle. 2016-04-05 14:53:52 +02:00
Robert Winkler
6c7a9ad46e Publish of Github pages from Gradle. 2016-04-05 13:43:44 +02:00
Robert Winkler
857ae5a3f7 Publish of Github pages from Gradle. 2016-04-05 13:18:16 +02:00
Robert Winkler
b881d7f8b5 Publish of Github pages from Gradle. 2016-04-04 16:39:03 +02:00
Robert Winkler
8014c4ba77 Publish of Github pages from Gradle. 2016-04-04 12:23:24 +02:00
Robert Winkler
8443ddc2dc Publish of Github pages from Gradle. 2016-04-04 11:19:21 +02:00
Robert Winkler
a6cf1b51c6 Publish of Github pages from Gradle. 2016-04-04 11:16:38 +02:00
Robert Winkler
5065d4c744 Publish of Github pages from Gradle. 2016-04-01 15:00:21 +02:00
Robert Winkler
7435dc8e1a Publish of Github pages from Gradle. 2016-04-01 14:56:41 +02:00
Robert Winkler
4eb0ee49f6 Publish of Github pages from Gradle. 2016-03-23 16:32:14 +01:00
Robert Winkler
b8984ca5f5 Publish of Github pages from Gradle. 2016-03-22 16:39:07 +01:00
Robert Winkler
b2bceaece0 Publish of Github pages from Gradle. 2016-03-22 16:34:23 +01:00
Robert Winkler
79446a84f1 Publish of Github pages from Gradle. 2016-03-10 10:06:42 +01:00
204 changed files with 9446 additions and 29100 deletions

5
.gitignore vendored
View File

@@ -1,5 +0,0 @@
.idea
*.iml
.gradle
build
/bin/

View File

@@ -1,18 +0,0 @@
language: java
jdk:
- oraclejdk8
before_install:
- chmod +x gradlew
after_success:
- ./gradlew jacocoTestReport coveralls
- ./gradlew artifactoryPublish -PbintrayUsername="${BINTRAY_USER}" -PbintrayApiKey="${BINTRAY_KEY}"
- ./gradlew publishGhPages -PgithubUser="${GITHUB_USER}" -PgithubPassword="${GITHUB_PASSWORD}"
--stacktrace
notifications:
slack: swagger2markup:Zz5kz0SnvtG6aVvZUM8yMkER
env:
global:
- secure: SPKolgUdjIa/uJ+7/B/GPFlsa8IZg7NuZdFA8zROTaqew/xu+oX7qVGImseeBpPIEPJb02ac6hr7Y3/zvv0GJxIPtIbyDzVh73ImQUhT1ttLYGJfITAWqAPFF7RNNMtuOl3S2DLZ5OMJddkcFp00pa9nyI82Gk47B8GsaGIntAI=
- secure: nXXuHfvFACZwdiFM3Ta0x/f49N7cAgi0AMkgEnQrh/2xWlvQk2z2ySGJQLkhJ7Wy8LDY7Yt1b1GUt6DlP3PuFFMW/cT4iARewqiJRXZXxUQz8fpTDeTo1nmVmW/zzII6Qj3QHM3NRbR/xDOVSJiT30Hnq2hcCBQJWYsTICmzjRk=
- secure: Ia/wJ572M2II76roFeGEVCzIiktG4v2j/reSn60fpk1gnoEPQEObL4j1dbVCgXBLz54YWcaQ3mICvOfBPPEl9IIV3Y6DDE2sBOmB3soznfdA/YVnJx0h0f1pfXu1dwqoiv1sgc1wewQuUWq+FV7xeDhFE3cnh9CXIexe9ykip8k=
- secure: GWfhYDsHRmTfOuEOIcHY8kT4jKBTbdhNLDQ/2amY06xenFblb4pEn6pgmn4IdK3ytjNovnZPTOOK8HqdEjhbfIGoQt6PZwuyANn4Df+zdqOC0+V+7DFG2QhEhbRCyEwPlDqTPjxlOMfAmvjFuY/NvQywoF3PYUyMfJwUV8ehmYk=

View File

Before

Width:  |  Height:  |  Size: 130 KiB

After

Width:  |  Height:  |  Size: 130 KiB

View File

Before

Width:  |  Height:  |  Size: 116 KiB

After

Width:  |  Height:  |  Size: 116 KiB

View File

Before

Width:  |  Height:  |  Size: 133 KiB

After

Width:  |  Height:  |  Size: 133 KiB

View File

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 46 KiB

View File

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 38 KiB

View File

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 35 KiB

3120
1.3.1/index.html Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

3120
1.3.3/index.html Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

3206
1.3.4/index.html Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +0,0 @@
Thanks for raising a Swagger2Markup issue. Please provide a brief description of your problem along with the Swagger2Markup version you are using. If possible, please also consider putting together a complete Swagger specification that reproduces the issue. It's better if the Swagger specification is small and isolate the issue.
Swagger2Markup version:
Problem description:

View File

@@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -1,66 +0,0 @@
= Swagger2Markup
:author: Robert Winkler
:hardbreaks:
image:https://travis-ci.org/Swagger2Markup/swagger2markup.svg?branch=master["Build Status", link="https://travis-ci.org/Swagger2Markup/swagger2markup"] image:https://coveralls.io/repos/Swagger2Markup/swagger2markup/badge.svg["Coverage Status", link="https://coveralls.io/r/Swagger2Markup/swagger2markup"] image:https://api.codacy.com/project/badge/grade/498a6a39d7d84ff687546359f58ee18d["Codacy code quality", link="https://www.codacy.com/app/robwin/swagger2markup"] image:https://api.bintray.com/packages/swagger2markup/Maven/swagger2markup/images/download.svg[link="https://bintray.com/swagger2markup/Maven/swagger2markup/_latestVersion"] image:http://img.shields.io/badge/license-ASF2-blue.svg["Apache License 2", link="http://www.apache.org/licenses/LICENSE-2.0.txt"] image:https://img.shields.io/badge/Twitter-rbrtwnklr-blue.svg["Twitter", link="https://twitter.com/rbrtwnklr"] image:https://badges.gitter.im/Join%20Chat.svg[link="https://gitter.im/RobWin/swagger2markup?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge"]
== Overview
The primary goal of this project is to *simplify the generation of an up-to-date RESTful API documentation by combining documentation that's been hand-written with auto-generated API documentation* produced by https://github.com/swagger-api[Swagger]. The result is intended to be an *up-to-date, easy-to-read, on- and offline user guide*, comparable to https://developer.github.com/v3/[GitHub's API documentation]. The output of Swagger2Markup can be used as an alternative to https://github.com/swagger-api/swagger-ui[swagger-ui] and can be served as static content.
NOTE: The Swagger Specification has been donated to to the https://openapis.org/[Open API Initiative (OAI)] and has been renamed to the https://github.com/OAI/OpenAPI-Specification[OpenAPI Specification].
Swagger2Markup converts a Swagger JSON or YAML file into several *AsciiDoc* or *GitHub Flavored Markdown* documents which can be combined with hand-written documentation. The Swagger source file can be located locally or remotely via HTTP. Swagger2Markup supports the Swagger 1.2 and 2.0 specification. Internally it uses the _official_ https://github.com/swagger-api/swagger-parser[swagger-parser] and my https://github.com/RobWin/markup-document-builder[markup-document-builder].
You can use Swagger2Markup to convert your contract-first Swagger YAML file into a human-readable format and combine it with hand-written documentation. As an alternative, you can choose the code-first approach and use Swagger2Markup together with https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-JAX-RS-Project-Setup-1.5.X[Swagger JAX-RS], https://github.com/springfox/springfox[springfox] or https://github.com/spring-projects/spring-restdocs[spring-restdocs]. If you are Gradle or Maven user, you can also use the https://github.com/RobWin/swagger2markup-gradle-plugin[Swagger2Markup Gradle Plugin] or https://github.com/redowl/swagger2markup-maven-plugin[Swagger2markup Maven Plugin].
http://asciidoctor.org/docs/asciidoc-writers-guide/[AsciiDoc] is preferable to Markdown as it has more features. AsciiDoc is a text document format for writing documentation, articles, books, ebooks, slideshows, web pages and blogs. AsciiDoc files can be converted to *HTML*, *PDF* and *EPUB*. AsciiDoc is much better suited for describing public APIs than *JavaDoc* or *Annotations*.
You can generate your HTML5, PDF and EPUB documentation via https://github.com/asciidoctor/asciidoctorj[asciidoctorj] or even better via the https://github.com/asciidoctor/asciidoctor-gradle-plugin[asciidoctor-gradle-plugin] or https://github.com/asciidoctor/asciidoctor-maven-plugin[asciidoctor-maven-plugin].
The project requires at least JDK 8.
== Example
image::src/docs/asciidoc/images/Swagger2Markup.PNG[]
image::src/docs/asciidoc/images/Swagger2Markup_definitions.PNG[]
== Reference documentation
- http://swagger2markup.github.io/swagger2markup/1.0.0/[Reference Documentation]
- https://github.com/Swagger2Markup/swagger2markup/blob/master/RELEASENOTES.adoc[Release notes]
- https://github.com/Swagger2Markup/spring-swagger2markup-demo[Demo using Swagger2Markup, Spring Boot, Springfox and spring-restdocs]
== Contributing
=== Community contributions
Pull requests are welcome.
=== Questions
You can ask questions about Swagger2Markup in https://gitter.im/Swagger2Markup/swagger2markup[Gitter].
=== Bugs
If you believe you have found a bug, please take a moment to search the existing issues. If no one else has reported the problem, please open a new issue that describes the problem in detail and, ideally, includes a test that reproduces it.
=== Enhancements
If youd like an enhancement to be made to Swagger2Markup, pull requests are most welcome. The source code is on GitHub. You may want to search the existing issues and pull requests to see if the enhancement is already being worked on. You may also want to open a new issue to discuss a possible enhancement before work on it begins.
== Companies who use Swagger2Markup
* Deutsche Telekom AG
* https://restlet.com/[Restlet] -- Restlet offers an API platform, covering the https://restlet.com/products/restlet-studio/[design], https://restlet.com/products/dhc/[test] and https://restlet.com/products/apispark/[operation] of Web APIs, and uses Swagger2Markup to generate appealing HTML documentation from API definitions.
* http://www.qaware.de/[QAware GmbH]
* http://www.appdirect.com/[AppDirect] -- The leading commerce platform for selling cloud services.
* http://www.wescale.com[wescale]
* http://taskassure.com[TaskAssure]
== License
Copyright 2015 Robert Winkler
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

View File

@@ -1,93 +0,0 @@
= Release Notes
== Version 0.1.0
* Initial version with support for AsciiDoc and Markdown
== Version 0.2.0
* This version is not downward compatible. This version supports includes of example files and JSON/XML Schema files. See documentation.
=== Version 0.2.1
* Signed jar files and published in Maven Central
=== Version 0.2.2
* Fixed wrong dependency version to io.github.robwin:markup-document-builder
=== Version 0.2.3
* Fixed issue #7: @ApiModelProperty metadata are ignored for definitions file
=== Version 0.2.4
* Fixed issue #8: logback.xml on the classpath
* Fixed issue #13: unknown format not supported for properties
== Version 0.3.0
* Support of YAML or JSON String as input.
== Version 0.4.0
* Updated Swagger-Parser from 1.0.0 to 1.0.5
* Updated commons-lang to commons-lang3
* Swagger2MarkupConverter generates three documents now: overview, paths and definitions
* Support for enums in HeaderParameter, QueryParameter, FormParameter and QueryParameter
* Support for global consumes, produces and tags
== Version 0.5.0
* Support for including hand-written descriptions instead of using Swagger Annotations for descriptions
=== Version 0.5.1
* Bugfix: Definition name must be lowercase so that descriptions file can be found
=== Version 0.5.2
* Swagger License is not mandatory anymore
* Updated markup-document-builder from v0.1.3 to v0.1.4
=== Version 0.5.3
* Fixed compiler warning: [options] bootstrap class path not set in conjunction with -source 1.7
== Version 0.6.0
* Updated swagger-parser from v1.0.5 to v1.0.6
* Support for default values in Parameters and Model properties
=== Version 0.6.1
* Updated swagger-parser from v1.0.6 to v1.0.8
=== Version 0.6.2
* curl-request.adoc from spring-restdocs is also added to the example chapters
=== Version 0.6.3
* Added possibility to write object definitions to separate files. Issue #19
== Version 0.7.0
* Added support for both reference models and composed models
=== Version 0.7.1
* Workaround: If the type of a BodyParameter is String and not a Model, the schema is null and lost. Therefore the fallback type of a BodyParameter is String now.
== Version 0.8.0
* Enhancement #26 and #27: Added a pre-process hook to modify a Swagger Model before it is converted.
* Bugfix #29: Tags are rendered twice
== Version 0.9.0
* Updated swagger-parser from v1.0.8 to v1.0.13
* Support for global responses and parameters
=== Version 0.9.1
* Added support to group the paths by tags or as-is
* Added support to order the definitions by natural ordering or as-is
=== Version 0.9.2
* Multi language support. Added russian.
=== Version 0.9.3
* Updated swagger-parser from v1.0.13 to v1.0.16
* Enhancement #61 Refactor separated documents logic to support inter-document cross-references
* Enhancement #53 : support for tags, paths and methods ordering
* Enhancement #51 : Support for separated operations files
* Enhancement #52: Markdown generation for inline schemas
== Version 1.0.0
* New configuration API
* New extension SPI
* Added new languages: turkish, german, france
* New security document
* Inline schema support
* New configuration options
* Support of deprecated path operations

View File

@@ -1,67 +0,0 @@
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.3'
classpath 'org.asciidoctor:asciidoctorj-pdf:1.5.0-alpha.10.1'
classpath 'org.kt3k.gradle.plugin:coveralls-gradle-plugin:2.0.1'
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.6'
classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4.0.0"
classpath "org.ajoberstar:gradle-git:1.3.2"
}
}
description = 'swagger2markup Build'
version = '1.0.1-SNAPSHOT'
group = 'io.github.swagger2markup'
apply plugin: 'java'
apply from: 'gradle/publishing.gradle'
apply from: 'gradle/coverage.gradle'
apply from: 'gradle/documentation.gradle'
tasks.withType(JavaCompile) {
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
options.deprecation = true
options.encoding = 'UTF-8'
options.compilerArgs << "-Xlint:unchecked"
}
repositories {
maven {
url "https://oss.jfrog.org/artifactory/oss-snapshot-local"
}
jcenter()
mavenCentral()
mavenLocal()
}
dependencies {
compile 'io.github.swagger2markup:markup-document-builder:1.0.0'
compile 'io.swagger:swagger-compat-spec-parser:1.0.21-SNAPSHOT'
compile 'org.apache.commons:commons-configuration2:2.0'
compile 'commons-beanutils:commons-beanutils:1.9.2'
compile 'org.apache.commons:commons-collections4:4.1'
testCompile 'junit:junit:4.11'
testCompile 'org.asciidoctor:asciidoctorj:1.5.4'
testCompile 'ch.qos.logback:logback-classic:1.1.2'
testCompile 'org.assertj:assertj-core:3.4.0'
testCompile 'io.github.robwin:assertj-diff:0.1.1'
}
test {
if (System.properties['http.proxyHost']) {
systemProperty 'http.proxyHost', System.properties['http.proxyHost']
systemProperty 'http.proxyPort', System.properties['http.proxyPort']
systemProperty 'http.nonProxyHosts', System.properties['http.nonProxyHosts']
}
systemProperty 'file.encoding', 'UTF-8'
ignoreFailures = true
}
task wrapper(type: Wrapper) {
gradleVersion = '2.12'
}

View File

@@ -1,13 +0,0 @@
apply plugin: 'jacoco'
apply plugin: 'com.github.kt3k.coveralls'
jacocoTestReport {
reports {
xml.enabled = true // coveralls plugin depends on xml format report
html.enabled = true
}
}
tasks.coveralls {
dependsOn 'check'
}

View File

@@ -1,34 +0,0 @@
apply plugin: 'org.asciidoctor.convert'
apply plugin: 'org.ajoberstar.github-pages'
asciidoctor {
sources {
include 'index.adoc'
}
backends = ['html5', 'pdf']
attributes = [
doctype: 'book',
toc: 'left',
toclevels: '3',
numbered: '',
sectlinks: '',
sectanchors: '',
hardbreaks: '',
]
}
publishGhPages.dependsOn asciidoctor
githubPages {
repoUri = 'https://github.com/Swagger2Markup/swagger2markup.git'
credentials {
username = project.hasProperty('githubUser') ? project.githubUser : System.getenv('GITHUB_USER')
password = project.hasProperty('githubPassword') ? project.githubPassword : System.getenv('GITHUB_PASSWORD')
}
pages {
from file(asciidoctor.outputDir.path + '/html5')
into project.version
}
}

View File

@@ -1,151 +0,0 @@
import java.text.SimpleDateFormat
apply plugin: 'maven-publish'
apply plugin: 'com.jfrog.bintray'
apply plugin: "com.jfrog.artifactory"
Date buildTimeAndDate = new Date()
ext {
buildDate = new SimpleDateFormat('yyyy-MM-dd').format(buildTimeAndDate)
buildTime = new SimpleDateFormat('HH:mm:ss.SSSZ').format(buildTimeAndDate)
projectUrl = 'https://github.com/Swagger2Markup/swagger2markup'
licenseUrl = 'https://github.com/Swagger2Markup/swagger2markup/blob/master/LICENSE.txt'
scmUrl = 'https://github.com/Swagger2Markup/swagger2markup.git'
issuesUrl = 'https://github.com/Swagger2Markup/swagger2markup/issues'
}
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
archives sourcesJar
archives javadocJar
}
jar {
manifest {
attributes(
'Created-By': System.properties['java.version'] + " (" + System.properties['java.vendor'] + " " + System.properties['java.vm.version'] + ")",
'Built-With': "gradle-${project.getGradle().getGradleVersion()}, groovy-${GroovySystem.getVersion()}",
'Build-Time': "${new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")}",
'Specification-Title': "${project.name}",
'Specification-Version': project.version.toString(),
'Implementation-Title': "${project.name}",
'Implementation-Version': project.version.toString()
)
}
}
if (!project.hasProperty('bintrayUsername')) ext.bintrayUsername = ''
if (!project.hasProperty('bintrayApiKey')) ext.bintrayApiKey = ''
if (!project.hasProperty('gpgPassphrase')) ext.gpgPassphrase = ''
if (!project.hasProperty('ossUser')) ext.ossUser = ''
if (!project.hasProperty('ossPassword')) ext.ossPassword = ''
publishing {
publications {
mavenJava(MavenPublication) {
from components.java
pom.withXml {
def devs = ['RobWin': 'Robert Winkler']
def root = asNode()
root.dependencies.'*'.findAll() {
it.scope.text() == 'runtime' && project.configurations.compile.allDependencies.find { dep ->
dep.name == it.artifactId.text()
}
}.each() {
it.scope*.value = 'compile'
}
root.appendNode('name', project.name)
root.appendNode('packaging', 'jar')
root.appendNode('url', projectUrl)
root.appendNode('description', project.description)
def license = root.appendNode('licenses').appendNode('license')
license.appendNode('name', 'Apache-2.0')
license.appendNode('url', licenseUrl)
license.appendNode('distribution', 'repo')
root.appendNode('scm').appendNode('url', scmUrl)
def developers = root.appendNode('developers')
devs.each {
def d = developers.appendNode('developer')
d.appendNode('id', it.key)
d.appendNode('name', it.value)
}
}
artifact sourcesJar
artifact javadocJar
}
}
}
bintray {
user = project.bintrayUsername
key = project.bintrayApiKey
dryRun = false //Whether to run this as dry-run, without deploying
publish = true //If version should be auto published after an upload
publications = ['mavenJava']
pkg {
repo = 'Maven'
name = 'swagger2markup'
userOrg = 'swagger2markup'
websiteUrl = projectUrl
issueTrackerUrl = issuesUrl
vcsUrl = scmUrl
desc = rootProject.description
licenses = ['Apache-2.0']
version {
vcsTag = rootProject.version
gpg {
sign = true //Determines whether to GPG sign the files. The default is false
passphrase = project.gpgPassphrase //Optional. The passphrase for GPG signing'
}
mavenCentralSync {
sync = true //Optional (true by default). Determines whether to sync the version to Maven Central.
user = ossUser //OSS user token
password = ossPassword //OSS user password
}
}
}
}
artifactory {
contextUrl = 'https://oss.jfrog.org'
resolve {
repository {
repoKey = 'libs-release'
}
}
publish {
repository {
repoKey = 'oss-snapshot-local' //The Artifactory repository key to publish to
//when using oss.jfrog.org the credentials are from Bintray. For local build we expect them to be found in
//~/.gradle/gradle.properties, otherwise to be set in the build server
username = project.hasProperty('bintrayUsername') ? project.bintrayUsername : System.getenv('BINTRAY_USER')
password = project.hasProperty('bintrayApiKey') ? project.bintrayApiKey : System.getenv('BINTRAY_KEY')
}
defaults {
publications('mavenJava')
}
}
if (System.properties['https.proxyHost']) {
clientConfig.proxy.host = System.properties['https.proxyHost']
clientConfig.proxy.port = System.properties['https.proxyPort'].toInteger()
}
}
tasks.artifactoryPublish {
dependsOn 'check'
}

Binary file not shown.

View File

@@ -1,6 +0,0 @@
#Thu Mar 31 16:29:35 CEST 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.12-all.zip

160
gradlew vendored
View File

@@ -1,160 +0,0 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

90
gradlew.bat vendored
View File

@@ -1,90 +0,0 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -1 +0,0 @@
rootProject.name = 'swagger2markup'

View File

@@ -1,94 +0,0 @@
== Advanced usage
[[swagger_operationId]]
=== Swagger operationId
Swagger2Markup uniquely identify each operations for multiple purposes :
* generating separated operation files : file name
* generating unique Markup anchors for operations and all sub-items.
* searching for extra content for operations : operation folder name for content plugins (Hand-written descriptions, Dynamic content, etc...)
* ...
Swagger specification supports the `operationId` field which create an unique name for each operation.
When provided, this `operationId` value will be used primarily. Otherwise Swagger2Markup generates an id using `normalize(operation.summary + " " + lowerCase(operation.HTTPmethod))`.
IMPORTANT: It is highly recommended to set an operationId for each operation, so that a lot of actions does not depend on operation `summary` which *can change at anytime*.
=== Swagger schema title
Swagger2Markup displays inline schemas by decomposing them (when schema is complex). In this process, some intermediate references are generated using field names which is not always the best choice.
The Swagger document supports JSON Schema `title` items in inline schemas.
It's recommended to use them in inline schemas so that they'll be used primarily to field names and this will lead to a better naming.
.Inline schema without title items
====
[source,yaml,subs="quotes"]
----
InlinePet:
type: object
required:
- id
properties:
id:
type: integer
format: int64
category:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
tags:
type: array
items:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
----
image::images/untitledSwagger.png[]
====
.Inline schema with title items
====
[source,yaml,subs="quotes"]
----
InlineTitlePet:
type: object
required:
- id
properties:
id:
type: integer
format: int64
category:
type: object
*title: CategoryModel*
properties:
id:
type: integer
format: int64
name:
type: string
tags:
type: array
items:
type: object
*title: TagModel*
properties:
id:
type: integer
format: int64
name:
type: string
----
image::images/titledSwagger.png[]
====

View File

@@ -1,103 +0,0 @@
== Command Line Interface
Swagger2Markup provides a Command line interface (CLI). The CLI is published in JCenter and Maven Central. The artifacts can be viewed at the following locations:
* Releases: https://jcenter.bintray.com/io/github/swagger2markup/swagger2markup-cli/
* Snapshots: https://oss.jfrog.org/artifactory/oss-snapshot-local/io/github/swagger2markup/swagger2markup-cli/
NOTE: The CLI requires at least JDK 8.
=== Usage guide
==== Show help
You can show the help:
[source, subs="attributes"]
----
java -jar swagger2markup-cli-{project-version}.jar help convert
----
Output:
----
NAME
swagger2markup convert - Converts a Swagger JSON or YAML file into
Markup documents.
SYNOPSIS
swagger2markup convert [(-c <configFile> | --config <configFile>)]
[(-d <outputDir> | --outputDir <outputDir>)]
[(-f <outputFile> | --outputFile <outputFile>)]
(-i <swaggerInput> | --swaggerInput <swaggerInput>)
OPTIONS
-c <configFile>, --config <configFile>
Config file.
-d <outputDir>, --outputDir <outputDir>
Output directory. Converts the Swagger specification into multiple
files.
-f <outputFile>, --outputFile <outputFile>
Output file. Converts the Swagger specification into one file.
-h, --help
Display help information
-i <swaggerInput>, --swaggerInput <swaggerInput>
Swagger input. Can either be a URL or a file path.
----
==== Conversion into a folder
You can convert a Swagger file into a folder as follows:
[source, subs="attributes"]
----
java -jar swagger2markup-cli-1.0.0-SNAPSHOT.jar convert -i /path/to/swagger_petstore.yaml -d /tmp/asiidoc
----
It generates the Markup documents into the `/tmp/asiidoc` folder.
==== Conversion into a file
You can convert a local Swagger file into a file as follows:
[source, subs="attributes"]
----
java -jar swagger2markup-cli-1.0.0-SNAPSHOT.jar convert -i /path/to/swagger_petstore.yaml -f /tmp/asiidoc/swagger
----
NOTE: The input file must not have a file extension
It generates the Markup documents into the file `/tmp/asiidoc/swagger.adoc`.
==== Conversion of a remote Swagger file
You can convert a remote Swagger specification which must be accessible via HTTP.
[source, subs="attributes"]
----
java -jar swagger2markup-cli-1.0.0-SNAPSHOT.jar convert -i "http://petstore.swagger.io/v2/swagger.json" -d /tmp
----
=== Configuration
Create a `config.properties` file to customize the <<Swagger2Markup properties>>. For Example:
.config.properties
----
swagger2markup.markupLanguage=MARKDOWN
swagger2markup.outputLanguage=DE
----
Invoke the CLI as follows:
[source, subs="attributes"]
----
java -jar swagger2markup-cli-1.0.0-SNAPSHOT.jar convert -i /path/to/swagger_petstore.yaml -o /tmp -c /path/to/config.properties
----

View File

@@ -1,10 +0,0 @@
== Contributing
=== Questions
You can ask questions about Swagger2Markup in https://gitter.im/Swagger2Markup/swagger2markup[Gitter].
=== Bugs
If you believe you have found a bug, please take a moment to search the existing issues. If no one else has reported the problem, please open a new issue that describes the problem in detail and, ideally, includes a test that reproduces it.
=== Enhancements
If youd like an enhancement to be made to Swagger2Markup, pull requests are most welcome. The source code is on GitHub. You may want to search the existing issues and pull requests to see if the enhancement is already being worked on. You may also want to open a new issue to discuss a possible enhancement before work on it begins.

View File

@@ -1,82 +0,0 @@
== Spring Boot and Springfox
If you use Spring Boot and Springfox or Swagger JAX-RS, you can do the following:
* generate an up-to-date Swagger JSON file during an unit or integration test
* convert the Swagger JSON file into AsciiDoc
* add hand-written AsciiDoc documentation
* convert AsciiDoc into HTML and PDF
* copy the HTML and PDF artifacts into an executable Spring Boot Jar file and serve it as static content
This transformation pipeline can be done with Gradle or Maven in the build phase. That way there is no runtime overhead and there are no additional runtime libraries required.
The Swagger2MarkupConverter can be used to make a request to a remote Swagger endpoint during an integration test. The Swagger2MarkupConverter allows to write the generated documents into any folder. In this this example it is ``src/docs/asciidoc/generated``.
[source,java]
----
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class, SwaggerConfig.class})
@WebIntegrationTest
public class Swagger2MarkupTest {
@Test
public void convertRemoteSwaggerToAsciiDoc() {
// Remote Swagger source
Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs")).build()
.toFolder(Paths.get("src/docs/asciidoc/generated"));
}
}
----
Spring's MVC Test framework can also be used to make a request to a Springfox Swagger endpoint during an unit test. A custom ResultHandler ``Swagger2MarkupResultHandler`` can be used to write the Swagger JSON response into a directory. The custom ResultHandler is part of ``springfox-staticdocs``. That way you also verify that your Swagger endpoint is working.
The Swagger JSON response can be converted using the <<Gradle Plugin>> or <<Maven Plugin>>.
[source,java]
----
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class, SwaggerConfig.class})
public class Swagger2MarkupTest {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
@Test
public void convertSwaggerToAsciiDoc() throws Exception {
this.mockMvc.perform(get("/v2/api-docs")
.accept(MediaType.APPLICATION_JSON))
.andDo(Swagger2MarkupResultHandler
.outputDirectory("src/docs/asciidoc/generated").build())
.andExpect(status().isOk());
}
}
----
=== Demo
The quickest way to get started is to look at the demo project https://github.com/Swagger2Markup/spring-swagger2markup-demo[spring-swagger2markup-demo]. The demo shows how to generate static docs (HTML5 and PDF) by using the Swagger2Markup Gradle Plugin and serve the generated documentation as static content in a Spring Boot App under http://localhost:9080/docs/index.html and http://localhost:9080/docs/index.pdf.
If you want to start the Spring Boot application, please run:
[source, java, subs="attributes"]
----
gradlew clean build
----
----
java -jar build/libs/spring-swagger2markup-demo-{project-version}.jar
----
If you only want to generate the HTML and PDF documentation, please run:
----
gradlew clean asciidoctor
----

View File

@@ -1,187 +0,0 @@
== Extension SPI
Swagger2Markup provides an Extension SPI to extend the functionality of Swagger2Markup. Five types of extension are available. An extension is an abstract class which must be implemented.
[options="header"]
.Swagger2Markup extensions
|====
| Name | Class | Description
| <<OverviewDocumentExtension>> | io.github.swagger2markup.spi.OverviewDocumentExtension | Can be used to extend the content of the Overview document
| <<PathsDocumentExtension>> | io.github.swagger2markup.spi.PathsDocumentExtension | Can be used to extend the content of the Paths document
| <<SecurityDocumentExtension>> | io.github.swagger2markup.spi.SecurityDocumentExtension | Can be used to extend the content of the Security document
| <<DefinitionsDocumentExtension>> | io.github.swagger2markup.spi.DefinitionsDocumentExtension | Can be used to extend the content of the Definitions document
| <<SwaggerModelExtension>> | io.github.swagger2markup.spi.SwaggerModelExtension | Can be used to modify the Swagger model before it is converted
|====
=== Creation of an extension
To create a custom extension, you have to create a class (e.g. `io.myname.MyExtension`) which extends an extension, e.g. `io.github.swagger2markup.spi.DefinitionsDocumentExtension`. Every extension point provides two methods which must be implemented:
* `init`: This method is invoked once and can be used to initialize the extension.
* `apply`: This method is invoked multiple times depending on the type of the extension. The `Position` can be retrieved from the `Context` and can be used to extend the document at specific extension points.
[source,java,indent=0]
----
include::../../test/java/io/github/swagger2markup/builder/MyExtension.java[tags=MyExtension]
----
1. You can retrieve extension properties from the config to configure the extension.
2. You can retrieve a `MarkupDocBuilder` from the `Context`.
3. You can retrieve the current `Position` from the Context.
4. You can use a `MarkupDocBuilder` to add Markup using a fluent API or import Markup from files.
=== Registration of an extension
Swagger2Markup extensions must be registered in the `Swagger2MarkupExtensionRegistry`. The default `Swagger2MarkupExtensionRegistry` of Swagger2Markup uses the `java.util.ServiceLoader` to load and register Swagger2Markup extensions automatically.
==== Automatic registration
To register your extension automatically, the following steps are required:
* Create a file called `META-INF/services/io.github.swagger2markup.spi.DefinitionsDocumentExtension` which contains your extensionss full qualified name, e.g. `io.myname.MyExtension`.
* When a `.jar` file containing your extension is added to the classpath of Swagger2Markup, the extensions will be automatically registered.
==== Manual registration
To register your extension manually, you have to use the `Swagger2MarkupExtensionRegistryBuilder`.
[source,java,indent=0]
----
include::../../test/java/io/github/swagger2markup/DocumentationTest.java[tags=swagger2MarkupExtensionRegistryBuilder]
----
1. Create a ``Swagger2MarkupExtensionRegistryBuilder`` using the default constructor
2. Register your custom extension
3. Build an instance of `Swagger2MarkupExtensionRegistry`
4. Use the custom Swagger2MarkupExtensionRegistry
=== Extensions points
==== OverviewDocumentExtension
The OverviewDocumentExtension allows to extend the overview document at positions :
* DOCUMENT_BEFORE: Before the document title (title level offset = 0)
* DOCUMENT_BEGIN: After the document title (title level offset = 1)
* DOCUMENT_END: At the end of the document (title level offset = 1)
* DOCUMENT_AFTER: At the very end of the document (title level offset = 0)
NOTE: Extension content titles must always start from level *1*. The title level will be adapted depending on position.
==== PathsDocumentExtension
The PathsDocumentExtension allows to extend the paths document at positions :
* DOCUMENT_BEFORE: Before the document title (title level offset = 0)
* DOCUMENT_BEGIN: After the document title (title level offset = 1)
* OPERATION_BEFORE: Before each operation title (title level offset = 1)
* OPERATION_BEGIN: After each operation title (title level offset = 2)
* OPERATION_END: At the end of each operation (title level offset = 2)
* OPERATION_AFTER: At the very end of each operation (title level offset = 1)
* DOCUMENT_END: At the end of the document (title level offset = 1)
* DOCUMENT_AFTER: At the very end of the document (title level offset = 0)
Moreover, the PathsDocumentExtension allows to extend operation sections at positions :
* OPERATION_DESCRIPTION_BEFORE: Before each description section title (title level offset = 2)
* OPERATION_DESCRIPTION_BEGIN: After each description section title (title level offset = 3)
* OPERATION_DESCRIPTION_END: At the end of each description section (title level offset = 3)
* OPERATION_DESCRIPTION_AFTER: At the very end of each description section (title level offset = 2)
* OPERATION_PARAMETERS_BEFORE: Before each parameters section title (title level offset = 2)
* OPERATION_PARAMETERS_BEGIN: After each parameters section title (title level offset = 3)
* OPERATION_PARAMETERS_END: At the end of each parameters section (title level offset = 3)
* OPERATION_PARAMETERS_AFTER: At the very end of each parameters section (title level offset = 2)
* OPERATION_RESPONSES_BEFORE: Before each responses section title (title level offset = 2)
* OPERATION_RESPONSES_BEGIN: After each responses section title (title level offset = 3)
* OPERATION_RESPONSES_END: At the end of each responses section (title level offset = 3)
* OPERATION_RESPONSES_AFTER: At the very end of each responses section (title level offset = 2)
* OPERATION_SECURITY_BEFORE: Before each security section title (title level offset = 2)
* OPERATION_SECURITY_BEGIN: After each security section title (title level offset = 3)
* OPERATION_SECURITY_END: At the end of each security section (title level offset = 3)
* OPERATION_SECURITY_AFTER: At the very end of each security section (title level offset = 2)
NOTE: Extension content titles must always start from level *1*. The title level will be adapted depending on position.
==== SecurityDocumentExtension
The SecurityDocumentExtension allows to extend the security document at positions :
* DOCUMENT_BEFORE: Before the document title (title level offset = 0)
* DOCUMENT_BEGIN: After the document title (title level offset = 1)
* SECURITY_SCHEME_BEFORE: Before each security scheme title (title level offset = 1)
* SECURITY_SCHEME_BEGIN: After each security scheme title (title level offset = 2)
* SECURITY_SCHEME_END: At the end of each security scheme (title level offset = 2)
* SECURITY_SCHEME_AFTER: At the very end of each security scheme (title level offset = 1)
* DOCUMENT_END: At the end of the document (title level offset = 1)
* DOCUMENT_AFTER: At the very end of the document (title level offset = 0)
NOTE: Extension content titles must always start from level *1*. The title level will be adapted depending on position.
==== DefinitionsDocumentExtension
The DefinitionsDocumentExtension allows to extend the definitions document at positions :
* DOCUMENT_BEFORE: Before the document title (title level offset = 0)
* DOCUMENT_BEGIN: After the document title (title level offset = 1)
* DEFINITION_BEFORE: Before each definition title (title level offset = 1)
* DEFINITION_BEGIN: After each definition title (title level offset = 2)
* DEFINITION_END: At the end of each definition (title level offset = 2)
* DEFINITION_AFTER: At the very end of each definition (title level offset = 1)
* DOCUMENT_END: At the end of the document (title level offset = 1)
* DOCUMENT_AFTER: At the very end of the document (title level offset = 0)
NOTE: Extension content titles must always start from level *1*. The title level will be adapted depending on position.
==== SwaggerModelExtension
The SwaggerModelExtension allows to modify the Swagger model before it is processed by Swagger2Markup. For example, you could use this extension to delete Paths from the Swagger model which should not be rendered.
Example:
[source,java,indent=0]
----
include::../../test/java/io/github/swagger2markup/builder/MySwaggerModelExtension.java[tags=MySwaggerModelExtension]
----
1. You can change any Swagger model property
2. You could even remove elements from the Swagger model
[[extension_commons_content_markup]]
=== Content markup language
Most content extensions supports to provide content in any markup language which will be *converted, if needed, to configured Swagger2Markup converter markup language* at import.
The content files markup language can be any https://github.com/Swagger2Markup/markup-document-builder[markup-document-builder] supported language :
* ASCIIDOC : AsciiDoc. Mandatory content file extension : `adoc`
* MARKDOWN : Github Flavored Markdown. Mandatory content file extension : `md`
* CONFLUENCE_MARKUP : Confluence Wiki markup. Mandatory content file extension : `txt`
[IMPORTANT]
====
Currently supported conversions are :
* Markdown -> AsciiDoc
====
=== Provided Extensions
Swagger2Markup provides some extensions which can be used out-of-the-box. You just have to add the extension to your classpath.
[options="header"]
.Swagger2Markup extensions
|====
| Name | Description
| <<extension_import_files,Dynamic file import extension>> | Allows to dynamically import Markup from files.
| <<extension_spring_restdocs,Spring RestDocs extension>> | Allows to import Curl, HTTP request and response snippets from https://github.com/spring-projects/spring-restdocs[Spring Rest Docs].
| <<extension_import_schemas,Schema file import extension>> | Allows to import JSON or XML Schema files.
|====
include::extensions/import_files.adoc[leveloffset=+2]
include::extensions/spring_restdocs.adoc[leveloffset=+2]
include::extensions/import_schemas.adoc[leveloffset=+2]

View File

@@ -1,117 +0,0 @@
[[extension_import_files]]
== Dynamic file import extension
=== Usage guide
[source,groovy, subs="attributes"]
----
repositories {
jCenter()
}
compile "io.github.swagger2markup:swagger2markup-import-files-ext:{project-version}"
----
The extension searches for markup files in configurable paths to append the markup to the documents at supported positions.
The markup files must conform to a naming convention to be found. The files must start with the position where the document should be extended and end with the markup file extension (e.g `adoc` or `md`).
See documentation of <<Extensions points>>.
Here the list of all document naming conventions for each position. You have to replace `*` with an arbitrary, meaningful, identifier.
NOTE: You can provide multiple contents for the same position, just specify different identifiers in place of `*` in the file name. The concurrent contents for a given position will all be added to the document in a determinist order, sorting content file by natural order.
All extensions, relatively to each extension contentPath :
* DOCUMENT_BEFORE : `document-before-*.<<extension_import_files_markup,<markup.ext> >>`
* DOCUMENT_BEGIN : `document-begin-*.<<extension_import_files_markup,<markup.ext> >>`
* DOCUMENT_END : `document-end-*.<<extension_import_files_markup,<markup.ext> >>`
* DOCUMENT_AFTER : `document-after-*.<<extension_import_files_markup,<markup.ext> >>`
Paths extensions, relatively to each extension contentPath :
* OPERATION_BEFORE : `<<swagger_operationId,<operationId> >>/operation-before-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_BEGIN : `<<swagger_operationId,<operationId> >>/operation-begin-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_END : `<<swagger_operationId,<operationId> >>/operation-end-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_AFTER : `<<swagger_operationId,<operationId> >>/operation-after-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_DESCRIPTION_BEFORE: `<<swagger_operationId,<operationId> >>/operation-description-before-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_DESCRIPTION_BEGIN: `<<swagger_operationId,<operationId> >>/operation-description-begin-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_DESCRIPTION_END: `<<swagger_operationId,<operationId> >>/operation-description-end-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_DESCRIPTION_AFTER: `<<swagger_operationId,<operationId> >>/operation-description-after-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_PARAMETERS_BEFORE: `<<swagger_operationId,<operationId> >>/operation-parameters-before-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_PARAMETERS_BEGIN: `<<swagger_operationId,<operationId> >>/operation-parameters-begin-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_PARAMETERS_END: `<<swagger_operationId,<operationId> >>/operation-parameters-end-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_PARAMETERS_AFTER: `<<swagger_operationId,<operationId> >>/operation-parameters-after-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_RESPONSES_BEFORE: `<<swagger_operationId,<operationId> >>/operation-responses-before-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_RESPONSES_BEGIN: `<<swagger_operationId,<operationId> >>/operation-responses-begin-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_RESPONSES_END: `<<swagger_operationId,<operationId> >>/operation-responses-end-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_RESPONSES_AFTER: `<<swagger_operationId,<operationId> >>/operation-responses-after-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_SECURITY_BEFORE: `<<swagger_operationId,<operationId> >>/operation-security-before-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_SECURITY_BEGIN: `<<swagger_operationId,<operationId> >>/operation-security-begin*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_SECURITY_END: `<<swagger_operationId,<operationId> >>/operation-security-end-*.<<extension_import_files_markup,<markup.ext> >>`
* OPERATION_SECURITY_AFTER: `<<swagger_operationId,<operationId> >>/operation-security-after-*.<<extension_import_files_markup,<markup.ext> >>`
Definitions extensions, relatively to each extension contentPath :
* DEFINITION_BEFORE : `<definitionName>/definition-before-*.<<extension_import_files_markup,<markup.ext> >>`
* DEFINITION_BEGIN : `<definitionName>/definition-begin-*.<<extension_import_files_markup,<markup.ext> >>`
* DEFINITION_END : `<definitionName>/definition-end-*.<<extension_import_files_markup,<markup.ext> >>`
* DEFINITION_AFTER : `<definitionName>/definition-after-*.<<extension_import_files_markup,<markup.ext> >>`
Security extensions, relatively to each extension contentPath :
* SECURITY_SCHEME_BEFORE : `<securitySchemeName>/security-scheme-before-*.<<extension_import_files_markup,<markup.ext> >>`
* SECURITY_SCHEME_BEGIN : `<securitySchemeName>/security-scheme-begin-*.<<extension_import_files_markup,<markup.ext> >>`
* SECURITY_SCHEME_END : `<securitySchemeName>/security-scheme-end-*.<<extension_import_files_markup,<markup.ext> >>`
* SECURITY_SCHEME_AFTER : `<securitySchemeName>/security-scheme-after-*.<<extension_import_files_markup,<markup.ext> >>`
IMPORTANT: `<operationId>` value depends on Swagger specification. If you provided an `operationId` for operations in the Swagger document, the value will be used primarily. *It is highly recommended to set operationId for operations* : see <<swagger_operationId,Swagger operationId>>. In all cases, all placeholder values are case-sensitive.
NOTE: It's *highly recommended* to configure a different contentPath for each extension (dynamicOverview, dynamicDefinitions, etc...) because content files for DOCUMENT_* positions have the same naming convention.
.Example of provided content files for petstore Swagger sample
====
....
overview/document-before-intro.adoc <1>
paths/document-before-intro.adoc <2>
paths/updatePet/operation-begin-description.adoc
paths/updatePet/operation-end-example1.adoc
paths/updatePet/operation-end-example2.adoc <3>
definitions/Pet/definition-begin-description.adoc
....
1. "overview", "paths" and "definitions" are different configured contentPath for different extensions.
2. the document name is the same but will be used only in Paths document because contentPath is different (cf 1.).
3. both example1 and example2 content files will be added to "updatePet" operation. They'll be applied consecutively, with their names sorted by natural order.
====
[[extension_import_files_markup]]
=== Content markup language
See <<extension_commons_content_markup,Extensions content markup language>>
By default, the markup language is set to *ASCIIDOC*. Set extension <<extension_import_files_configuration,Configuration>> to change content markup language.
[[extension_import_files_configuration]]
=== Configuration
The extension adds the following properties to Swagger2Markup which must be configured:
[options="header"]
.Extension properties
|====
| Name | Description | Default | Example
| `swagger2markup.extensions.dynamicOverview.contentPath` | The path to the files which should be imported | - | `src/test/resources/docs/asciidoc/overview`
| `swagger2markup.extensions.dynamicOverview.markupLanguage` | The markup language of the content files | `ASCIIDOC` | `MARKDOWN`
| `swagger2markup.extensions.dynamicDefinitions.contentPath` | The path to the files which should be imported | - | `src/test/resources/docs/asciidoc/definitions`
| `swagger2markup.extensions.dynamicDefinitions.markupLanguage` | The markup language of the content files | `ASCIIDOC` | `MARKDOWN`
| `swagger2markup.extensions.dynamicPaths.contentPath` | The path to the files which should be imported | - | `src/test/resources/docs/asciidoc/paths`
| `swagger2markup.extensions.dynamicPaths.markupLanguage` | The markup language of the content files | `ASCIIDOC` | `MARKDOWN`
| `swagger2markup.extensions.dynamicSecurity.contentPath` | TThe path to the files which should be imported | - | `src/test/resources/docs/asciidoc/security`
| `swagger2markup.extensions.dynamicSecurity.markupLanguage` | The markup language of the content files | `ASCIIDOC` | `MARKDOWN`
|====

View File

@@ -1,29 +0,0 @@
[[extension_import_schemas]]
== Schema file import extension
=== Usage guide
[source,groovy, subs="attributes"]
----
repositories {
jCenter()
}
compile "io.github.swagger2markup:swagger2markup-import-schemas-ext:{project-version}"
----
The extension searches for Schema files in a configurable path to append the Schema file content at the end of a definition section. The Schema files must conform to a naming convention to be found. The files must be called `schema.xsd` or `schema.json` and must be stored in a folder which matches the name of a definition.
Example: `/schemas/Pet/schema.json`.
=== Configuration
The extension adds the following properties to Swagger2Markup which must be configured:
[options="header"]
.Extension properties
|====
| Name | Description | Example
| `swagger2markup.extensions.schema.schemaBaseUri` | The path to the schema files | `src/test/resources/docs/asciidoc/schemas`
|====

View File

@@ -1,74 +0,0 @@
[[extension_spring_restdocs]]
== Spring RestDocs extension
Swagger2Markup can be used together with https://github.com/spring-projects/spring-restdocs[spring-restdocs]. Swagger2Markup can include the generated CURL request, HTTP request and HTTP response example snippets from spring-restdocs into the generated Markup documents. See spring-restdocs how to configure it.
=== Usage guide
[source,groovy,subs="attributes"]
----
repositories {
jCenter()
}
compile "io.github.swagger2markup:swagger2markup-spring-restdocs-ext:{project-version}"
----
The extension searches for https://github.com/spring-projects/spring-restdocs[Spring RestDocs] snippet files in a configurable path to append the snippets at the end of a path operation section. By default the following snippets are searched :
* `<<swagger_operationId,<operationId> >>/http-request.<<extension_spring_restdocs_markup,<markup.ext> >>`
* `<<swagger_operationId,<operationId> >>/http-response.<<extension_spring_restdocs_markup,<markup.ext> >>`
* `<<swagger_operationId,<operationId> >>/curl-request.<<extension_spring_restdocs_markup,<markup.ext> >>`
IMPORTANT: `<operationId>` value depends on Swagger specification. If you provided an `operationId` for operations in the Swagger document, the value will be used primarily. *It is highly recommended to set operationId for operations* : see <<swagger_operationId,Swagger operationId>>. In all cases, `<operationId>` is case-sensitive.
Swagger Example:
[source,yaml]
----
paths:
/pets:
post:
summary: Add a new pet to the store
operationId: addPet
...
----
The following Unit Test uses Spring RestDocs to tests the `/pets` endoint and writes the example files into the ``build/snippets`` folder. Have a look at the <<Spring Boot and Springfox>> chapter for a full example using https://github.com/spring-projects/spring-boot[Spring Boot], https://github.com/springfox/springfox[Springfox] and Spring RestDocs.
[source,java]
----
@Rule
public final RestDocumentation restDocumentation = new RestDocumentation("build/snippets");
@Test
public void addAPetToTheStore() throws Exception {
this.mockMvc.perform(post("/pets/").content(createPet())
.contentType(MediaType.APPLICATION_JSON))
.andDo(document("addPet", preprocessResponse(prettyPrint())))
.andExpect(status().isOk());
}
----
Example: `build/snippets/addPet/http-request.adoc`.
[[extension_spring_restdocs_markup]]
=== Content markup language
See <<extension_commons_content_markup,Extensions content markup language>>
By default, the markup language is set to *ASCIIDOC*. Set extension <<extension_spring_restdocs_configuration,Configuration>> to change content markup language.
[[extension_spring_restdocs_configuration]]
=== Configuration
The extension adds the following properties to Swagger2Markup which must be configured:
[options="header"]
.Extension properties
|====
| Name | Description | Default | Example
| `swagger2markup.extensions.springRestDocs.snippetBaseUri` | The path to the Spring RestDocs snippets | - | `src/test/resources/docs/asciidoc/paths`
| `swagger2markup.extensions.springRestDocs.markupLanguage` | The markup language of the content files | `ASCIIDOC` | `MARKDOWN`
| `swagger2markup.extensions.springRestDocs.defaultSnippets` | Boolean value. Set to false to disable default snippet files | `true` | `false`
|====

View File

@@ -1,71 +0,0 @@
== Getting started
Swagger2Markup is a standard .jar file. To start using it, you need to add the library to your projects classpath. Swagger2Markup is published in JCenter and Maven Central. The artifacts can be viewed at the following locations:
* Releases: https://jcenter.bintray.com/io/github/swagger2markup/swagger2markup/
* Snapshots: https://oss.jfrog.org/simple/oss-snapshot-local/io/github/swagger2markup/swagger2markup/
If you use Gradle or Maven, you can include Swagger2Markup as follows.
WARNING: The *groupId* has been changed from *io.github.robwin* to *io.github.swagger2markup*
=== Gradle
==== Release
[source,groovy, subs="attributes"]
----
repositories {
jCenter()
}
compile "io.github.swagger2markup:swagger2markup:{project-version}"
----
==== Snapshot
[source,groovy]
----
repositories {
maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
}
----
=== Maven
==== Release
[source,xml, subs="specialcharacters,attributes"]
----
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>jcenter-releases</id>
<name>jcenter</name>
<url>http://jcenter.bintray.com</url>
</repository>
</repositories>
<dependency>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup</artifactId>
<version>{project-version}</version>
</dependency>
----
==== Snapshot
[source,java]
----
<repositories>
<repository>
<id>jcenter-snapshots</id>
<name>jcenter</name>
<url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url>
</repository>
</repositories>
----

View File

@@ -1,62 +0,0 @@
== Gradle Plugin
Swagger2Markup provides a Gradle plugin. The Gradle plugin is published in JCenter and Maven Central.
NOTE: The Gradle Plugin requires at least JDK 8.
=== Usage guide
Add the following snippet to your Gradle build file:
[source,java]
[source,groovy, subs="attributes"]
----
buildscript {
repositories {
jcenter()
maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
}
dependencies {
classpath 'io.github.swagger2markup:swagger2markup-gradle-plugin:{project-version}'
}
}
apply plugin: 'io.github.swagger2markup'
----
The plugin adds a new task named ``convertSwagger2markup``. You can run the task as follows:
`gradlew convertSwagger2markup`
=== Configuration
You can customize the task by configuring a Map of <<Swagger2Markup properties>>.
[source,groovy]
----
convertSwagger2markup {
swaggerInput file("src/docs/swagger/swagger_petstore.yaml").getAbsolutePath()
outputDir file("${buildDir}/asciidoc")
config = ['swagger2markup.markupLanguage' : 'ASCIIDOC',
'swagger2markup.pathsGroupedBy' : 'TAGS']
}
----
[options="header"]
.Gradle Plugin properties
|====
| Name | Description | Type | Example
| swaggerInput | The URL or file path to the Swagger specification | String | `file("src/docs/swagger/swagger_petstore.yaml").getAbsolutePath()` or `http://petstore.swagger.io/v2/swagger.json`
| outputDir | The directory where the output should be stored. | File | `file("${buildDir}/asciidoc")`
| outputFile | The file path (without extension) where the output should be stored. | File | `file("${buildDir}/asciidoc/swagger")`
| config | The Swagger2Markup properties to configure the converter | Map | |
|====
=== Example
You can copy the template project from GitHub to get started.
https://github.com/Swagger2Markup/swagger2markup-gradle-project-template

View File

@@ -1,34 +0,0 @@
= Swagger2Markup Documentation
Robert Winkler
:toc: left
:toclevels: 3
:source-highlighter: coderay
:numbered:
:hardbreaks:
:revnumber: {project-version}
:revdate: {localdate}
:icons: font
:pagenums:
include::introduction.adoc[]
include::getting_started.adoc[]
include::usage_guide.adoc[]
include::advanced_usage.adoc[]
include::extension_spi.adoc[]
include::gradle_plugin.adoc[]
include::maven_plugin.adoc[]
include::command_line_interface.adoc[]
include::demo.adoc[]
include::contributing.adoc[]
include::license.adoc[]

View File

@@ -1,23 +0,0 @@
== Introduction
The primary goal of this project is to **simplify the generation of an up-to-date RESTful API documentation by combining documentation that's been hand-written with auto-generated API documentation** produced by https://github.com/swagger-api[Swagger]. The result is intended to be an **up-to-date, easy-to-read, on- and offline user guide**. The output of Swagger2Markup can be used as an alternative to https://github.com/swagger-api/swagger-ui[swagger-ui] and can be served as static content.
NOTE: The Swagger Specification has been donated to to the https://openapis.org/[Open API Initiative (OAI)] and has been renamed to https://github.com/OAI/OpenAPI-Specification[OpenAPI Specification].
Swagger2Markup converts a Swagger JSON or YAML specification into either **AsciiDoc**, **GitHub Flavored Markdown** or *Atlassian Confluence Wiki* documents which can be combined with hand-written Markup documentation. The Swagger source file can be located locally or remotely via HTTP. Internally Swagger2Markup uses the __official__ https://github.com/swagger-api/swagger-parser[swagger-parser] and https://github.com/Swagger2Markup/markup-document-builder[markup-document-builder].
You can use Swagger2Markup to convert your contract-first Swagger YAML file into Markup. As an alternative, you can choose the code-first approach and use Swagger2Markup together with https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-JAX-RS-Project-Setup-1.5.X[Swagger JAX-RS], https://github.com/springfox/springfox[Springfox] or https://github.com/spring-projects/spring-restdocs[spring-restdocs]. If you are are Gradle or Maven user, you can also use the https://github.com/Swagger2Markup/swagger2markup-gradle-plugin[Swagger2Markup Gradle Plugin] or https://github.com/redowl/swagger2markup-maven-plugin[Swagger2markup Maven Plugin].
NOTE: The project requires at least JDK 8.
=== AsciiDoc
http://asciidoctor.org/docs/asciidoc-writers-guide/[AsciiDoc] is preferable to Markdown as it has more features. AsciiDoc is a text document format for writing documentation, articles, books, ebooks, slideshows, web pages and blogs. AsciiDoc files can be converted to **HTML**, **PDF** and **EPUB**. AsciiDoc is much better suited for describing public APIs than **JavaDoc** or **Annotations**.
You can generate your HTML5, PDF and EPUB documentation via https://github.com/asciidoctor/asciidoctorj[asciidoctorj] or even better via the https://github.com/asciidoctor/asciidoctor-gradle-plugin[asciidoctor-gradle-plugin] or https://github.com/asciidoctor/asciidoctor-maven-plugin[asciidoctor-maven-plugin].
.HTML example using AsciiDoctor - path section
image::images/Swagger2Markup.PNG[]
.HTML example using AsciiDoctor - definition section
image::images/Swagger2Markup_definitions.PNG[]

View File

@@ -1,9 +0,0 @@
== License
Copyright 2016 Robert Winkler
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

View File

@@ -1,86 +0,0 @@
== Maven Plugin
Swagger2Markup provides a Maven plugin. The Maven plugin is published in JCenter and Maven Central.
NOTE: The Maven Plugin requires at least JDK 8.
=== Usage guide
Add the following snippet to your Maven POM file:
[source,xml, subs="specialcharacters,attributes"]
----
<pluginRepositories>
<pluginRepository>
<id>jcenter-snapshots</id>
<name>jcenter</name>
<url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url>
</pluginRepository>
<pluginRepository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>jcenter-releases</id>
<name>jcenter</name>
<url>http://jcenter.bintray.com</url>
</pluginRepository>
</pluginRepositories>
<build>
<plugins>
<plugin>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup-maven-plugin</artifactId>
<version>{project-version}</version>
</plugin>
</plugins>
</build>
----
The plugin adds a new task goal `swagger2markup:convertSwagger2markup`. You can run the goal as follows:
`mvn swagger2markup:convertSwagger2markup`
=== Configuration
You can customize the task by configuring a Map of <<Swagger2Markup properties>>.
[source,xml]
----
<build>
<plugins>
<plugin>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup-maven-plugin</artifactId>
<version>{project-version}</version>
<configuration>
<swaggerInput>${project.basedir}/src/docs/swagger/swagger_petstore.yaml</swaggerInput>
<outputDir>${project.build.directory}/asciidoc</outputDir>
<config>
<swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage>
</config>
</configuration>
</plugin>
</plugins>
</build>
----
[options="header"]
.Maven Plugin properties
|====
| Name | Description | Type | Example
| swaggerInput | The URL or file path to the Swagger specification | String | `${project.basedir}/src/docs/swagger/swagger_petstore.yaml` or `http://petstore.swagger.io/v2/swagger.json`
| outputDir | The directory where the output should be stored. | File | `${project.build.directory}/asciidoc`
| outputFile | The file path (without extension) where the output should be stored. | File | `${project.build.directory}/asciidoc/swagger`
| config | The Swagger2Markup properties to configure the converter | Map | |
|====
=== Example
You can copy the template project from GitHub to get started.
https://github.com/Swagger2Markup/swagger2markup-maven-project-template

View File

@@ -1,196 +0,0 @@
== Swagger2Markup API
=== Usage guide
Swagger2Markup converts a Swagger JSON or YAML specification into either **AsciiDoc**, **GitHub Flavored Markdown** or **Atlassian Confluence Wiki** documents. By default the Swagger2Markup converts a Swagger specification into four AsciiDoc files: __overview.adoc__, __paths.adoc__ , __security.adoc__ and __definitions.adoc__. But you can also convert a Swagger specification into only one file or a String.
==== Conversion of a local Swagger file
The entry point of the Swagger2Markup API is the ``Swagger2MarkupConverter`` class. This class provides static factory methods to create a `Swagger2MarkupConverter.Builder`.
[source,java,indent=0]
----
include::../../test/java/io/github/swagger2markup/DocumentationTest.java[tags=localSwaggerSpec]
----
1. Create a ``Swagger2MarkupConverter.Builder`` by specifying the Path to the local file
2. Build an instance of the ``Swagger2MarkupConverter``
3. Invoke ``toFolder`` by specifying the output directory
==== Conversion of a remote Swagger file
You can convert a remote Swagger specification which must be accessible via HTTP.
[source,java,indent=0]
----
include::../../test/java/io/github/swagger2markup/DocumentationTest.java[tags=remoteSwaggerSpec]
----
1. Create a ``Swagger2MarkupConverter.Builder`` by specifying the URL to the remote file
2. Build an instance of the ``Swagger2MarkupConverter``
3. Invoke ``toFolder`` by specifying the output directory
==== Conversion into a file
You can convert the Swagger specification into a file.
[source,java,indent=0]
----
include::../../test/java/io/github/swagger2markup/DocumentationTest.java[tags=convertIntoOneFile]
----
==== Conversion to a String
You can convert the Swagger specification to a String.
[source,java,indent=0]
----
include::../../test/java/io/github/swagger2markup/DocumentationTest.java[tags=convertIntoString]
----
=== Configuration
Swagger2Markup provides several options to configure the Swagger2MarkupConverter:
* Using system properties
* Using a fluent API
* Using a properties file
* Using a Java Map
* Using Apache Commons Configuration
==== Configuration using the Builder
You can configure the Swagger2MarkupConverter by using the `Swagger2MarkupConfigBuilder` to build a custom `Swagger2MarkupConfig`. The `Swagger2MarkupConfigBuilder` can be used to define Swagger2Markup properties with a fluent API.
[source,java,indent=0]
----
include::../../test/java/io/github/swagger2markup/DocumentationTest.java[tags=swagger2MarkupConfigBuilder]
----
1. Create a `Swagger2MarkupConfigBuilder` using the default constructor.
2. Configure the output `MarkupLanguage`
3. Configure the output `Language`
4. Configure additional Swagger2Markup properties
5. Build an instance of the `Swagger2MarkupConfig`
6. Use the custom Swagger2MarkupConfig
You can also create a `Swagger2MarkupConfig` from a Properties file, a `Map` or a Apache Commons Configuration.
==== Configuration from a Properties file
[source,java,indent=0]
----
include::../../test/java/io/github/swagger2markup/DocumentationTest.java[tags=swagger2MarkupConfigFromProperties]
----
1. Load a `Properties` file from the classpath or local filesystem.
2. Create a `Swagger2MarkupConfigBuilder` using the proper constructor.
==== Configuration from a Map
[source,java,indent=0]
----
include::../../test/java/io/github/swagger2markup/DocumentationTest.java[tags=swagger2MarkupConfigFromMap]
----
1. Create a `Map` and configure the `Swagger2MarkupProperties`.
2. Create a `Swagger2MarkupConfigBuilder` using the proper constructor.
==== Configuration from a Apache Commons Configuration
Configuration parameters may be loaded from the following sources using Apache Commons Configuration:
* Properties files
* XML documents
* Property list files (plist)
* JDBC Datasource
* Servlet parameters
[source,java,indent=0]
----
include::../../test/java/io/github/swagger2markup/DocumentationTest.java[tags=swagger2MarkupConfigFromCommonsConfiguration]
----
1. Create an Apache Commons `Configuration` object using the proper ConfigurationBuilder.
2. Create a `Swagger2MarkupConfigBuilder` using the proper constructor.
==== Swagger2Markup properties
The properties of Swagger2Markup are defined in the class `io.github.swagger2markup.Swagger2MarkupProperties`.
The properties are considered in the following order:
1. Java System properties
2. Custom properties
3. Default properties (included in Swagger2Markup)
The following tables list all available properties of Swagger2Markup:
[options="header"]
.Mostly used properties
|===
|Name | Description | Possible Values | Default
|swagger2markup.markupLanguage| Specifies the markup language which should be used to generate the files. | ASCIIDOC, MARKDOWN, CONFLUENCE_MARKUP | ASCIIDOC
|swagger2markup.swaggerMarkupLanguage| Specifies the markup language used in Swagger descriptions. | ASCIIDOC, MARKDOWN, CONFLUENCE_MARKUP | MARKDOWN
|swagger2markup.pathsGroupedBy| Specifies how the paths should be grouped | AS_IS, TAGS | AS_IS
|swagger2markup.outputLanguage| Specifies the language of the labels | EN, DE, FR, RU | EN
|swagger2markup.lineSeparator| Specifies the line separator which should be used | UNIX, WINDOWS, MAC | <System-dependent>
|swagger2markup.generatedExamplesEnabled| Specifies if HTTP request and response examples should be generated | true, false | false
|swagger2markup.flatBodyEnabled| Optionally isolate the body parameter, if any, from other parameters | true, false | false
|swagger2markup.anchorPrefix| Optionally prefix all anchors for uniqueness if you want to include generated documents into a global documentation | Any String |
|===
[options="header"]
.Properties which configure the order of Swagger Objects
|===
|Name | Description | Possible Values | Default
|swagger2markup.tagOrderBy| Specifies the order of global tags | AS_IS, NATURAL, CUSTOM | NATURAL
|swagger2markup.operationOrderBy| Specifies the order of path operations | AS_IS, NATURAL, CUSTOM | NATURAL
|swagger2markup.definitionOrderBy| Specifies the order of definitions | AS_IS, NATURAL, CUSTOM | NATURAL
|swagger2markup.parameterOrderBy| Specifies the order of operation parameters | AS_IS, NATURAL, CUSTOM | NATURAL
|swagger2markup.propertyOrderBy | Specifies the order of definition properties | AS_IS, NATURAL, CUSTOM | NATURAL
|swagger2markup.responseOrderBy| Specifies the order of responses | AS_IS, NATURAL, CUSTOM | NATURAL
|===
[options="header"]
.Properties which configure document file names
|===
|Name | Description | Possible Values | Default
|swagger2markup.overviewDocument| Specifies the file name of the overview document | Any String | "overview"
|swagger2markup.pathsDocument| Specifies the file name of the paths document | Any String | "paths"
|swagger2markup.definitionsDocument| Specifies the file name of the definitions document | Any String | "definitions"
|swagger2markup.securityDocument| Specifies the file name of the security document | Any String | "security"
|===
[options="header"]
.Properties which configure the generation of separate files
|===
|Name | Description | Possible Values | Default
|swagger2markup.separatedDefinitionsEnabled| In addition to the Definitions file, also create separate definition files for each model definition | true, false | false
|swagger2markup.separatedOperationsEnabled| In addition to the Paths file, also create separate operation files for each operation | true, false | false
|swagger2markup.separatedOperationsFolder| Specifies the target folder path for definition files| Any valid folder name | "operations"
|swagger2markup.separatedDefinitionsFolder| Specifies the target folder path for operation files | Any valid folder name | "definitions"
|===
[options="header"]
.Properties which configure inter-document cross references
|===
|Name | Description | Possible Values | Default
|swagger2markup.interDocumentCrossReferencesEnabled| Enable use of inter-document cross-references when needed | true, false | false
|swagger2markup.interDocumentCrossReferencesPrefix| Specifies a prefix for all inter-document cross-references for advanced usage | Any String |
|===
[options="header"]
.Properties which configure inline schema rendering
|===
|Name | Description | Possible Values | Default
|swagger2markup.inlineSchemaEnabled| Enable inline object schema support | true, false | true
|===
=== Logging
Swagger2Markup uses http://www.slf4j.org/[SLF4J] for all internal logging, but leaves the underlying log implementation open. To change the log level, you have the set the log level of the `io.github.swagger2markup` package.

View File

@@ -1,21 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup;
public enum GroupBy {
AS_IS,
TAGS
}

View File

@@ -1,40 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup;
import java.util.Locale;
/**
* @author Maksim Myshkin
*/
public enum Language {
EN(new Locale("en")),
RU(new Locale("ru")),
FR(new Locale("fr")),
DE(new Locale("de")),
TR(new Locale("tr"));
private final Locale lang;
Language(final Locale lang) {
this.lang = lang;
}
public Locale toLocale() {
return lang;
}
}

View File

@@ -1,22 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup;
public enum OrderBy {
AS_IS,
NATURAL,
CUSTOM
}

View File

@@ -1,206 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup;
import io.github.swagger2markup.markup.builder.LineSeparator;
import io.github.swagger2markup.markup.builder.MarkupLanguage;
import io.github.swagger2markup.model.PathOperation;
import io.swagger.models.parameters.Parameter;
import java.util.Comparator;
/**
* Swagger2Markup configuration interface.
*/
public interface Swagger2MarkupConfig {
/**
* Specifies the markup language which should be used to generate the files.
*/
MarkupLanguage getMarkupLanguage();
/**
* Specifies the markup language used in Swagger descriptions.<br>
* By default, {@link io.github.swagger2markup.markup.builder.MarkupLanguage#MARKDOWN} is assumed.
*/
MarkupLanguage getSwaggerMarkupLanguage();
/**
* Include generated examples into the documents.
*/
boolean isGeneratedExamplesEnabled();
/**
* In addition to the Definitions file, also create separate definition files for each model definition.
*/
boolean isSeparatedDefinitionsEnabled();
/**
* In addition to the Paths file, also create separate operation files for each operation.
*/
boolean isSeparatedOperationsEnabled();
/**
* Specifies if the operations should be grouped by tags or stay as-is.
*/
GroupBy getPathsGroupedBy();
/**
* Specifies labels language of output files.
*/
Language getOutputLanguage();
/**
* Specifies if inline schemas are detailed
*/
boolean isInlineSchemaEnabled();
/**
* Specifies tag ordering.
*/
OrderBy getTagOrderBy();
/**
* Specifies a custom comparator function to order tags.
*/
Comparator<String> getTagOrdering();
/**
* Specifies operation ordering.
*/
OrderBy getOperationOrderBy();
/**
* Specifies a custom comparator function to order operations.
*/
Comparator<PathOperation> getOperationOrdering();
/**
* Specifies definition ordering.
*/
OrderBy getDefinitionOrderBy();
/**
* Specifies a custom comparator function to order definitions.
*/
Comparator<String> getDefinitionOrdering();
/**
* Specifies parameter ordering.
*/
OrderBy getParameterOrderBy();
/**
* Specifies a custom comparator function to order parameters.
*/
Comparator<Parameter> getParameterOrdering();
/**
* Specifies property ordering.
*/
OrderBy getPropertyOrderBy();
/**
* Specifies a custom comparator function to order properties.
*/
Comparator<String> getPropertyOrdering();
/**
* Specifies response ordering.
*/
OrderBy getResponseOrderBy();
/**
* Specifies a custom comparator function to order responses.
*/
Comparator<String> getResponseOrdering();
/**
* Enable use of inter-document cross-references when needed.
*/
boolean isInterDocumentCrossReferencesEnabled();
/**
* Inter-document cross-references optional prefix.
*/
String getInterDocumentCrossReferencesPrefix();
/**
* Optionally isolate the body parameter, if any, from other parameters.
*/
boolean isFlatBodyEnabled();
/**
* Optionally prefix all anchors for uniqueness.
*/
String getAnchorPrefix();
/**
* Overview document name (without extension).
*
* @return the overview document name (without extension)
*/
String getOverviewDocument();
/**
* Paths document name (without extension).
*
* @return the paths document name (without extension)
*/
String getPathsDocument();
/**
* Definitions document name (without extension).
*
* @return the definitions document name (without extension)
*/
String getDefinitionsDocument();
/**
* Security document name (without extension).
*
* @return the security document name (without extension)
*/
String getSecurityDocument();
/**
* Separated operations sub-folder name.
*
* @return the operations sub-folder name
*/
String getSeparatedOperationsFolder();
/**
* Separated definitions sub-folder name.
*
* @return the definitions sub-folder name
*/
String getSeparatedDefinitionsFolder();
/**
* Specifies the line separator which should be used.
*
* @return the line separator
*/
LineSeparator getLineSeparator();
/**
* Returns properties for extensions.
*
* @return the extension properties
*/
Swagger2MarkupProperties getExtensionsProperties();
}

View File

@@ -1,370 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup;
import io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder;
import io.github.swagger2markup.builder.Swagger2MarkupExtensionRegistryBuilder;
import io.github.swagger2markup.internal.document.builder.DefinitionsDocumentBuilder;
import io.github.swagger2markup.internal.document.builder.OverviewDocumentBuilder;
import io.github.swagger2markup.internal.document.builder.PathsDocumentBuilder;
import io.github.swagger2markup.internal.document.builder.SecurityDocumentBuilder;
import io.github.swagger2markup.spi.*;
import io.github.swagger2markup.utils.URIUtils;
import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.Validate;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
/**
* @author Robert Winkler
*/
public class Swagger2MarkupConverter {
private Context context;
private Swagger2MarkupExtensionRegistry extensionRegistry;
public Swagger2MarkupConverter(Context globalContext, Swagger2MarkupExtensionRegistry extensionRegistry) {
this.context = globalContext;
this.extensionRegistry = extensionRegistry;
}
/**
* Returns the global Context
*
* @return the global Context
*/
Context getContext(){
return context;
}
/**
* Creates a Swagger2MarkupConverter.Builder from a URI.
*
* @param swaggerUri the URI
* @return a Swagger2MarkupConverter
*/
public static Builder from(URI swaggerUri) {
Validate.notNull(swaggerUri, "swaggerUri must not be null");
String scheme = swaggerUri.getScheme();
if(scheme != null && swaggerUri.getScheme().startsWith("http")){
try {
return from(swaggerUri.toURL());
}
catch (MalformedURLException e) {
throw new RuntimeException("Failed to convert URI to URL", e);
}
} else if(scheme != null && swaggerUri.getScheme().startsWith("file")){
return from(Paths.get(swaggerUri));
}
else {
return from(URIUtils.convertUriWithoutSchemeToFileScheme(swaggerUri));
}
}
/**
* Creates a Swagger2MarkupConverter.Builder using a remote URL.
*
* @param swaggerURL the remote URL
* @return a Swagger2MarkupConverter
*/
public static Builder from(URL swaggerURL){
Validate.notNull(swaggerURL, "swaggerURL must not be null");
return new Builder(swaggerURL);
}
/**
* Creates a Swagger2MarkupConverter.Builder using a local Path.
*
* @param swaggerPath the local Path
* @return a Swagger2MarkupConverter
*/
public static Builder from(Path swaggerPath) {
Validate.notNull(swaggerPath, "swaggerPath must not be null");
if(Files.notExists(swaggerPath)){
throw new IllegalArgumentException(String.format("swaggerPath does not exist: %s", swaggerPath));
}
try {
if(Files.isHidden(swaggerPath)){
throw new IllegalArgumentException("swaggerPath must not be a hidden file");
}
} catch (IOException e) {
throw new RuntimeException("Failed to check if swaggerPath is a hidden file", e);
}
return new Builder(swaggerPath);
}
/**
* Creates a Swagger2MarkupConverter.Builder from a given Swagger model.
*
* @param swagger the Swagger source.
* @return a Swagger2MarkupConverter
*/
public static Builder from(Swagger swagger) {
Validate.notNull(swagger, "swagger must not be null");
return new Builder(swagger);
}
/**
* Creates a Swagger2MarkupConverter.Builder from a given Swagger YAML or JSON String.
*
* @param swaggerString the Swagger YAML or JSON String.
* @return a Swagger2MarkupConverter
*/
public static Builder from(String swaggerString) {
Validate.notEmpty(swaggerString, "swaggerString must not be null");
return from(new StringReader(swaggerString));
}
/**
* Creates a Swagger2MarkupConverter.Builder from a given Swagger YAML or JSON reader.
*
* @param swaggerReader the Swagger YAML or JSON reader.
* @return a Swagger2MarkupConverter
*/
public static Builder from(Reader swaggerReader) {
Validate.notNull(swaggerReader, "swaggerReader must not be null");
Swagger swagger;
try {
swagger = new SwaggerParser().parse(IOUtils.toString(swaggerReader));
} catch (IOException e) {
throw new RuntimeException("Swagger source can not be parsed", e);
}
if (swagger == null)
throw new IllegalArgumentException("Swagger source is in a wrong format");
return new Builder(swagger);
}
/**
* Converts the Swagger specification into the given {@code outputDirectory}.
*
* @param outputDirectory the output directory path
*/
public void toFolder(Path outputDirectory){
Validate.notNull(outputDirectory, "outputDirectory must not be null");
new OverviewDocumentBuilder(context, extensionRegistry, outputDirectory).build().writeToFile(outputDirectory.resolve(context.config.getOverviewDocument()), StandardCharsets.UTF_8);
new PathsDocumentBuilder(context, extensionRegistry, outputDirectory).build().writeToFile(outputDirectory.resolve(context.config.getPathsDocument()), StandardCharsets.UTF_8);
new DefinitionsDocumentBuilder(context, extensionRegistry, outputDirectory).build().writeToFile(outputDirectory.resolve(context.config.getDefinitionsDocument()), StandardCharsets.UTF_8);
new SecurityDocumentBuilder(context, extensionRegistry, outputDirectory).build().writeToFile(outputDirectory.resolve(context.config.getSecurityDocument()), StandardCharsets.UTF_8);
}
/**
* Converts the Swagger specification into the {@code outputPath} which can be either a directory (e.g /tmp) or a file without extension (e.g /tmp/swagger).
* Internally the method invokes either {@code toFolder} or {@code toFile}. If the {@code outputPath} is a directory, the directory must exist.
* Otherwise it cannot be determined if the {@code outputPath} is a directory or not.
*
* @param outputPath the output path
*/
public void toPath(Path outputPath) {
Validate.notNull(outputPath, "outputPath must not be null");
if (Files.isDirectory(outputPath)) {
toFolder(outputPath);
} else {
toFile(outputPath);
}
}
/**
* Converts the Swagger specification the given {@code outputFile}.<br>
* An extension identifying the markup language will be automatically added to file name.
*
* @param outputFile the output file
*/
public void toFile(Path outputFile) {
Validate.notNull(outputFile, "outputFile must not be null");
new OverviewDocumentBuilder(context,extensionRegistry, null).build().writeToFile(outputFile, StandardCharsets.UTF_8);
new PathsDocumentBuilder(context, extensionRegistry, null).build().writeToFile(outputFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
new DefinitionsDocumentBuilder(context, extensionRegistry, null).build().writeToFile(outputFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
new SecurityDocumentBuilder(context, extensionRegistry, null).build().writeToFile(outputFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
}
/**
* Converts the Swagger specification the given {@code outputFile}.
*
* @param outputFile the output file
*/
public void toFileWithoutExtension(Path outputFile){
Validate.notNull(outputFile, "outputFile must not be null");
new OverviewDocumentBuilder(context, extensionRegistry, null).build().writeToFileWithoutExtension(outputFile, StandardCharsets.UTF_8);
new PathsDocumentBuilder(context, extensionRegistry, null).build().writeToFileWithoutExtension(outputFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
new DefinitionsDocumentBuilder(context, extensionRegistry, null).build().writeToFileWithoutExtension(outputFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
new SecurityDocumentBuilder(context, extensionRegistry, null).build().writeToFileWithoutExtension(outputFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
}
/**
* Builds the document returns it as a String.
*
* @return the document as a String
*/
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(new OverviewDocumentBuilder(context,extensionRegistry, null).build().toString());
sb.append(new PathsDocumentBuilder(context, extensionRegistry, null).build().toString());
sb.append(new DefinitionsDocumentBuilder(context, extensionRegistry, null).build().toString());
sb.append(new SecurityDocumentBuilder(context, extensionRegistry, null).build().toString());
return sb.toString();
}
public static class Builder {
private final Swagger swagger;
private final URI swaggerLocation;
private Swagger2MarkupConfig config;
private Swagger2MarkupExtensionRegistry extensionRegistry;
/**
* Creates a Builder from a remote URL.
*
* @param swaggerUrl the remote URL
*/
Builder(URL swaggerUrl) {
try {
this.swaggerLocation = swaggerUrl.toURI();
} catch (URISyntaxException e) {
throw new IllegalArgumentException("swaggerURL is in a wrong format", e);
}
this.swagger = readSwagger(swaggerUrl.toString());
}
/**
* Creates a Builder from a local Path.
*
* @param swaggerPath the local Path
*/
Builder(Path swaggerPath) {
this.swaggerLocation = swaggerPath.toAbsolutePath().toUri();
this.swagger = readSwagger(swaggerPath.toString());
}
/**
* Creates a Builder using a given Swagger model.
*
* @param swagger the Swagger source.
*/
Builder(Swagger swagger) {
this.swagger = swagger;
this.swaggerLocation = null;
}
/**
* Uses the SwaggerParser to read the Swagger source.
*
* @param swaggerLocation the location of the Swagger source
* @return the Swagger model
*/
private Swagger readSwagger(String swaggerLocation){
Swagger swagger = new SwaggerParser().read(swaggerLocation);
if (swagger == null) {
throw new IllegalArgumentException("Failed to read the Swagger source");
}
return swagger;
}
public Builder withConfig(Swagger2MarkupConfig config) {
Validate.notNull(config, "config must not be null");
this.config = config;
return this;
}
public Builder withExtensionRegistry(Swagger2MarkupExtensionRegistry registry) {
Validate.notNull(registry, "registry must not be null");
this.extensionRegistry = registry;
return this;
}
public Swagger2MarkupConverter build() {
if (config == null)
config = new Swagger2MarkupConfigBuilder().build();
if (extensionRegistry == null)
extensionRegistry = new Swagger2MarkupExtensionRegistryBuilder().build();
Context context = new Context(config, swagger, swaggerLocation);
initExtensions(context);
applySwaggerExtensions(context);
return new Swagger2MarkupConverter(context, extensionRegistry);
}
private void initExtensions(Context context) {
for (SwaggerModelExtension extension : extensionRegistry.getSwaggerModelExtensions())
extension.setGlobalContext(context);
for (OverviewDocumentExtension extension : extensionRegistry.getOverviewDocumentExtensions())
extension.setGlobalContext(context);
for (DefinitionsDocumentExtension extension : extensionRegistry.getDefinitionsDocumentExtensions())
extension.setGlobalContext(context);
for (PathsDocumentExtension extension : extensionRegistry.getPathsDocumentExtensions())
extension.setGlobalContext(context);
for (SecurityDocumentExtension extension : extensionRegistry.getSecurityDocumentExtensions())
extension.setGlobalContext(context);
}
private void applySwaggerExtensions(Context context) {
for (SwaggerModelExtension swaggerModelExtension : extensionRegistry.getSwaggerModelExtensions()) {
swaggerModelExtension.apply(context.getSwagger());
}
}
}
public static class Context {
private Swagger2MarkupConfig config;
private Swagger swagger;
private URI swaggerLocation;
Context(Swagger2MarkupConfig config, Swagger swagger, URI swaggerLocation) {
this.config = config;
this.swagger = swagger;
this.swaggerLocation = swaggerLocation;
}
public Swagger2MarkupConfig getConfig() {
return config;
}
public Swagger getSwagger() {
return swagger;
}
public URI getSwaggerLocation() {
return swaggerLocation;
}
}
}

View File

@@ -1,55 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup;
import io.github.swagger2markup.spi.*;
import java.util.List;
/**
* Extension points registry interface.
*/
public interface Swagger2MarkupExtensionRegistry {
/**
* SwaggerModelExtension extension point can be used to preprocess the Swagger model.
* @return registered extensions extending SwaggerModelExtension extension point
*/
List<SwaggerModelExtension> getSwaggerModelExtensions();
/**
* OverviewDocumentExtension extension point can be used to extend the overview document content.
* @return registered extensions extending OverviewDocumentExtension extension point
*/
List<OverviewDocumentExtension> getOverviewDocumentExtensions();
/**
* DefinitionsDocumentExtension extension point can be used to extend the definitions document content.
* @return registered extensions extending DefinitionsDocumentExtension extension point
*/
List<DefinitionsDocumentExtension> getDefinitionsDocumentExtensions();
/**
* SecurityContentExtension extension point can be used to extend the security document content.
* @return registered extensions extending SecurityContentExtension extension point
*/
List<SecurityDocumentExtension> getSecurityDocumentExtensions();
/**
* PathsDocumentExtension extension point can be used to extend the paths document content.
* @return registered extensions extending PathsDocumentExtension extension point
*/
List<PathsDocumentExtension> getPathsDocumentExtensions();
}

View File

@@ -1,338 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup;
import io.github.swagger2markup.markup.builder.MarkupLanguage;
import io.github.swagger2markup.utils.URIUtils;
import org.apache.commons.collections4.IteratorUtils;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.ConfigurationConverter;
import org.apache.commons.configuration2.MapConfiguration;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
public class Swagger2MarkupProperties {
/**
* Prefix for Swagger2Markup properties
*/
public static final String PROPERTIES_PREFIX = "swagger2markup";
public static final String MARKUP_LANGUAGE = PROPERTIES_PREFIX + ".markupLanguage";
public static final String SWAGGER_MARKUP_LANGUAGE = PROPERTIES_PREFIX + ".swaggerMarkupLanguage";
public static final String GENERATED_EXAMPLES_ENABLED = PROPERTIES_PREFIX + ".generatedExamplesEnabled";
public static final String SEPARATED_DEFINITIONS_ENABLED = PROPERTIES_PREFIX + ".separatedDefinitionsEnabled";
public static final String SEPARATED_OPERATIONS_ENABLED = PROPERTIES_PREFIX + ".separatedOperationsEnabled";
public static final String PATHS_GROUPED_BY = PROPERTIES_PREFIX + ".pathsGroupedBy";
public static final String OUTPUT_LANGUAGE = PROPERTIES_PREFIX + ".outputLanguage";
public static final String INLINE_SCHEMA_ENABLED = PROPERTIES_PREFIX + ".inlineSchemaEnabled";
public static final String INTER_DOCUMENT_CROSS_REFERENCES_ENABLED = PROPERTIES_PREFIX + ".interDocumentCrossReferencesEnabled";
public static final String INTER_DOCUMENT_CROSS_REFERENCES_PREFIX = PROPERTIES_PREFIX + ".interDocumentCrossReferencesPrefix";
public static final String FLAT_BODY_ENABLED = PROPERTIES_PREFIX + ".flatBodyEnabled";
public static final String ANCHOR_PREFIX = PROPERTIES_PREFIX + ".anchorPrefix";
public static final String OVERVIEW_DOCUMENT = PROPERTIES_PREFIX + ".overviewDocument";
public static final String PATHS_DOCUMENT = PROPERTIES_PREFIX + ".pathsDocument";
public static final String DEFINITIONS_DOCUMENT = PROPERTIES_PREFIX + ".definitionsDocument";
public static final String SECURITY_DOCUMENT = PROPERTIES_PREFIX + ".securityDocument";
public static final String SEPARATED_OPERATIONS_FOLDER = PROPERTIES_PREFIX + ".separatedOperationsFolder";
public static final String SEPARATED_DEFINITIONS_FOLDER = PROPERTIES_PREFIX + ".separatedDefinitionsFolder";
public static final String TAG_ORDER_BY = PROPERTIES_PREFIX + ".tagOrderBy";
public static final String OPERATION_ORDER_BY = PROPERTIES_PREFIX + ".operationOrderBy";
public static final String DEFINITION_ORDER_BY = PROPERTIES_PREFIX + ".definitionOrderBy";
public static final String PARAMETER_ORDER_BY = PROPERTIES_PREFIX + ".parameterOrderBy";
public static final String PROPERTY_ORDER_BY = PROPERTIES_PREFIX + ".propertyOrderBy";
public static final String RESPONSE_ORDER_BY = PROPERTIES_PREFIX + ".responseOrderBy";
public static final String LINE_SEPARATOR = PROPERTIES_PREFIX + ".lineSeparator";
/**
* Prefix for Swagger2Markup extension properties
*/
public static final String EXTENSION_PREFIX = "extensions";
private final Configuration configuration;
public Swagger2MarkupProperties(Properties properties) {
this(ConfigurationConverter.getConfiguration(properties));
}
public Swagger2MarkupProperties(Map<String, String> map) {
this(new MapConfiguration(map));
}
public Swagger2MarkupProperties(Configuration configuration){
this.configuration = configuration;
}
/**
* Returns an optional String property value associated with the given key.
* @param key the property name to resolve
*
* @return The string property
*/
public Optional<String> getString(String key){
return Optional.ofNullable(configuration.getString(key));
}
/**
* Return the String property value associated with the given key, or
* {@code defaultValue} if the key cannot be resolved.
* @param key the property name to resolve
* @param defaultValue the default value to return if no value is found
*
* @return The string property
*/
public String getString(String key, String defaultValue){
return configuration.getString(key, defaultValue);
}
/**
* Return the int property value associated with the given key, or
* {@code defaultValue} if the key cannot be resolved.
* @param key the property name to resolve
* @param defaultValue the default value to return if no value is found
*
* @return The int property
*/
public int getInt(String key, int defaultValue){
return configuration.getInt(key, defaultValue);
}
/**
* Returns an optional Integer property value associated with the given key.
* @param key the property name to resolve
*
* @return An optional Integer property
*/
public Optional<Integer> getInteger(String key){
return Optional.ofNullable(configuration.getInteger(key, null));
}
/**
* Return the int property value associated with the given key (never {@code null}).
* @throws IllegalStateException if the key cannot be
*
* @return The int property
*/
public int getRequiredInt(String key){
Optional<Integer> value = getInteger(key);
if(value.isPresent()){
return value.get();
}
throw new IllegalStateException(String.format("required key [%s] not found", key));
}
/**
* Return the boolean property value associated with the given key (never {@code null}).
* @throws IllegalStateException if the key cannot be resolved
*
* @return The boolean property
*/
public boolean getRequiredBoolean(String key){
Boolean value = configuration.getBoolean(key, null);
if(value != null){
return value;
}else{
throw new IllegalStateException(String.format("required key [%s] not found", key));
}
}
/**
* Return the boolean property value associated with the given key, or
* {@code defaultValue} if the key cannot be resolved.
* @param key the property name to resolve
* @param defaultValue the default value to return if no value is found
*
* @return The boolean property
*/
public boolean getBoolean(String key, boolean defaultValue){
return configuration.getBoolean(key, defaultValue);
}
/**
* Return the URI property value associated with the given key, or
* {@code defaultValue} if the key cannot be resolved.
* @param key the property name to resolve
* @throws IllegalStateException if the value cannot be mapped to the enum
*
* @return The URI property
*/
public Optional<URI> getURI(String key){
Optional<String> property = getString(key);
if(property.isPresent()){
return Optional.of(URIUtils.create(property.get()));
}else{
return Optional.empty();
}
}
/**
* Return the URI property value associated with the given key (never {@code null}).
* @throws IllegalStateException if the key cannot be resolved
*
* @return The URI property
*/
public URI getRequiredURI(String key){
Optional<String> property = getString(key);
if(property.isPresent()){
return URIUtils.create(property.get());
}else{
throw new IllegalStateException(String.format("required key [%s] not found", key));
}
}
/**
* Return the Path property value associated with the given key, or
* {@code defaultValue} if the key cannot be resolved.
* @param key the property name to resolve
* @throws IllegalStateException if the value cannot be mapped to the enum
*
* @return The Path property
*/
public Optional<Path> getPath(String key){
Optional<String> property = getString(key);
if(property.isPresent()){
return Optional.of(Paths.get(property.get()));
}else{
return Optional.empty();
}
}
/**
* Return the Path property value associated with the given key (never {@code null}).
* @throws IllegalStateException if the key cannot be resolved
*
* @return The Path property
*/
public Path getRequiredPath(String key){
Optional<String> property = getString(key);
if(property.isPresent()){
return Paths.get(property.get());
}else{
throw new IllegalStateException(String.format("required key [%s] not found", key));
}
}
/**
* Return the MarkupLanguage property value associated with the given key, or
* {@code defaultValue} if the key cannot be resolved.
* @param key the property name to resolve
*
* @return The MarkupLanguage property
*/
public Optional<MarkupLanguage> getMarkupLanguage(String key){
Optional<String> property = getString(key);
if(property.isPresent()){
return Optional.of(MarkupLanguage.valueOf(property.get()));
}else{
return Optional.empty();
}
}
/**
* Return the MarkupLanguage property value associated with the given key (never {@code null}).
* @throws IllegalStateException if the key cannot be resolved
*
* @return The MarkupLanguage property
*/
public MarkupLanguage getRequiredMarkupLanguage(String key){
return MarkupLanguage.valueOf(configuration.getString(key));
}
/**
* Return the Language property value associated with the given key, or
* {@code defaultValue} if the key cannot be resolved.
* @param key the property name to resolve
*
* @return The Language property
*/
public Language getLanguage(String key){
return Language.valueOf(configuration.getString(key));
}
/**
* Return the GroupBy property value associated with the given key, or
* {@code defaultValue} if the key cannot be resolved.
* @param key the property name to resolve
* @throws IllegalStateException if the value cannot be mapped to the enum
*
* @return The GroupBy property
*/
public GroupBy getGroupBy(String key){
return GroupBy.valueOf(configuration.getString(key));
}
/**
* Return the OrderBy property value associated with the given key, or
* {@code defaultValue} if the key cannot be resolved.
* @param key the property name to resolve
* @throws IllegalStateException if the value cannot be mapped to the enum
*
* @return The OrderBy property
*/
public OrderBy getOrderBy(String key){
return OrderBy.valueOf(configuration.getString(key));
}
/**
* Return the String property value associated with the given key (never {@code null}).
* @throws IllegalStateException if the key cannot be resolved
*
* @return The String property
*/
public String getRequiredString(String key) throws IllegalStateException{
Optional<String> property = getString(key);
if(property.isPresent()){
return property.get();
}else{
throw new IllegalStateException(String.format("required key [%s] not found", key));
}
}
/**
* Return the list of keys.
*
* @return the list of keys.
*/
public List<String> getKeys(){
return IteratorUtils.toList(configuration.getKeys());
}
/**
* Get the list of the keys contained in the configuration that match the
* specified prefix. For instance, if the configuration contains the
* following keys:<br>
* {@code swagger2markup.extensions.folder1, swagger2markup.extensions.folder2, swagger2markup.folder3},<br>
* an invocation of {@code getKeys("swagger2markup.extensions");}<br>
* will return the key below:<br>
* {@code swagger2markup.extensions.folder1, swagger2markup.extensions.folder2}.<br>
* Note that the prefix itself is included in the result set if there is a
* matching key. The exact behavior - how the prefix is actually
* interpreted - depends on a concrete implementation.
*
* @param prefix The prefix to test against.
*
* @return the list of keys.
*/
public List<String> getKeys(String prefix){
return IteratorUtils.toList(configuration.getKeys(prefix));
}
}

View File

@@ -1,690 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.builder;
import com.google.common.base.Function;
import com.google.common.collect.Ordering;
import io.github.swagger2markup.*;
import io.github.swagger2markup.markup.builder.LineSeparator;
import io.github.swagger2markup.markup.builder.MarkupLanguage;
import io.github.swagger2markup.model.PathOperation;
import io.swagger.models.HttpMethod;
import io.swagger.models.parameters.Parameter;
import org.apache.commons.configuration2.*;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Comparator;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import static io.github.swagger2markup.Swagger2MarkupProperties.*;
public class Swagger2MarkupConfigBuilder {
private static final Logger logger = LoggerFactory.getLogger(Swagger2MarkupConfigBuilder.class);
private static final String PROPERTIES_DEFAULT = "io/github/swagger2markup/config/default.properties";
static final Ordering<PathOperation> OPERATION_METHOD_NATURAL_ORDERING = Ordering
.explicit(HttpMethod.POST, HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE, HttpMethod.PATCH, HttpMethod.HEAD, HttpMethod.OPTIONS)
.onResultOf(new Function<PathOperation, HttpMethod>() {
public HttpMethod apply(PathOperation operation) {
return operation.getMethod();
}
});
static final Ordering<PathOperation> OPERATION_PATH_NATURAL_ORDERING = Ordering
.natural()
.onResultOf(new Function<PathOperation, String>() {
public String apply(PathOperation operation) {
return operation.getPath();
}
});
static final Ordering<Parameter> PARAMETER_IN_NATURAL_ORDERING = Ordering
.explicit("header", "path", "query", "formData", "body")
.onResultOf(new Function<Parameter, String>() {
public String apply(Parameter parameter) {
return parameter.getIn();
}
});
static final Ordering<Parameter> PARAMETER_NAME_NATURAL_ORDERING = Ordering
.natural()
.onResultOf(new Function<Parameter, String>() {
public String apply(Parameter parameter) {
return parameter.getName();
}
});
DefaultSwagger2MarkupConfig config = new DefaultSwagger2MarkupConfig();
public Swagger2MarkupConfigBuilder() {
this(new PropertiesConfiguration());
}
public Swagger2MarkupConfigBuilder(Properties properties) {
this(ConfigurationConverter.getConfiguration(properties));
}
public Swagger2MarkupConfigBuilder(Map<String, String> map) {
this(new MapConfiguration(map));
}
public Swagger2MarkupConfigBuilder(Configuration configuration) {
CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
compositeConfiguration.addConfiguration(new SystemConfiguration());
compositeConfiguration.addConfiguration(configuration);
compositeConfiguration.addConfiguration(getDefaultConfiguration());
Swagger2MarkupProperties swagger2MarkupProperties = new Swagger2MarkupProperties(compositeConfiguration);
config.markupLanguage = swagger2MarkupProperties.getRequiredMarkupLanguage(MARKUP_LANGUAGE);
config.swaggerMarkupLanguage = swagger2MarkupProperties.getRequiredMarkupLanguage(SWAGGER_MARKUP_LANGUAGE);
config.generatedExamplesEnabled = swagger2MarkupProperties.getRequiredBoolean(GENERATED_EXAMPLES_ENABLED);
config.separatedDefinitionsEnabled = swagger2MarkupProperties.getRequiredBoolean(SEPARATED_DEFINITIONS_ENABLED);
config.separatedOperationsEnabled = swagger2MarkupProperties.getRequiredBoolean(SEPARATED_OPERATIONS_ENABLED);
config.pathsGroupedBy = swagger2MarkupProperties.getGroupBy(PATHS_GROUPED_BY);
config.outputLanguage = swagger2MarkupProperties.getLanguage(OUTPUT_LANGUAGE);
config.inlineSchemaEnabled = swagger2MarkupProperties.getRequiredBoolean(INLINE_SCHEMA_ENABLED);
config.interDocumentCrossReferencesEnabled = swagger2MarkupProperties.getRequiredBoolean(INTER_DOCUMENT_CROSS_REFERENCES_ENABLED);
config.interDocumentCrossReferencesPrefix = swagger2MarkupProperties.getString(INTER_DOCUMENT_CROSS_REFERENCES_PREFIX, null);
config.flatBodyEnabled = swagger2MarkupProperties.getRequiredBoolean(FLAT_BODY_ENABLED);
config.anchorPrefix = swagger2MarkupProperties.getString(ANCHOR_PREFIX, null);
config.overviewDocument = swagger2MarkupProperties.getRequiredString(OVERVIEW_DOCUMENT);
config.pathsDocument = swagger2MarkupProperties.getRequiredString(PATHS_DOCUMENT);
config.definitionsDocument = swagger2MarkupProperties.getRequiredString(DEFINITIONS_DOCUMENT);
config.securityDocument = swagger2MarkupProperties.getRequiredString(SECURITY_DOCUMENT);
config.separatedOperationsFolder = swagger2MarkupProperties.getRequiredString(SEPARATED_OPERATIONS_FOLDER);
config.separatedDefinitionsFolder = swagger2MarkupProperties.getRequiredString(SEPARATED_DEFINITIONS_FOLDER);
config.tagOrderBy = swagger2MarkupProperties.getOrderBy(TAG_ORDER_BY);
config.operationOrderBy = swagger2MarkupProperties.getOrderBy(OPERATION_ORDER_BY);
config.definitionOrderBy = swagger2MarkupProperties.getOrderBy(DEFINITION_ORDER_BY);
config.parameterOrderBy = swagger2MarkupProperties.getOrderBy(PARAMETER_ORDER_BY);
config.propertyOrderBy = swagger2MarkupProperties.getOrderBy(PROPERTY_ORDER_BY);
config.responseOrderBy = swagger2MarkupProperties.getOrderBy(RESPONSE_ORDER_BY);
Optional<String> lineSeparator = swagger2MarkupProperties.getString(LINE_SEPARATOR);
if(lineSeparator.isPresent() && StringUtils.isNoneBlank(lineSeparator.get())){
config.lineSeparator = LineSeparator.valueOf(lineSeparator.get());
}
Configuration swagger2markupConfiguration = compositeConfiguration.subset(PROPERTIES_PREFIX);
Configuration extensionsConfiguration = swagger2markupConfiguration.subset(EXTENSION_PREFIX);
config.extensionsProperties = new Swagger2MarkupProperties(extensionsConfiguration);
}
/**
* Loads the default properties from the classpath.
*
* @return the default properties
*/
private Configuration getDefaultConfiguration() {
Configurations configs = new Configurations();
try {
return configs.properties(PROPERTIES_DEFAULT);
} catch (ConfigurationException e) {
throw new RuntimeException(String.format("Can't load default properties '%s'", PROPERTIES_DEFAULT), e);
}
}
/**
* Builds the Swagger2MarkupConfig.
*
* @return the Swagger2MarkupConfig
*/
public Swagger2MarkupConfig build() {
buildNaturalOrdering();
return config;
}
private void buildNaturalOrdering() {
if (config.tagOrderBy == OrderBy.NATURAL)
config.tagOrdering = Ordering.natural();
if (config.operationOrderBy == OrderBy.NATURAL)
config.operationOrdering = OPERATION_PATH_NATURAL_ORDERING.compound(OPERATION_METHOD_NATURAL_ORDERING);
if (config.definitionOrderBy == OrderBy.NATURAL)
config.definitionOrdering = Ordering.natural();
if (config.parameterOrderBy == OrderBy.NATURAL)
config.parameterOrdering = PARAMETER_IN_NATURAL_ORDERING.compound(PARAMETER_NAME_NATURAL_ORDERING);
if (config.propertyOrderBy == OrderBy.NATURAL)
config.propertyOrdering = Ordering.natural();
if (config.responseOrderBy == OrderBy.NATURAL)
config.responseOrdering = Ordering.natural();
}
/**
* Specifies the markup language which should be used to generate the files.
*
* @param markupLanguage the markup language which is used to generate the files
* @return this builder
*/
public Swagger2MarkupConfigBuilder withMarkupLanguage(MarkupLanguage markupLanguage) {
Validate.notNull(markupLanguage, "%s must not be null", "markupLanguage");
config.markupLanguage = markupLanguage;
return this;
}
/**
* Specifies the markup language used in Swagger descriptions.
*
* @param swaggerMarkupLanguage the markup language used in Swagger descriptions
* @return this builder
*/
public Swagger2MarkupConfigBuilder withSwaggerMarkupLanguage(MarkupLanguage swaggerMarkupLanguage) {
Validate.notNull(swaggerMarkupLanguage, "%s must not be null", "swaggerMarkupLanguage");
config.swaggerMarkupLanguage = swaggerMarkupLanguage;
return this;
}
/**
* Include generated examples into the documents.
*
* @return this builder
*/
public Swagger2MarkupConfigBuilder withGeneratedExamples() {
config.generatedExamplesEnabled = true;
return this;
}
/**
* In addition to the Definitions file, also create separate definition files for each model definition.
*
* @return this builder
*/
public Swagger2MarkupConfigBuilder withSeparatedDefinitions() {
config.separatedDefinitionsEnabled = true;
return this;
}
/**
* In addition to the Paths file, also create separate operation files for each operation.
*
* @return this builder
*/
public Swagger2MarkupConfigBuilder withSeparatedOperations() {
config.separatedOperationsEnabled = true;
return this;
}
/**
* Specifies if the paths should be grouped by tags or stay as-is.
*
* @param pathsGroupedBy the GroupBy enum
* @return this builder
*/
public Swagger2MarkupConfigBuilder withPathsGroupedBy(GroupBy pathsGroupedBy) {
Validate.notNull(pathsGroupedBy, "%s must not be null", "pathsGroupedBy");
config.pathsGroupedBy = pathsGroupedBy;
return this;
}
/**
* Specifies labels language of output files.
*
* @param language the enum
* @return this builder
*/
public Swagger2MarkupConfigBuilder withOutputLanguage(Language language) {
Validate.notNull(language, "%s must not be null", "language");
config.outputLanguage = language;
return this;
}
/**
* Disable inline schema support.
*
* @return this builder
*/
public Swagger2MarkupConfigBuilder withoutInlineSchema() {
config.inlineSchemaEnabled = false;
return this;
}
/**
* Specifies tag ordering.<br>
* By default tag ordering == {@link io.github.swagger2markup.OrderBy#NATURAL}.<br>
* Use {@link #withTagOrdering(Comparator)} to set a custom ordering.
*
* @param orderBy tag ordering
* @return this builder
*/
public Swagger2MarkupConfigBuilder withTagOrdering(OrderBy orderBy) {
Validate.notNull(orderBy, "%s must not be null", "orderBy");
Validate.isTrue(orderBy != OrderBy.CUSTOM, "You must provide a custom comparator if orderBy == OrderBy.CUSTOM");
config.tagOrderBy = orderBy;
return this;
}
/**
* Specifies a custom comparator function to order tags.
*
* @param tagOrdering tag ordering
* @return this builder
*/
public Swagger2MarkupConfigBuilder withTagOrdering(Comparator<String> tagOrdering) {
Validate.notNull(tagOrdering, "%s must not be null", "tagOrdering");
config.tagOrderBy = OrderBy.CUSTOM;
config.tagOrdering = tagOrdering;
return this;
}
/**
* Specifies operation ordering.<br>
* By default operation ordering == {@link io.github.swagger2markup.OrderBy#AS_IS}.<br>
* Use {@link #withOperationOrdering(Comparator)} to set a custom ordering.
*
* @param orderBy operation ordering
* @return this builder
*/
public Swagger2MarkupConfigBuilder withOperationOrdering(OrderBy orderBy) {
Validate.notNull(orderBy, "%s must not be null", "orderBy");
Validate.isTrue(orderBy != OrderBy.CUSTOM, "You must provide a custom comparator if orderBy == OrderBy.CUSTOM");
config.operationOrderBy = orderBy;
return this;
}
/**
* Specifies a custom comparator function to order operations.
*
* @param operationOrdering operation ordering
* @return this builder
*/
public Swagger2MarkupConfigBuilder withOperationOrdering(Comparator<PathOperation> operationOrdering) {
Validate.notNull(operationOrdering, "%s must not be null", "operationOrdering");
config.operationOrderBy = OrderBy.CUSTOM;
config.operationOrdering = operationOrdering;
return this;
}
/**
* Specifies definition ordering.<br>
* By default definition ordering == {@link io.github.swagger2markup.OrderBy#NATURAL}.<br>
* Use {@link #withDefinitionOrdering(Comparator)} to set a custom ordering.
*
* @param orderBy definition ordering
* @return this builder
*/
public Swagger2MarkupConfigBuilder withDefinitionOrdering(OrderBy orderBy) {
Validate.notNull(orderBy, "%s must not be null", "orderBy");
Validate.isTrue(orderBy != OrderBy.CUSTOM, "You must provide a custom comparator if orderBy == OrderBy.CUSTOM");
config.definitionOrderBy = orderBy;
return this;
}
/**
* Specifies a custom comparator function to order definitions.
*
* @param definitionOrdering definition ordering
* @return this builder
*/
public Swagger2MarkupConfigBuilder withDefinitionOrdering(Comparator<String> definitionOrdering) {
Validate.notNull(definitionOrdering, "%s must not be null", "definitionOrdering");
config.definitionOrderBy = OrderBy.CUSTOM;
config.definitionOrdering = definitionOrdering;
return this;
}
/**
* Specifies parameter ordering.<br>
* By default parameter ordering == {@link OrderBy#NATURAL}.<br>
* Use {@link #withParameterOrdering(Comparator)} to set a custom ordering.
*
* @param orderBy parameter ordering
* @return this builder
*/
public Swagger2MarkupConfigBuilder withParameterOrdering(OrderBy orderBy) {
Validate.notNull(orderBy, "%s must not be null", "orderBy");
Validate.isTrue(orderBy != OrderBy.CUSTOM, "You must provide a custom comparator if orderBy == OrderBy.CUSTOM");
config.parameterOrderBy = orderBy;
return this;
}
/**
* Specifies a custom comparator function to order parameters.
*
* @param parameterOrdering parameter ordering
* @return this builder
*/
public Swagger2MarkupConfigBuilder withParameterOrdering(Comparator<Parameter> parameterOrdering) {
Validate.notNull(parameterOrdering, "%s must not be null", "parameterOrdering");
config.parameterOrderBy = OrderBy.CUSTOM;
config.parameterOrdering = parameterOrdering;
return this;
}
/**
* Specifies property ordering.<br>
* By default property ordering == {@link io.github.swagger2markup.OrderBy#NATURAL}.<br>
* Use {@link #withPropertyOrdering(Comparator)} to set a custom ordering.
*
* @param orderBy property ordering
* @return this builder
*/
public Swagger2MarkupConfigBuilder withPropertyOrdering(OrderBy orderBy) {
Validate.notNull(orderBy, "%s must not be null", "orderBy");
Validate.isTrue(orderBy != OrderBy.CUSTOM, "You must provide a custom comparator if orderBy == OrderBy.CUSTOM");
config.propertyOrderBy = orderBy;
return this;
}
/**
* Specifies a custom comparator function to order properties.
*
* @param propertyOrdering property ordering
* @return this builder
*/
public Swagger2MarkupConfigBuilder withPropertyOrdering(Comparator<String> propertyOrdering) {
Validate.notNull(propertyOrdering, "%s must not be null", "propertyOrdering");
config.propertyOrderBy = OrderBy.CUSTOM;
config.propertyOrdering = propertyOrdering;
return this;
}
/**
* Specifies response ordering.<br>
* By default response ordering == {@link io.github.swagger2markup.OrderBy#NATURAL}.<br>
* Use {@link #withResponseOrdering(Comparator)} to set a custom ordering.
*
* @param orderBy response ordering
* @return this builder
*/
public Swagger2MarkupConfigBuilder withResponseOrdering(OrderBy orderBy) {
Validate.notNull(orderBy, "%s must not be null", "orderBy");
Validate.isTrue(orderBy != OrderBy.CUSTOM, "You must provide a custom comparator if orderBy == OrderBy.CUSTOM");
config.responseOrderBy = orderBy;
return this;
}
/**
* Specifies a custom comparator function to order responses.
*
* @param responseOrdering response ordering
* @return this builder
*/
public Swagger2MarkupConfigBuilder withResponseOrdering(Comparator<String> responseOrdering) {
Validate.notNull(responseOrdering, "%s must not be null", "responseOrdering");
config.responseOrderBy = OrderBy.CUSTOM;
config.responseOrdering = responseOrdering;
return this;
}
/**
* Enable use of inter-document cross-references when needed.
*
* @param prefix Prefix to document in all inter-document cross-references.
* @return this builder
*/
public Swagger2MarkupConfigBuilder withInterDocumentCrossReferences(String prefix) {
Validate.notNull(prefix, "%s must not be null", "prefix");
config.interDocumentCrossReferencesEnabled = true;
config.interDocumentCrossReferencesPrefix = prefix;
return this;
}
/**
* Enable use of inter-document cross-references when needed.
*
* @return this builder
*/
public Swagger2MarkupConfigBuilder withInterDocumentCrossReferences() {
config.interDocumentCrossReferencesEnabled = true;
return this;
}
/**
* Optionally isolate the body parameter, if any, from other parameters.
*
* @return this builder
*/
public Swagger2MarkupConfigBuilder withFlatBody() {
config.flatBodyEnabled = true;
return this;
}
/**
* Optionally prefix all anchors for uniqueness.
*
* @param anchorPrefix anchor prefix.
* @return this builder
*/
public Swagger2MarkupConfigBuilder withAnchorPrefix(String anchorPrefix) {
Validate.notNull(anchorPrefix, "%s must no be null", "anchorPrefix");
config.anchorPrefix = anchorPrefix;
return this;
}
/**
* Specifies the line separator which should be used.
*
* @param lineSeparator the lineSeparator
* @return this builder
*/
public Swagger2MarkupConfigBuilder withLineSeparator(LineSeparator lineSeparator) {
Validate.notNull(lineSeparator, "%s must no be null", "lineSeparator");
config.lineSeparator = lineSeparator;
return this;
}
static class DefaultSwagger2MarkupConfig implements Swagger2MarkupConfig{
private MarkupLanguage markupLanguage;
private MarkupLanguage swaggerMarkupLanguage;
private boolean generatedExamplesEnabled;
private boolean separatedDefinitionsEnabled;
private boolean separatedOperationsEnabled;
private GroupBy pathsGroupedBy;
private Language outputLanguage;
private boolean inlineSchemaEnabled;
private OrderBy tagOrderBy;
private Comparator<String> tagOrdering;
private OrderBy operationOrderBy;
private Comparator<PathOperation> operationOrdering;
private OrderBy definitionOrderBy;
private Comparator<String> definitionOrdering;
private OrderBy parameterOrderBy;
private Comparator<Parameter> parameterOrdering;
private OrderBy propertyOrderBy;
private Comparator<String> propertyOrdering;
private OrderBy responseOrderBy;
private Comparator<String> responseOrdering;
private boolean interDocumentCrossReferencesEnabled;
private String interDocumentCrossReferencesPrefix;
private boolean flatBodyEnabled;
private String anchorPrefix;
private LineSeparator lineSeparator;
private String overviewDocument;
private String pathsDocument;
private String definitionsDocument;
private String securityDocument;
private String separatedOperationsFolder;
private String separatedDefinitionsFolder;
private Swagger2MarkupProperties extensionsProperties;
@Override
public MarkupLanguage getMarkupLanguage() {
return markupLanguage;
}
@Override
public MarkupLanguage getSwaggerMarkupLanguage() {
return swaggerMarkupLanguage;
}
@Override
public boolean isGeneratedExamplesEnabled() {
return generatedExamplesEnabled;
}
@Override
public boolean isSeparatedDefinitionsEnabled() {
return separatedDefinitionsEnabled;
}
@Override
public boolean isSeparatedOperationsEnabled() {
return separatedOperationsEnabled;
}
@Override
public GroupBy getPathsGroupedBy() {
return pathsGroupedBy;
}
@Override
public Language getOutputLanguage() {
return outputLanguage;
}
@Override
public boolean isInlineSchemaEnabled() {
return inlineSchemaEnabled;
}
@Override
public OrderBy getTagOrderBy() {
return tagOrderBy;
}
@Override
public Comparator<String> getTagOrdering() {
return tagOrdering;
}
@Override
public OrderBy getOperationOrderBy() {
return operationOrderBy;
}
@Override
public Comparator<PathOperation> getOperationOrdering() {
return operationOrdering;
}
@Override
public OrderBy getDefinitionOrderBy() {
return definitionOrderBy;
}
@Override
public Comparator<String> getDefinitionOrdering() {
return definitionOrdering;
}
@Override
public OrderBy getParameterOrderBy() {
return parameterOrderBy;
}
@Override
public Comparator<Parameter> getParameterOrdering() {
return parameterOrdering;
}
@Override
public OrderBy getPropertyOrderBy() {
return propertyOrderBy;
}
@Override
public Comparator<String> getPropertyOrdering() {
return propertyOrdering;
}
@Override
public OrderBy getResponseOrderBy() {
return responseOrderBy;
}
@Override
public Comparator<String> getResponseOrdering() {
return responseOrdering;
}
@Override
public boolean isInterDocumentCrossReferencesEnabled() {
return interDocumentCrossReferencesEnabled;
}
@Override
public String getInterDocumentCrossReferencesPrefix() {
return interDocumentCrossReferencesPrefix;
}
@Override
public boolean isFlatBodyEnabled() {
return flatBodyEnabled;
}
@Override
public String getAnchorPrefix() {
return anchorPrefix;
}
@Override
public String getOverviewDocument() {
return overviewDocument;
}
@Override
public String getPathsDocument() {
return pathsDocument;
}
@Override
public String getDefinitionsDocument() {
return definitionsDocument;
}
@Override
public String getSecurityDocument() {
return securityDocument;
}
@Override
public String getSeparatedOperationsFolder() {
return separatedOperationsFolder;
}
@Override
public String getSeparatedDefinitionsFolder() {
return separatedDefinitionsFolder;
}
@Override
public LineSeparator getLineSeparator() {
return lineSeparator;
}
@Override
public Swagger2MarkupProperties getExtensionsProperties() {
return extensionsProperties;
}
}
}

View File

@@ -1,128 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.builder;
import io.github.swagger2markup.Swagger2MarkupExtensionRegistry;
import io.github.swagger2markup.spi.*;
import java.util.List;
import static java.util.ServiceLoader.load;
import static org.apache.commons.collections4.IteratorUtils.toList;
public class Swagger2MarkupExtensionRegistryBuilder {
private final Context context;
public Swagger2MarkupExtensionRegistryBuilder() {
List<SwaggerModelExtension> swaggerModelExtensions = toList(load(SwaggerModelExtension.class).iterator());
List<OverviewDocumentExtension> overviewDocumentExtensions = toList(load(OverviewDocumentExtension.class).iterator());
List<DefinitionsDocumentExtension> definitionsDocumentExtensions = toList(load(DefinitionsDocumentExtension.class).iterator());
List<PathsDocumentExtension> pathsDocumentExtensions = toList(load(PathsDocumentExtension.class).iterator());
List<SecurityDocumentExtension> securityDocumentExtensions = toList(load(SecurityDocumentExtension.class).iterator());
context = new Context(
swaggerModelExtensions,
overviewDocumentExtensions,
definitionsDocumentExtensions,
pathsDocumentExtensions,
securityDocumentExtensions);
}
public Swagger2MarkupExtensionRegistry build() {
return new DefaultSwagger2MarkupExtensionRegistry(context);
}
public Swagger2MarkupExtensionRegistryBuilder withSwaggerModelExtension(SwaggerModelExtension extension) {
context.swaggerModelExtensions.add(extension);
return this;
}
public Swagger2MarkupExtensionRegistryBuilder withOverviewDocumentExtension(OverviewDocumentExtension extension) {
context.overviewDocumentExtensions.add(extension);
return this;
}
public Swagger2MarkupExtensionRegistryBuilder withDefinitionsDocumentExtension(DefinitionsDocumentExtension extension) {
context.definitionsDocumentExtensions.add(extension);
return this;
}
public Swagger2MarkupExtensionRegistryBuilder withPathsDocumentExtension(PathsDocumentExtension extension) {
context.pathsDocumentExtensions.add(extension);
return this;
}
public Swagger2MarkupExtensionRegistryBuilder withSecurityDocumentExtension(SecurityDocumentExtension extension) {
context.securityDocumentExtensions.add(extension);
return this;
}
static class DefaultSwagger2MarkupExtensionRegistry implements Swagger2MarkupExtensionRegistry{
private Context context;
DefaultSwagger2MarkupExtensionRegistry(Context context) {
this.context = context;
}
@Override
public List<SwaggerModelExtension> getSwaggerModelExtensions(){
return context.swaggerModelExtensions;
}
@Override
public List<OverviewDocumentExtension> getOverviewDocumentExtensions(){
return context.overviewDocumentExtensions;
}
@Override
public List<DefinitionsDocumentExtension> getDefinitionsDocumentExtensions(){
return context.definitionsDocumentExtensions;
}
@Override
public List<SecurityDocumentExtension> getSecurityDocumentExtensions(){
return context.securityDocumentExtensions;
}
@Override
public List<PathsDocumentExtension> getPathsDocumentExtensions(){
return context.pathsDocumentExtensions;
}
}
private static class Context {
public final List<SwaggerModelExtension> swaggerModelExtensions;
public final List<OverviewDocumentExtension> overviewDocumentExtensions;
public final List<DefinitionsDocumentExtension> definitionsDocumentExtensions;
public final List<PathsDocumentExtension> pathsDocumentExtensions;
public final List<SecurityDocumentExtension> securityDocumentExtensions;
public Context(List<SwaggerModelExtension> swaggerModelExtensions,
List<OverviewDocumentExtension> overviewDocumentExtensions,
List<DefinitionsDocumentExtension> definitionsDocumentExtensions,
List<PathsDocumentExtension> pathsDocumentExtensions,
List<SecurityDocumentExtension> securityDocumentExtensions){
this.swaggerModelExtensions = swaggerModelExtensions;
this.overviewDocumentExtensions = overviewDocumentExtensions;
this.definitionsDocumentExtensions = definitionsDocumentExtensions;
this.pathsDocumentExtensions = pathsDocumentExtensions;
this.securityDocumentExtensions = securityDocumentExtensions;
}
}
}

View File

@@ -1,61 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.document;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import java.nio.charset.Charset;
import java.nio.file.OpenOption;
import java.nio.file.Path;
public class MarkupDocument {
private MarkupDocBuilder markupDocBuilder;
public MarkupDocument(MarkupDocBuilder markupDocBuilder) {
this.markupDocBuilder = markupDocBuilder;
}
/**
* Returns a string representation of the document.
*/
public String toString() {
return markupDocBuilder.toString();
}
/**
* Writes the content of the builder to a file.<br>
* An extension identifying the markup language will be automatically added to file name.
*
* @param file the generated file
* @param charset the the charset to use for encoding
* @param options the file open options
*/
public void writeToFile(Path file, Charset charset, OpenOption... options) {
markupDocBuilder.writeToFile(file, charset, options);
}
/**
* Writes the content of the builder to a file.
*
* @param file the generated file
* @param charset the the charset to use for encoding
* @param options the file open options
*/
public void writeToFileWithoutExtension(Path file, Charset charset, OpenOption... options) {
markupDocBuilder.writeToFileWithoutExtension(file, charset, options);
}
}

View File

@@ -1,336 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.document.builder;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.Swagger2MarkupExtensionRegistry;
import io.github.swagger2markup.internal.document.MarkupDocument;
import io.github.swagger2markup.internal.type.ObjectType;
import io.github.swagger2markup.internal.type.ObjectTypePolymorphism;
import io.github.swagger2markup.internal.type.Type;
import io.github.swagger2markup.internal.utils.ModelUtils;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.spi.DefinitionsDocumentExtension;
import io.swagger.models.Model;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.*;
import static io.github.swagger2markup.internal.utils.MapUtils.toKeySet;
import static io.github.swagger2markup.spi.DefinitionsDocumentExtension.Context;
import static io.github.swagger2markup.spi.DefinitionsDocumentExtension.Position;
import static io.github.swagger2markup.utils.IOUtils.normalizeName;
import static org.apache.commons.lang3.StringUtils.defaultString;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
/**
* @author Robert Winkler
*/
public class DefinitionsDocumentBuilder extends MarkupDocumentBuilder {
/* Discriminator is only displayed for inheriting definitions */
private static final boolean ALWAYS_DISPLAY_DISCRIMINATOR = false;
private static final String DEFINITIONS_ANCHOR = "definitions";
private final String DEFINITIONS;
private final String DISCRIMINATOR_COLUMN;
private final String POLYMORPHISM_COLUMN;
private final Map<ObjectTypePolymorphism.Nature, String> POLYMORPHISM_NATURE;
private final String TYPE_COLUMN;
private static final List<String> IGNORED_DEFINITIONS = Collections.singletonList("Void");
public DefinitionsDocumentBuilder(Swagger2MarkupConverter.Context context, Swagger2MarkupExtensionRegistry extensionRegistry, Path outputPath) {
super(context, extensionRegistry, outputPath);
ResourceBundle labels = ResourceBundle.getBundle("io/github/swagger2markup/lang/labels", config.getOutputLanguage().toLocale());
DEFINITIONS = labels.getString("definitions");
POLYMORPHISM_COLUMN = labels.getString("polymorphism.column");
DISCRIMINATOR_COLUMN = labels.getString("polymorphism.discriminator");
POLYMORPHISM_NATURE = new HashMap<ObjectTypePolymorphism.Nature, String>() {{
put(ObjectTypePolymorphism.Nature.COMPOSITION, labels.getString("polymorphism.nature.COMPOSITION"));
put(ObjectTypePolymorphism.Nature.INHERITANCE, labels.getString("polymorphism.nature.INHERITANCE"));
}};
TYPE_COLUMN = labels.getString("type_column");
if (config.isSeparatedDefinitionsEnabled()) {
if (logger.isDebugEnabled()) {
logger.debug("Create separated definition files is enabled.");
}
Validate.notNull(outputPath, "Output directory is required for separated definition files!");
} else {
if (logger.isDebugEnabled()) {
logger.debug("Create separated definition files is disabled.");
}
}
}
/**
* Builds the definitions MarkupDocument.
*
* @return the definitions MarkupDocument
*/
@Override
public MarkupDocument build() {
if (MapUtils.isNotEmpty(globalContext.getSwagger().getDefinitions())) {
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_BEFORE, this.markupDocBuilder));
buildDefinitionsTitle(DEFINITIONS);
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_BEGIN, this.markupDocBuilder));
buildDefinitionsSection();
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_END, this.markupDocBuilder));
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_AFTER, this.markupDocBuilder));
}
return new MarkupDocument(markupDocBuilder);
}
private void buildDefinitionsSection() {
Set<String> definitionNames = toKeySet(globalContext.getSwagger().getDefinitions(), config.getDefinitionOrdering());
for (String definitionName : definitionNames) {
Model model = globalContext.getSwagger().getDefinitions().get(definitionName);
if (isNotBlank(definitionName)) {
if (checkThatDefinitionIsNotInIgnoreList(definitionName)) {
buildDefinition(definitionName, model);
if (logger.isInfoEnabled()) {
logger.info("Definition processed : '{}'", definitionName);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Definition was ignored : '{}'", definitionName);
}
}
}
}
}
private void buildDefinitionsTitle(String title) {
this.markupDocBuilder.sectionTitleWithAnchorLevel1(title, DEFINITIONS_ANCHOR);
}
/**
* Apply extension context to all DefinitionsContentExtension
*
* @param context context
*/
private void applyDefinitionsDocumentExtension(Context context) {
for (DefinitionsDocumentExtension extension : extensionRegistry.getDefinitionsDocumentExtensions()) {
extension.apply(context);
}
}
/**
* Create the definition filename depending on the generation mode
*
* @param definitionName definition name
* @return definition filename
*/
private String resolveDefinitionDocument(String definitionName) {
if (config.isSeparatedDefinitionsEnabled())
return new File(config.getSeparatedDefinitionsFolder(), markupDocBuilder.addFileExtension(normalizeName(definitionName))).getPath();
else
return markupDocBuilder.addFileExtension(config.getDefinitionsDocument());
}
/**
* Generate definition files depending on the generation mode
*
* @param definitionName definition name to process
* @param model definition model to process
*/
private void buildDefinition(String definitionName, Model model) {
if (config.isSeparatedDefinitionsEnabled()) {
MarkupDocBuilder defDocBuilder = copyMarkupDocBuilder();
buildDefinition(definitionName, model, defDocBuilder);
Path definitionFile = outputPath.resolve(resolveDefinitionDocument(definitionName));
defDocBuilder.writeToFileWithoutExtension(definitionFile, StandardCharsets.UTF_8);
if (logger.isInfoEnabled()) {
logger.info("Separate definition file produced : '{}'", definitionFile);
}
definitionRef(definitionName, this.markupDocBuilder);
} else {
buildDefinition(definitionName, model, this.markupDocBuilder);
}
}
/**
* Checks that the definition is not in the list of ignored definitions.
*
* @param definitionName the name of the definition
* @return true if the definition can be processed
*/
private boolean checkThatDefinitionIsNotInIgnoreList(String definitionName) {
return !IGNORED_DEFINITIONS.contains(definitionName);
}
/**
* Builds a concrete definition
*
* @param definitionName the name of the definition
* @param model the Swagger Model of the definition
* @param docBuilder the docbuilder do use for output
*/
private void buildDefinition(String definitionName, Model model, MarkupDocBuilder docBuilder) {
applyDefinitionsDocumentExtension(new Context(Position.DEFINITION_BEFORE, docBuilder, definitionName, model));
buildDefinitionTitle(definitionName, definitionName, docBuilder);
applyDefinitionsDocumentExtension(new Context(Position.DEFINITION_BEGIN, docBuilder, definitionName, model));
buildDescriptionParagraph(model, docBuilder);
inlineDefinitions(typeSection(definitionName, model, docBuilder), definitionName, docBuilder);
applyDefinitionsDocumentExtension(new Context(Position.DEFINITION_END, docBuilder, definitionName, model));
applyDefinitionsDocumentExtension(new Context(Position.DEFINITION_AFTER, docBuilder, definitionName, model));
}
/**
* Builds a cross-reference to a separated definition file.
*
* @param definitionName definition name to target
* @param docBuilder the docbuilder do use for output
*/
private void definitionRef(String definitionName, MarkupDocBuilder docBuilder) {
buildDefinitionTitle(copyMarkupDocBuilder().crossReference(new DefinitionDocumentResolverDefault().apply(definitionName), definitionName, definitionName).toString(), "ref-" + definitionName, docBuilder);
}
/**
* Builds definition title
*
* @param title definition title
* @param anchor optional anchor (null => auto-generate from title)
* @param docBuilder the docbuilder do use for output
*/
private void buildDefinitionTitle(String title, String anchor, MarkupDocBuilder docBuilder) {
docBuilder.sectionTitleWithAnchorLevel2(title, anchor);
}
/**
* Builds the type informations of a definition
*
* @param definitionName name of the definition to display
* @param model model of the definition to display
* @param docBuilder the docbuilder do use for output
* @return a list of inlined types.
*/
private List<ObjectType> typeSection(String definitionName, Model model, MarkupDocBuilder docBuilder) {
List<ObjectType> inlineDefinitions = new ArrayList<>();
Type modelType = ModelUtils.resolveRefType(ModelUtils.getType(model, globalContext.getSwagger().getDefinitions(), new DefinitionDocumentResolverFromDefinition()));
if (!(modelType instanceof ObjectType)) {
modelType = createInlineType(modelType, definitionName, definitionName + " " + "inline", inlineDefinitions);
}
if (modelType instanceof ObjectType) {
ObjectType objectType = (ObjectType) modelType;
MarkupDocBuilder typeInfos = copyMarkupDocBuilder();
switch (objectType.getPolymorphism().getNature()) {
case COMPOSITION:
typeInfos.italicText(POLYMORPHISM_COLUMN).textLine(COLON + POLYMORPHISM_NATURE.get(objectType.getPolymorphism().getNature()));
break;
case INHERITANCE:
typeInfos.italicText(POLYMORPHISM_COLUMN).textLine(COLON + POLYMORPHISM_NATURE.get(objectType.getPolymorphism().getNature()));
typeInfos.italicText(DISCRIMINATOR_COLUMN).textLine(COLON + objectType.getPolymorphism().getDiscriminator());
break;
case NONE:
if (ALWAYS_DISPLAY_DISCRIMINATOR) {
if (StringUtils.isNotBlank(objectType.getPolymorphism().getDiscriminator()))
typeInfos.italicText(DISCRIMINATOR_COLUMN).textLine(COLON + objectType.getPolymorphism().getDiscriminator());
}
default: break;
}
String typeInfosString = typeInfos.toString();
if (StringUtils.isNotBlank(typeInfosString))
docBuilder.paragraph(typeInfosString, true);
inlineDefinitions.addAll(buildPropertiesTable(((ObjectType) modelType).getProperties(), definitionName, new DefinitionDocumentResolverFromDefinition(), docBuilder));
} else if (modelType != null) {
MarkupDocBuilder typeInfos = copyMarkupDocBuilder();
typeInfos.italicText(TYPE_COLUMN).textLine(COLON + modelType.displaySchema(docBuilder));
docBuilder.paragraph(typeInfos.toString());
}
return inlineDefinitions;
}
private void buildDescriptionParagraph(Model model, MarkupDocBuilder docBuilder) {
modelDescription(model, docBuilder);
}
private void modelDescription(Model model, MarkupDocBuilder docBuilder) {
String description = model.getDescription();
if (isNotBlank(description)) {
buildDescriptionParagraph(description, docBuilder);
}
}
/**
* Builds the title of an inline schema.
* Inline definitions should never been referenced in TOC because they have no real existence, so they are just text.
*
* @param title inline schema title
* @param anchor inline schema anchor
* @param docBuilder the docbuilder do use for output
*/
private void addInlineDefinitionTitle(String title, String anchor, MarkupDocBuilder docBuilder) {
docBuilder.anchor(anchor, null);
docBuilder.newLine();
docBuilder.boldTextLine(title);
}
/**
* Builds inline schema definitions
*
* @param definitions all inline definitions to display
* @param uniquePrefix unique prefix to prepend to inline object names to enforce unicity
* @param docBuilder the docbuilder do use for output
*/
private void inlineDefinitions(List<ObjectType> definitions, String uniquePrefix, MarkupDocBuilder docBuilder) {
if (CollectionUtils.isNotEmpty(definitions)) {
for (ObjectType definition : definitions) {
addInlineDefinitionTitle(definition.getName(), definition.getUniqueName(), docBuilder);
List<ObjectType> localDefinitions = buildPropertiesTable(definition.getProperties(), uniquePrefix, new DefinitionDocumentResolverFromDefinition(), docBuilder);
for (ObjectType localDefinition : localDefinitions)
inlineDefinitions(Collections.singletonList(localDefinition), localDefinition.getUniqueName(), docBuilder);
}
}
}
/**
* Overrides definition document resolver functor for inter-document cross-references from definitions files.
* This implementation simplify the path between two definitions because all definitions are in the same path.
*/
class DefinitionDocumentResolverFromDefinition extends DefinitionDocumentResolverDefault {
public DefinitionDocumentResolverFromDefinition() {
}
public String apply(String definitionName) {
String defaultResolver = super.apply(definitionName);
if (defaultResolver != null && config.isSeparatedDefinitionsEnabled())
return defaultString(config.getInterDocumentCrossReferencesPrefix()) + markupDocBuilder.addFileExtension(normalizeName(definitionName));
else
return defaultResolver;
}
}
}

View File

@@ -1,282 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.document.builder;
import io.github.swagger2markup.Swagger2MarkupConfig;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.Swagger2MarkupExtensionRegistry;
import io.github.swagger2markup.internal.document.MarkupDocument;
import io.github.swagger2markup.internal.type.*;
import io.github.swagger2markup.internal.utils.PropertyUtils;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.markup.builder.MarkupDocBuilders;
import io.github.swagger2markup.markup.builder.MarkupLanguage;
import io.github.swagger2markup.markup.builder.MarkupTableColumn;
import io.github.swagger2markup.utils.IOUtils;
import io.swagger.models.properties.Property;
import io.swagger.util.Json;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Path;
import java.util.*;
import static io.github.swagger2markup.internal.utils.MapUtils.toKeySet;
import static org.apache.commons.lang3.StringUtils.defaultString;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
/**
* @author Robert Winkler
*/
public abstract class MarkupDocumentBuilder {
protected static final String COLON = " : ";
protected final String DEFAULT_COLUMN;
protected final String EXAMPLE_COLUMN;
protected final String SCHEMA_COLUMN;
protected final String NAME_COLUMN;
protected final String DESCRIPTION_COLUMN;
protected final String SCOPES_COLUMN;
protected final String DESCRIPTION;
protected final String PRODUCES;
protected final String CONSUMES;
protected final String TAGS;
protected final String NO_CONTENT;
protected final String FLAGS_COLUMN;
protected final String FLAGS_REQUIRED;
protected final String FLAGS_OPTIONAL;
protected final String FLAGS_READ_ONLY;
protected Logger logger = LoggerFactory.getLogger(getClass());
protected Swagger2MarkupConverter.Context globalContext;
protected Swagger2MarkupExtensionRegistry extensionRegistry;
protected Swagger2MarkupConfig config;
protected MarkupDocBuilder markupDocBuilder;
protected Path outputPath;
MarkupDocumentBuilder(Swagger2MarkupConverter.Context globalContext, Swagger2MarkupExtensionRegistry extensionRegistry, Path outputPath) {
this.globalContext = globalContext;
this.extensionRegistry = extensionRegistry;
this.config = globalContext.getConfig();
this.outputPath = outputPath;
this.markupDocBuilder = MarkupDocBuilders.documentBuilder(config.getMarkupLanguage(), config.getLineSeparator()).withAnchorPrefix(config.getAnchorPrefix());
ResourceBundle labels = ResourceBundle.getBundle("io/github/swagger2markup/lang/labels", config.getOutputLanguage().toLocale());
DEFAULT_COLUMN = labels.getString("default_column");
EXAMPLE_COLUMN = labels.getString("example_column");
FLAGS_COLUMN = labels.getString("flags.column");
FLAGS_REQUIRED = labels.getString("flags.required");
FLAGS_OPTIONAL = labels.getString("flags.optional");
FLAGS_READ_ONLY = labels.getString("flags.read_only");
SCHEMA_COLUMN = labels.getString("schema_column");
NAME_COLUMN = labels.getString("name_column");
DESCRIPTION_COLUMN = labels.getString("description_column");
SCOPES_COLUMN = labels.getString("scopes_column");
DESCRIPTION = DESCRIPTION_COLUMN;
PRODUCES = labels.getString("produces");
CONSUMES = labels.getString("consumes");
TAGS = labels.getString("tags");
NO_CONTENT = labels.getString("no_content");
}
/**
* Builds the MarkupDocument.
*
* @return the built MarkupDocument
* @throws IOException if the files to include are not readable
*/
public abstract MarkupDocument build() throws IOException;
/**
* Returns a RefType to a new inlined type named with {@code name} and {@code uniqueName}.<br>
* The returned RefType point to the new inlined type which is added to the {@code inlineDefinitions} collection.<br>
* The function is recursive and support collections (ArrayType and MapType).<br>
* The function is transparent : {@code type} is returned as-is if type is not inlinable or if !config.isInlineSchemaEnabled().<br>
*
* @param type type to inline
* @param name name of the created inline ObjectType
* @param uniqueName unique name of the created inline ObjectType
* @param inlineDefinitions a non null collection of inline ObjectType
* @return the type referencing the newly created inline ObjectType. Can be a RefType, an ArrayType or a MapType
*/
protected Type createInlineType(Type type, String name, String uniqueName, List<ObjectType> inlineDefinitions) {
if (!config.isInlineSchemaEnabled())
return type;
if (type instanceof ObjectType) {
return createInlineObjectType(type, name, uniqueName, inlineDefinitions);
} else if (type instanceof ArrayType) {
ArrayType arrayType = (ArrayType)type;
arrayType.setOfType(createInlineType(arrayType.getOfType(), name, uniqueName, inlineDefinitions));
return arrayType;
} else if (type instanceof MapType) {
MapType mapType = (MapType)type;
if (mapType.getValueType() instanceof ObjectType)
mapType.setValueType(createInlineType(mapType.getValueType(), name, uniqueName, inlineDefinitions));
return mapType;
} else {
return type;
}
}
protected Type createInlineObjectType(Type type, String name, String uniqueName, List<ObjectType> inlineDefinitions) {
if (type instanceof ObjectType) {
ObjectType objectType = (ObjectType)type;
if (MapUtils.isNotEmpty(objectType.getProperties())) {
if (objectType.getName() == null) {
objectType.setName(name);
objectType.setUniqueName(uniqueName);
}
inlineDefinitions.add(objectType);
return new RefType(objectType);
} else
return type;
} else
return type;
}
/**
* Build a generic property table
*
* @param properties properties to display
* @param uniquePrefix unique prefix to prepend to inline object names to enforce unicity
* @param definitionDocumentResolver definition document resolver to apply to property type cross-reference
* @param docBuilder the docbuilder do use for output
* @return a list of inline schemas referenced by some properties, for later display
*/
protected List<ObjectType> buildPropertiesTable(Map<String, Property> properties, String uniquePrefix, DefinitionDocumentResolver definitionDocumentResolver, MarkupDocBuilder docBuilder) {
List<ObjectType> inlineDefinitions = new ArrayList<>();
List<List<String>> cells = new ArrayList<>();
List<MarkupTableColumn> cols = Arrays.asList(
new MarkupTableColumn(NAME_COLUMN).withWidthRatio(3).withHeaderColumn(false).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^3"),
new MarkupTableColumn(DESCRIPTION_COLUMN).withWidthRatio(11).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^11"),
new MarkupTableColumn(SCHEMA_COLUMN).withWidthRatio(4).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^4"));
if (MapUtils.isNotEmpty(properties)) {
Set<String> propertyNames = toKeySet(properties, config.getPropertyOrdering());
for (String propertyName : propertyNames) {
Property property = properties.get(propertyName);
Type propertyType = PropertyUtils.getType(property, definitionDocumentResolver);
propertyType = createInlineType(propertyType, propertyName, uniquePrefix + " " + propertyName, inlineDefinitions);
Object example = PropertyUtils.getExample(config.isGeneratedExamplesEnabled(), property, markupDocBuilder);
Object defaultValue = PropertyUtils.getDefaultValue(property);
MarkupDocBuilder propertyNameContent = copyMarkupDocBuilder();
propertyNameContent.boldTextLine(propertyName, true);
if (BooleanUtils.isTrue(property.getRequired()))
propertyNameContent.italicText(FLAGS_REQUIRED.toLowerCase());
else
propertyNameContent.italicText(FLAGS_OPTIONAL.toLowerCase());
if (BooleanUtils.isTrue(property.getReadOnly())) {
propertyNameContent.newLine(true);
propertyNameContent.italicText(FLAGS_READ_ONLY.toLowerCase());
}
MarkupDocBuilder descriptionContent = copyMarkupDocBuilder();
String description = defaultString(swaggerMarkupDescription(property.getDescription()));
if (isNotBlank(description))
descriptionContent.text(description);
if(defaultValue != null){
if (isNotBlank(description))
descriptionContent.newLine(true);
descriptionContent.boldText(DEFAULT_COLUMN).text(COLON).literalText(Json.pretty(defaultValue));
}
if (example != null) {
if (isNotBlank(description) || defaultValue != null)
descriptionContent.newLine(true);
descriptionContent.boldText(EXAMPLE_COLUMN).text(COLON).literalText(Json.pretty(example));
}
List<String> content = Arrays.asList(
propertyNameContent.toString(),
descriptionContent.toString(),
propertyType.displaySchema(docBuilder)
);
cells.add(content);
}
docBuilder.tableWithColumnSpecs(cols, cells);
} else {
docBuilder.textLine(NO_CONTENT);
}
return inlineDefinitions;
}
protected MarkupDocBuilder copyMarkupDocBuilder() {
return markupDocBuilder.copy(false);
}
protected String boldText(String text) {
return copyMarkupDocBuilder().boldText(text).toString();
}
protected String italicText(String text) {
return copyMarkupDocBuilder().italicText(text).toString();
}
protected String literalText(String text) {
return copyMarkupDocBuilder().literalText(text).toString();
}
/**
* Returns converted markup text from Swagger.
*
* @param markupText text to convert, or null
* @return converted markup text, or null if {@code markupText} == null
*/
protected String swaggerMarkupDescription(String markupText) {
if (markupText == null)
return null;
return copyMarkupDocBuilder().importMarkup(new StringReader(markupText), globalContext.getConfig().getSwaggerMarkupLanguage()).toString().trim();
}
protected void buildDescriptionParagraph(String description, MarkupDocBuilder docBuilder) {
if (isNotBlank(description)) {
docBuilder.paragraph(swaggerMarkupDescription(description));
}
}
/**
* Default {@code DefinitionDocumentResolver} functor
*/
class DefinitionDocumentResolverDefault implements DefinitionDocumentResolver {
public DefinitionDocumentResolverDefault() {
}
public String apply(String definitionName) {
if (!config.isInterDocumentCrossReferencesEnabled() || outputPath == null)
return null;
else if (config.isSeparatedDefinitionsEnabled())
return defaultString(config.getInterDocumentCrossReferencesPrefix()) + new File(config.getSeparatedDefinitionsFolder(), markupDocBuilder.addFileExtension(IOUtils.normalizeName(definitionName))).getPath();
else
return defaultString(config.getInterDocumentCrossReferencesPrefix()) + markupDocBuilder.addFileExtension(config.getDefinitionsDocument());
}
}
}

View File

@@ -1,224 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.document.builder;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.Swagger2MarkupExtensionRegistry;
import io.github.swagger2markup.internal.document.MarkupDocument;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.spi.OverviewDocumentExtension;
import io.swagger.models.*;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import static io.github.swagger2markup.spi.OverviewDocumentExtension.Context;
import static io.github.swagger2markup.spi.OverviewDocumentExtension.Position;
import static org.apache.commons.collections4.CollectionUtils.isNotEmpty;
import static org.apache.commons.lang3.StringUtils.*;
public class OverviewDocumentBuilder extends MarkupDocumentBuilder {
private static final String OVERVIEW_ANCHOR = "overview";
private final String OVERVIEW;
private final String CURRENT_VERSION;
private final String VERSION;
private final String CONTACT_INFORMATION;
private final String CONTACT_NAME;
private final String CONTACT_EMAIL;
private final String LICENSE_INFORMATION;
private final String LICENSE;
private final String LICENSE_URL;
private final String TERMS_OF_SERVICE;
private final String URI_SCHEME;
private final String HOST;
private final String BASE_PATH;
private final String SCHEMES;
public OverviewDocumentBuilder(Swagger2MarkupConverter.Context context, Swagger2MarkupExtensionRegistry extensionRegistry, Path outputPath){
super(context, extensionRegistry, outputPath);
ResourceBundle labels = ResourceBundle.getBundle("io/github/swagger2markup/lang/labels", config.getOutputLanguage().toLocale());
OVERVIEW = labels.getString("overview");
CURRENT_VERSION = labels.getString("current_version");
VERSION = labels.getString("version");
CONTACT_INFORMATION = labels.getString("contact_information");
CONTACT_NAME = labels.getString("contact_name");
CONTACT_EMAIL = labels.getString("contact_email");
LICENSE_INFORMATION = labels.getString("license_information");
LICENSE = labels.getString("license");
LICENSE_URL = labels.getString("license_url");
TERMS_OF_SERVICE = labels.getString("terms_of_service");
URI_SCHEME = labels.getString("uri_scheme");
HOST = labels.getString("host");
BASE_PATH = labels.getString("base_path");
SCHEMES = labels.getString("schemes");
}
/**
* Builds the overview MarkupDocument.
*
* @return the overview MarkupDocument
*/
@Override
public MarkupDocument build(){
Swagger swagger = globalContext.getSwagger();
Info info = swagger.getInfo();
buildDocumentTitle(info.getTitle());
applyOverviewDocumentExtension(new Context(Position.DOCUMENT_BEFORE, this.markupDocBuilder));
buildOverviewTitle(OVERVIEW);
applyOverviewDocumentExtension(new Context(Position.DOCUMENT_BEGIN, this.markupDocBuilder));
buildDescriptionParagraph(info.getDescription(), this.markupDocBuilder);
buildVersionInfoSection(info.getVersion());
buildContactInfoSection(info.getContact());
buildLicenseInfoSection(info.getLicense(), info.getTermsOfService());
buildUriSchemeSection(swagger);
buildTagsSection(swagger.getTags());
buildConsumesSection(swagger.getConsumes());
buildProducesSection(swagger.getProduces());
applyOverviewDocumentExtension(new Context(Position.DOCUMENT_END, this.markupDocBuilder));
applyOverviewDocumentExtension(new Context(Position.DOCUMENT_AFTER, this.markupDocBuilder));
return new MarkupDocument(markupDocBuilder);
}
private void buildDocumentTitle(String title) {
this.markupDocBuilder.documentTitle(title);
}
private void buildOverviewTitle(String title) {
this.markupDocBuilder.sectionTitleWithAnchorLevel1(title, OVERVIEW_ANCHOR);
}
private void buildVersionInfoSection(String version) {
if(isNotBlank(version)){
this.markupDocBuilder.sectionTitleLevel2(CURRENT_VERSION);
MarkupDocBuilder paragraph = copyMarkupDocBuilder();
paragraph.italicText(VERSION).textLine(COLON + version);
this.markupDocBuilder.paragraph(paragraph.toString(), true);
}
}
private void buildContactInfoSection(Contact contact) {
if(contact != null){
this.markupDocBuilder.sectionTitleLevel2(CONTACT_INFORMATION);
MarkupDocBuilder paragraph = copyMarkupDocBuilder();
if(isNotBlank(contact.getName())){
paragraph.italicText(CONTACT_NAME).textLine(COLON + contact.getName());
}
if(isNotBlank(contact.getEmail())){
paragraph.italicText(CONTACT_EMAIL).textLine(COLON + contact.getEmail());
}
this.markupDocBuilder.paragraph(paragraph.toString(), true);
}
}
private void buildLicenseInfoSection(License license, String termOfService) {
if (
(license != null && (isNotBlank(license.getName()) || isNotBlank(license.getUrl()))) ||
(isNotBlank(termOfService))
) {
this.markupDocBuilder.sectionTitleLevel2(LICENSE_INFORMATION);
MarkupDocBuilder paragraph = copyMarkupDocBuilder();
if (license != null && isNotBlank(license.getName())) {
paragraph.italicText(LICENSE).textLine(COLON + license.getName());
}
if (license != null && isNotBlank(license.getUrl())) {
paragraph.italicText(LICENSE_URL).textLine(COLON + license.getUrl());
}
if(isNotBlank(termOfService)){
paragraph.italicText(TERMS_OF_SERVICE).textLine(COLON + termOfService);
}
this.markupDocBuilder.paragraph(paragraph.toString(), true);
}
}
private void buildUriSchemeSection(Swagger swagger) {
if(isNotBlank(swagger.getHost()) || isNotBlank(swagger.getBasePath()) || isNotEmpty(swagger.getSchemes())) {
this.markupDocBuilder.sectionTitleLevel2(URI_SCHEME);
MarkupDocBuilder paragraph = copyMarkupDocBuilder();
if (isNotBlank(swagger.getHost())) {
paragraph.italicText(HOST).textLine(COLON + swagger.getHost());
}
if (isNotBlank(swagger.getBasePath())) {
paragraph.italicText(BASE_PATH).textLine(COLON + swagger.getBasePath());
}
if (isNotEmpty(swagger.getSchemes())) {
List<String> schemes = new ArrayList<>();
for (Scheme scheme : swagger.getSchemes()) {
schemes.add(scheme.toString());
}
paragraph.italicText(SCHEMES).textLine(COLON + join(schemes, ", "));
}
this.markupDocBuilder.paragraph(paragraph.toString(), true);
}
}
private void buildTagsSection(List<Tag> tags) {
if(isNotEmpty(tags)){
this.markupDocBuilder.sectionTitleLevel2(TAGS);
List<String> tagsList = new ArrayList<>();
for(Tag tag : tags){
String name = tag.getName();
String description = tag.getDescription();
if(isNoneBlank(description)){
tagsList.add(name + COLON + description);
}else{
tagsList.add(name);
}
}
this.markupDocBuilder.unorderedList(tagsList);
}
}
private void buildConsumesSection(List<String> consumes) {
if (isNotEmpty(consumes)) {
this.markupDocBuilder.sectionTitleLevel2(CONSUMES);
this.markupDocBuilder.newLine();
for (String consume : consumes) {
this.markupDocBuilder.unorderedListItem(literalText(consume));
}
this.markupDocBuilder.newLine();
}
}
private void buildProducesSection(List<String> produces) {
if (isNotEmpty(produces)) {
this.markupDocBuilder.sectionTitleLevel2(PRODUCES);
this.markupDocBuilder.newLine();
for (String produce : produces) {
this.markupDocBuilder.unorderedListItem(literalText(produce));
}
this.markupDocBuilder.newLine();
}
}
/**
* Apply extension context to all OverviewContentExtension
*
* @param context context
*/
private void applyOverviewDocumentExtension(Context context) {
for (OverviewDocumentExtension extension : extensionRegistry.getOverviewDocumentExtensions()) {
extension.apply(context);
}
}
}

View File

@@ -1,770 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.document.builder;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.Multimap;
import io.github.swagger2markup.GroupBy;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.Swagger2MarkupExtensionRegistry;
import io.github.swagger2markup.internal.document.MarkupDocument;
import io.github.swagger2markup.internal.type.ObjectType;
import io.github.swagger2markup.internal.type.Type;
import io.github.swagger2markup.internal.utils.ExamplesUtil;
import io.github.swagger2markup.internal.utils.ParameterUtils;
import io.github.swagger2markup.internal.utils.PropertyUtils;
import io.github.swagger2markup.internal.utils.TagUtils;
import io.github.swagger2markup.markup.builder.*;
import io.github.swagger2markup.model.PathOperation;
import io.github.swagger2markup.spi.PathsDocumentExtension;
import io.swagger.models.*;
import io.swagger.models.auth.SecuritySchemeDefinition;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.Property;
import io.swagger.util.Json;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.text.WordUtils;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.*;
import static io.github.swagger2markup.internal.utils.ListUtils.toSet;
import static io.github.swagger2markup.internal.utils.MapUtils.toKeySet;
import static io.github.swagger2markup.internal.utils.TagUtils.convertTagsListToMap;
import static io.github.swagger2markup.internal.utils.TagUtils.getTagDescription;
import static io.github.swagger2markup.spi.PathsDocumentExtension.Context;
import static io.github.swagger2markup.spi.PathsDocumentExtension.Position;
import static io.github.swagger2markup.utils.IOUtils.normalizeName;
import static org.apache.commons.lang3.StringUtils.defaultString;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
/**
* @author Robert Winkler
*/
public class PathsDocumentBuilder extends MarkupDocumentBuilder {
private final String RESPONSE;
private final String REQUEST;
private final String PATHS;
private final String RESOURCES;
private final String PARAMETERS;
private final String BODY_PARAMETER;
private final String RESPONSES;
private final String HEADERS_COLUMN;
private final String EXAMPLE_REQUEST;
private final String EXAMPLE_RESPONSE;
private final String SECURITY;
private final String TYPE_COLUMN;
private final String HTTP_CODE_COLUMN;
private final String DEPRECATED_OPERATION;
private final String UNKNOWN;
private static final String PATHS_ANCHOR = "paths";
public PathsDocumentBuilder(Swagger2MarkupConverter.Context globalContext, Swagger2MarkupExtensionRegistry extensionRegistry, java.nio.file.Path outputPath) {
super(globalContext, extensionRegistry, outputPath);
ResourceBundle labels = ResourceBundle.getBundle("io/github/swagger2markup/lang/labels", config.getOutputLanguage().toLocale());
RESPONSE = labels.getString("response");
REQUEST = labels.getString("request");
PATHS = labels.getString("paths");
RESOURCES = labels.getString("resources");
PARAMETERS = labels.getString("parameters");
BODY_PARAMETER = labels.getString("body_parameter");
RESPONSES = labels.getString("responses");
HEADERS_COLUMN = labels.getString("headers_column");
EXAMPLE_REQUEST = labels.getString("example_request");
EXAMPLE_RESPONSE = labels.getString("example_response");
SECURITY = labels.getString("security");
TYPE_COLUMN = labels.getString("type_column");
HTTP_CODE_COLUMN = labels.getString("http_code_column");
DEPRECATED_OPERATION = labels.getString("operation.deprecated");
UNKNOWN = labels.getString("unknown");
if (config.isGeneratedExamplesEnabled()) {
if (logger.isDebugEnabled()) {
logger.debug("Include examples is enabled.");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Include examples is disabled.");
}
}
if (config.isSeparatedOperationsEnabled()) {
if (logger.isDebugEnabled()) {
logger.debug("Create separated operation files is enabled.");
}
Validate.notNull(outputPath, "Output directory is required for separated operation files!");
} else {
if (logger.isDebugEnabled()) {
logger.debug("Create separated operation files is disabled.");
}
}
}
/**
* Builds the paths MarkupDocument.
*
* @return the paths MarkupDocument
*/
@Override
public MarkupDocument build() {
Map<String, Path> paths = globalContext.getSwagger().getPaths();
if (MapUtils.isNotEmpty(paths)) {
applyPathsDocumentExtension(new Context(Position.DOCUMENT_BEFORE, this.markupDocBuilder));
buildPathsTitle();
applyPathsDocumentExtension(new Context(Position.DOCUMENT_BEGIN, this.markupDocBuilder));
buildsPathsSection(paths);
applyPathsDocumentExtension(new Context(Position.DOCUMENT_END, this.markupDocBuilder));
applyPathsDocumentExtension(new Context(Position.DOCUMENT_AFTER, this.markupDocBuilder));
}
return new MarkupDocument(markupDocBuilder);
}
private void buildsPathsSection(Map<String, Path> paths) {
Set<PathOperation> pathOperations = toPathOperationsSet(paths);
if (CollectionUtils.isNotEmpty(pathOperations)) {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
for (PathOperation operation : pathOperations) {
buildOperation(operation);
}
} else {
Multimap<String, PathOperation> operationsGroupedByTag = TagUtils.groupOperationsByTag(pathOperations, config.getTagOrdering(), config.getOperationOrdering());
Map<String, Tag> tagsMap = convertTagsListToMap(globalContext.getSwagger().getTags());
for (String tagName : operationsGroupedByTag.keySet()) {
this.markupDocBuilder.sectionTitleWithAnchorLevel2(WordUtils.capitalize(tagName), tagName + "_resource");
Optional<String> tagDescription = getTagDescription(tagsMap, tagName);
if (tagDescription.isPresent()) {
this.markupDocBuilder.paragraph(tagDescription.get());
}
for (PathOperation operation : operationsGroupedByTag.get(tagName)) {
buildOperation(operation);
}
}
}
}
}
/**
* Builds the path title depending on the operationsGroupedBy configuration setting.
*/
private void buildPathsTitle() {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
buildPathsTitle(PATHS);
} else {
buildPathsTitle(RESOURCES);
}
}
/**
* Converts the Swagger paths into a list PathOperations.
*
* @param paths the Swagger paths
* @return the path operations
*/
private Set<PathOperation> toPathOperationsSet(Map<String, Path> paths) {
Set<PathOperation> pathOperations;
if (config.getOperationOrdering() != null) {
pathOperations = new TreeSet<>(config.getOperationOrdering());
} else {
pathOperations = new LinkedHashSet<>();
}
for (Map.Entry<String, Path> path : paths.entrySet()) {
Map<HttpMethod, Operation> operations = path.getValue().getOperationMap(); // TODO AS_IS does not work because of https://github.com/swagger-api/swagger-core/issues/1696
if (MapUtils.isNotEmpty(operations)) {
for (Map.Entry<HttpMethod, Operation> operation : operations.entrySet()) {
pathOperations.add(new PathOperation(operation.getKey(), path.getKey(), operation.getValue()));
}
}
}
return pathOperations;
}
private void buildPathsTitle(String title) {
this.markupDocBuilder.sectionTitleWithAnchorLevel1(title, PATHS_ANCHOR);
}
/**
* Apply extension context to all OperationsContentExtension.
*
* @param context context
*/
private void applyPathsDocumentExtension(Context context) {
for (PathsDocumentExtension extension : extensionRegistry.getPathsDocumentExtensions()) {
extension.apply(context);
}
}
/**
* Create the operation filename depending on the generation mode
*
* @param operation operation
* @return operation filename
*/
private String resolveOperationDocument(PathOperation operation) {
if (config.isSeparatedOperationsEnabled())
return new File(config.getSeparatedOperationsFolder(), this.markupDocBuilder.addFileExtension(normalizeName(operation.getId()))).getPath();
else
return this.markupDocBuilder.addFileExtension(config.getPathsDocument());
}
/**
* Builds a path operation depending on generation mode.
*
* @param operation operation
*/
private void buildOperation(PathOperation operation) {
if (config.isSeparatedOperationsEnabled()) {
MarkupDocBuilder pathDocBuilder = copyMarkupDocBuilder();
buildOperation(operation, pathDocBuilder);
java.nio.file.Path operationFile = outputPath.resolve(resolveOperationDocument(operation));
pathDocBuilder.writeToFileWithoutExtension(operationFile, StandardCharsets.UTF_8);
if (logger.isInfoEnabled()) {
logger.info("Separate operation file produced : '{}'", operationFile);
}
buildOperationRef(operation, this.markupDocBuilder);
} else {
buildOperation(operation, this.markupDocBuilder);
}
if (logger.isInfoEnabled()) {
logger.info("Operation processed : '{}' (normalized id = '{}')", operation, normalizeName(operation.getId()));
}
}
/**
* Builds a path operation.
*
* @param operation the Swagger Operation
* @param docBuilder the docbuilder do use for output
*/
private void buildOperation(PathOperation operation, MarkupDocBuilder docBuilder) {
if (operation != null) {
applyPathsDocumentExtension(new Context(Position.OPERATION_BEFORE, docBuilder, operation));
buildDeprecatedSection(operation, docBuilder);
buildOperationTitle(operation, docBuilder);
applyPathsDocumentExtension(new Context(Position.OPERATION_BEGIN, docBuilder, operation));
buildDescriptionSection(operation, docBuilder);
inlineDefinitions(buildParametersSection(operation, docBuilder), operation.getPath() + " " + operation.getMethod(), docBuilder);
inlineDefinitions(buildBodyParameterSection(operation, docBuilder), operation.getPath() + " " + operation.getMethod(), docBuilder);
inlineDefinitions(buildResponsesSection(operation, docBuilder), operation.getPath() + " " + operation.getMethod(), docBuilder);
buildConsumesSection(operation, docBuilder);
buildProducesSection(operation, docBuilder);
buildTagsSection(operation, docBuilder);
buildSecuritySchemeSection(operation, docBuilder);
buildExamplesSection(operation, docBuilder);
applyPathsDocumentExtension(new Context(Position.OPERATION_END, docBuilder, operation));
applyPathsDocumentExtension(new Context(Position.OPERATION_AFTER, docBuilder, operation));
}
}
/**
* Builds a cross-reference to a separated operation file
*
* @param operation the Swagger Operation
* @param docBuilder the docbuilder do use for output
*/
private void buildOperationRef(PathOperation operation, MarkupDocBuilder docBuilder) {
String document;
if (!config.isInterDocumentCrossReferencesEnabled() || outputPath == null)
document = null;
else if (config.isSeparatedOperationsEnabled())
document = defaultString(config.getInterDocumentCrossReferencesPrefix()) + resolveOperationDocument(operation);
else
document = defaultString(config.getInterDocumentCrossReferencesPrefix()) + resolveOperationDocument(operation);
buildOperationTitle(copyMarkupDocBuilder().crossReference(document, operation.getId(), operation.getTitle()).toString(), "ref-" + operation.getId(), docBuilder);
}
/**
* Builds a warning if method is deprecated.
*
* @param operation the Swagger Operation
* @param docBuilder the docbuilder do use for output
*/
private void buildDeprecatedSection(PathOperation operation, MarkupDocBuilder docBuilder) {
Boolean deprecated = operation.getOperation().isDeprecated();
if (deprecated != null && deprecated) {
docBuilder.block(DEPRECATED_OPERATION, MarkupBlockStyle.EXAMPLE, null, MarkupAdmonition.CAUTION);
}
}
/**
* Adds the operation title to the document. If the operation has a summary, the title is the summary.
* Otherwise the title is the method of the operation and the URL of the operation.
*
* @param operation the Swagger Operation
* @param docBuilder the docbuilder do use for output
*/
private void buildOperationTitle(PathOperation operation, MarkupDocBuilder docBuilder) {
buildOperationTitle(operation.getTitle(), operation.getId(), docBuilder);
if (operation.getTitle().equals(operation.getOperation().getSummary())) {
docBuilder.block(operation.getMethod() + " " + operation.getPath(), MarkupBlockStyle.LITERAL);
}
}
/**
* Adds a operation title to the document.
*
* @param title the operation title
* @param anchor optional anchor (null => auto-generate from title)
* @param docBuilder the MarkupDocBuilder to use
*/
private void buildOperationTitle(String title, String anchor, MarkupDocBuilder docBuilder) {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
docBuilder.sectionTitleWithAnchorLevel2(title, anchor);
} else {
docBuilder.sectionTitleWithAnchorLevel3(title, anchor);
}
}
/**
* Adds a operation section title to the document.
*
* @param title the section title
* @param docBuilder the MarkupDocBuilder to use
*/
private void buildSectionTitle(String title, MarkupDocBuilder docBuilder) {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
docBuilder.sectionTitleLevel3(title);
} else {
docBuilder.sectionTitleLevel4(title);
}
}
/**
* Adds a example title to the document.
*
* @param title the section title
* @param docBuilder the MarkupDocBuilder to use
*/
private void buildExampleTitle(String title, MarkupDocBuilder docBuilder) {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
docBuilder.sectionTitleLevel4(title);
} else {
docBuilder.sectionTitleLevel5(title);
}
}
/**
* Adds a operation description to the document.
*
* @param operation the Swagger Operation
* @param docBuilder the docbuilder do use for output
*/
private void buildDescriptionSection(PathOperation operation, MarkupDocBuilder docBuilder) {
MarkupDocBuilder descriptionBuilder = copyMarkupDocBuilder();
applyPathsDocumentExtension(new Context(Position.OPERATION_DESCRIPTION_BEGIN, descriptionBuilder, operation));
buildDescriptionParagraph(operation.getOperation().getDescription(), descriptionBuilder);
applyPathsDocumentExtension(new Context(Position.OPERATION_DESCRIPTION_END, descriptionBuilder, operation));
String descriptionContent = descriptionBuilder.toString();
applyPathsDocumentExtension(new Context(Position.OPERATION_DESCRIPTION_BEFORE, docBuilder, operation));
if (isNotBlank(descriptionContent)) {
buildSectionTitle(DESCRIPTION, docBuilder);
docBuilder.text(descriptionContent);
}
applyPathsDocumentExtension(new Context(Position.OPERATION_DESCRIPTION_AFTER, docBuilder, operation));
}
/**
* Filter parameters to display in parameters section
*
* @param parameter parameter to filter
* @return true if parameter can be displayed
*/
private boolean filterParameter(Parameter parameter) {
return (!config.isFlatBodyEnabled() || !StringUtils.equals(parameter.getIn(), "body"));
}
private List<ObjectType> buildParametersSection(PathOperation operation, MarkupDocBuilder docBuilder) {
List<Parameter> parameters = operation.getOperation().getParameters();
if (config.getParameterOrdering() != null)
Collections.sort(parameters, config.getParameterOrdering());
List<ObjectType> inlineDefinitions = new ArrayList<>();
boolean hasParameters = false;
if (CollectionUtils.isNotEmpty(parameters)) {
for (Parameter p : parameters) {
if (filterParameter(p)) {
hasParameters = true;
break;
}
}
}
MarkupDocBuilder parametersBuilder = copyMarkupDocBuilder();
applyPathsDocumentExtension(new Context(Position.OPERATION_DESCRIPTION_BEGIN, parametersBuilder, operation));
if (hasParameters) {
List<List<String>> cells = new ArrayList<>();
List<MarkupTableColumn> cols = Arrays.asList(
new MarkupTableColumn(TYPE_COLUMN).withWidthRatio(1).withHeaderColumn(false).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1"),
new MarkupTableColumn(NAME_COLUMN).withWidthRatio(3).withHeaderColumn(false).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^3"),
new MarkupTableColumn(DESCRIPTION_COLUMN).withWidthRatio(10).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^10"),
new MarkupTableColumn(SCHEMA_COLUMN).withWidthRatio(4).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^4"),
new MarkupTableColumn(DEFAULT_COLUMN).withWidthRatio(2).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^2"));
for (Parameter parameter : parameters) {
if (filterParameter(parameter)) {
Type type = ParameterUtils.getType(parameter, globalContext.getSwagger().getDefinitions(), new DefinitionDocumentResolverFromOperation());
type = createInlineType(type, parameter.getName(), operation.getId() + " " + parameter.getName(), inlineDefinitions);
String parameterType = WordUtils.capitalize(parameter.getIn());
MarkupDocBuilder parameterNameContent = copyMarkupDocBuilder();
parameterNameContent.boldTextLine(parameter.getName(), true);
if (parameter.getRequired())
parameterNameContent.italicText(FLAGS_REQUIRED.toLowerCase());
else
parameterNameContent.italicText(FLAGS_OPTIONAL.toLowerCase());
Object defaultValue = ParameterUtils.getDefaultValue(parameter);
List<String> content = Arrays.asList(
boldText(parameterType),
parameterNameContent.toString(),
defaultString(swaggerMarkupDescription(parameter.getDescription())),
type.displaySchema(markupDocBuilder),
defaultValue != null ? literalText(Json.pretty(defaultValue)) : "");
cells.add(content);
}
}
parametersBuilder.tableWithColumnSpecs(cols, cells);
}
applyPathsDocumentExtension(new Context(Position.OPERATION_DESCRIPTION_END, parametersBuilder, operation));
String parametersContent = parametersBuilder.toString();
applyPathsDocumentExtension(new Context(Position.OPERATION_PARAMETERS_BEFORE, docBuilder, operation));
if (isNotBlank(parametersContent)) {
buildSectionTitle(PARAMETERS, docBuilder);
docBuilder.text(parametersContent);
}
applyPathsDocumentExtension(new Context(Position.OPERATION_PARAMETERS_AFTER, docBuilder, operation));
return inlineDefinitions;
}
/**
* Builds the body parameter section, if {@code Swagger2MarkupConfig.isIsolatedBody()} is true
*
* @param operation the Swagger Operation
* @param docBuilder the docbuilder do use for output
* @return a list of inlined types.
*/
private List<ObjectType> buildBodyParameterSection(PathOperation operation, MarkupDocBuilder docBuilder) {
List<ObjectType> inlineDefinitions = new ArrayList<>();
if (config.isFlatBodyEnabled()) {
List<Parameter> parameters = operation.getOperation().getParameters();
if (CollectionUtils.isNotEmpty(parameters)) {
for (Parameter parameter : parameters) {
if (StringUtils.equals(parameter.getIn(), "body")) {
Type type = ParameterUtils.getType(parameter, globalContext.getSwagger().getDefinitions(), new DefinitionDocumentResolverFromOperation());
if (!(type instanceof ObjectType)) {
type = createInlineType(type, parameter.getName(), operation.getId() + " " + parameter.getName(), inlineDefinitions);
}
buildSectionTitle(BODY_PARAMETER, docBuilder);
if (isNotBlank(parameter.getDescription())) {
buildDescriptionParagraph(parameter.getDescription(), docBuilder);
}
MarkupDocBuilder typeInfos = copyMarkupDocBuilder();
typeInfos.italicText(NAME_COLUMN).textLine(COLON + parameter.getName());
typeInfos.italicText(FLAGS_COLUMN).textLine(COLON + (BooleanUtils.isTrue(parameter.getRequired()) ? FLAGS_REQUIRED.toLowerCase() : FLAGS_OPTIONAL.toLowerCase()));
if (!(type instanceof ObjectType)) {
typeInfos.italicText(TYPE_COLUMN).textLine(COLON + type.displaySchema(docBuilder));
}
docBuilder.paragraph(typeInfos.toString(), true);
if (type instanceof ObjectType) {
inlineDefinitions.addAll(buildPropertiesTable(((ObjectType) type).getProperties(), operation.getId(), new DefinitionDocumentResolverFromOperation(), docBuilder));
}
}
}
}
}
return inlineDefinitions;
}
private void buildConsumesSection(PathOperation operation, MarkupDocBuilder docBuilder) {
List<String> consumes = operation.getOperation().getConsumes();
if (CollectionUtils.isNotEmpty(consumes)) {
buildSectionTitle(CONSUMES, docBuilder);
docBuilder.newLine();
for (String consume : consumes) {
docBuilder.unorderedListItem(literalText(consume));
}
docBuilder.newLine();
}
}
private void buildProducesSection(PathOperation operation, MarkupDocBuilder docBuilder) {
List<String> produces = operation.getOperation().getProduces();
if (CollectionUtils.isNotEmpty(produces)) {
buildSectionTitle(PRODUCES, docBuilder);
docBuilder.newLine();
for (String produce : produces) {
docBuilder.unorderedListItem(literalText(produce));
}
docBuilder.newLine();
}
}
private void buildTagsSection(PathOperation operation, MarkupDocBuilder docBuilder) {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
List<String> tags = operation.getOperation().getTags();
if (CollectionUtils.isNotEmpty(tags)) {
buildSectionTitle(TAGS, docBuilder);
Set<String> tagsSet = toSet(tags, config.getTagOrdering());
docBuilder.unorderedList(new ArrayList<>(tagsSet));
}
}
}
/**
* Builds the example section of a Swagger Operation.
*
* @param operation the Swagger Operation
* @param docBuilder the docbuilder do use for output
*/
private void buildExamplesSection(PathOperation operation, MarkupDocBuilder docBuilder) {
Map<String, Object> generatedRequestExampleMap = ExamplesUtil.generateRequestExampleMap(config.isGeneratedExamplesEnabled(), operation, globalContext.getSwagger().getDefinitions(), markupDocBuilder);
Map<String, Object> generatedResponseExampleMap = ExamplesUtil.generateResponseExampleMap(config.isGeneratedExamplesEnabled(), operation.getOperation(), globalContext.getSwagger().getDefinitions(), markupDocBuilder);
exampleMap(generatedRequestExampleMap, EXAMPLE_REQUEST, REQUEST, docBuilder);
exampleMap(generatedResponseExampleMap, EXAMPLE_RESPONSE, RESPONSE, docBuilder);
}
private void exampleMap(Map<String, Object> exampleMap, String operationSectionTitle, String sectionTitle, MarkupDocBuilder docBuilder) {
if (exampleMap.size() > 0) {
buildSectionTitle(operationSectionTitle, docBuilder);
for (Map.Entry<String, Object> entry : exampleMap.entrySet()) {
buildExampleTitle(sectionTitle + " " + entry.getKey(), docBuilder);
docBuilder.listingBlock(Json.pretty(entry.getValue()), "json");
}
}
}
/**
* Builds the security section of a Swagger Operation.
*
* @param operation the Swagger Operation
* @param docBuilder the MarkupDocBuilder document builder
*/
private void buildSecuritySchemeSection(PathOperation operation, MarkupDocBuilder docBuilder) {
List<Map<String, List<String>>> securitySchemes = operation.getOperation().getSecurity();
MarkupDocBuilder securityBuilder = copyMarkupDocBuilder();
applyPathsDocumentExtension(new Context(Position.OPERATION_SECURITY_BEGIN, securityBuilder, operation));
if (CollectionUtils.isNotEmpty(securitySchemes)) {
Map<String, SecuritySchemeDefinition> securityDefinitions = globalContext.getSwagger().getSecurityDefinitions();
List<List<String>> cells = new ArrayList<>();
List<MarkupTableColumn> cols = Arrays.asList(
new MarkupTableColumn(TYPE_COLUMN).withWidthRatio(3).withHeaderColumn(false).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^3"),
new MarkupTableColumn(NAME_COLUMN).withWidthRatio(4).withHeaderColumn(false).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^4"),
new MarkupTableColumn(SCOPES_COLUMN).withWidthRatio(13).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^13"));
for (Map<String, List<String>> securityScheme : securitySchemes) {
for (Map.Entry<String, List<String>> securityEntry : securityScheme.entrySet()) {
String securityKey = securityEntry.getKey();
String type = UNKNOWN;
if (securityDefinitions != null && securityDefinitions.containsKey(securityKey)) {
type = securityDefinitions.get(securityKey).getType();
}
List<String> content = Arrays.asList(boldText(type), boldText(copyMarkupDocBuilder().crossReference(securityDocumentResolver(), securityKey, securityKey).toString()),
Joiner.on(",").join(securityEntry.getValue()));
cells.add(content);
}
}
securityBuilder.tableWithColumnSpecs(cols, cells);
}
applyPathsDocumentExtension(new Context(Position.OPERATION_SECURITY_END, securityBuilder, operation));
String securityContent = securityBuilder.toString();
applyPathsDocumentExtension(new Context(Position.OPERATION_SECURITY_BEFORE, docBuilder, operation));
if (isNotBlank(securityContent)) {
buildSectionTitle(SECURITY, docBuilder);
docBuilder.text(securityContent);
}
applyPathsDocumentExtension(new Context(Position.OPERATION_SECURITY_AFTER, docBuilder, operation));
}
/**
* Resolve Security document for use in cross-references.
*
* @return document or null if cross-reference is not inter-document
*/
private String securityDocumentResolver() {
if (!config.isInterDocumentCrossReferencesEnabled() || outputPath == null)
return null;
else
return defaultString(config.getInterDocumentCrossReferencesPrefix()) + markupDocBuilder.addFileExtension(config.getSecurityDocument());
}
private List<ObjectType> buildResponsesSection(PathOperation operation, MarkupDocBuilder docBuilder) {
Map<String, Response> responses = operation.getOperation().getResponses();
List<ObjectType> inlineDefinitions = new ArrayList<>();
MarkupDocBuilder responsesBuilder = copyMarkupDocBuilder();
applyPathsDocumentExtension(new Context(Position.OPERATION_RESPONSES_BEGIN, responsesBuilder, operation));
if (MapUtils.isNotEmpty(responses)) {
List<MarkupTableColumn> responseCols = Arrays.asList(
new MarkupTableColumn(HTTP_CODE_COLUMN).withWidthRatio(1).withHeaderColumn(false).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1"),
new MarkupTableColumn(DESCRIPTION_COLUMN).withWidthRatio(15).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^15"),
new MarkupTableColumn(SCHEMA_COLUMN).withWidthRatio(4).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^4"));
List<List<String>> cells = new ArrayList<>();
Set<String> responseNames = toKeySet(responses, config.getResponseOrdering());
for (String responseName : responseNames) {
Response response = responses.get(responseName);
String schemaContent = NO_CONTENT;
if (response.getSchema() != null) {
Property property = response.getSchema();
Type type = PropertyUtils.getType(property, new DefinitionDocumentResolverFromOperation());
type = createInlineType(type, RESPONSE + " " + responseName, operation.getId() + " " + RESPONSE + " " + responseName, inlineDefinitions);
schemaContent = type.displaySchema(markupDocBuilder);
}
MarkupDocBuilder descriptionBuilder = copyMarkupDocBuilder();
descriptionBuilder.text(defaultString(swaggerMarkupDescription(response.getDescription())));
Map<String, Property> headers = response.getHeaders();
if (MapUtils.isNotEmpty(headers)) {
descriptionBuilder.newLine(true).boldText(HEADERS_COLUMN).text(COLON);
for (Map.Entry<String, Property> header : headers.entrySet()) {
descriptionBuilder.newLine(true);
Property headerProperty = header.getValue();
Type propertyType = PropertyUtils.getType(headerProperty, null);
String headerDescription = defaultString(swaggerMarkupDescription(headerProperty.getDescription()));
Object defaultValue = PropertyUtils.getDefaultValue(headerProperty);
descriptionBuilder
.literalText(header.getKey())
.text(String.format(" (%s)", propertyType.displaySchema(markupDocBuilder)));
if (isNotBlank(headerDescription) || defaultValue != null) {
descriptionBuilder.text(COLON);
if (isNotBlank(headerDescription) && !headerDescription.endsWith("."))
headerDescription += ".";
descriptionBuilder.text(headerDescription);
if (defaultValue != null) {
descriptionBuilder.text(" ").boldText(DEFAULT_COLUMN).text(COLON).literalText(Json.pretty(defaultValue));
}
}
}
}
cells.add(Arrays.asList(boldText(responseName), descriptionBuilder.toString(), schemaContent));
}
responsesBuilder.tableWithColumnSpecs(responseCols, cells);
}
applyPathsDocumentExtension(new Context(Position.OPERATION_RESPONSES_END, responsesBuilder, operation));
String responsesContent = responsesBuilder.toString();
applyPathsDocumentExtension(new Context(Position.OPERATION_RESPONSES_BEFORE, docBuilder, operation));
if (isNotBlank(responsesContent)) {
buildSectionTitle(RESPONSES, docBuilder);
docBuilder.text(responsesContent);
}
applyPathsDocumentExtension(new Context(Position.OPERATION_RESPONSES_AFTER, docBuilder, operation));
return inlineDefinitions;
}
/**
* Builds the title of an inline schema.
* Inline definitions should never been referenced in TOC because they have no real existence, so they are just text.
*
* @param title inline schema title
* @param anchor inline schema anchor
* @param docBuilder the docbuilder do use for output
*/
private void addInlineDefinitionTitle(String title, String anchor, MarkupDocBuilder docBuilder) {
docBuilder.anchor(anchor);
docBuilder.newLine();
docBuilder.boldTextLine(title);
}
/**
* Builds inline schema definitions
*
* @param definitions all inline definitions to display
* @param uniquePrefix unique prefix to prepend to inline object names to enforce unicity
* @param docBuilder the docbuilder do use for output
*/
private void inlineDefinitions(List<ObjectType> definitions, String uniquePrefix, MarkupDocBuilder docBuilder) {
if (CollectionUtils.isNotEmpty(definitions)) {
for (ObjectType definition : definitions) {
addInlineDefinitionTitle(definition.getName(), definition.getUniqueName(), docBuilder);
List<ObjectType> localDefinitions = buildPropertiesTable(definition.getProperties(), uniquePrefix, new DefinitionDocumentResolverFromOperation(), docBuilder);
for (ObjectType localDefinition : localDefinitions)
inlineDefinitions(Collections.singletonList(localDefinition), localDefinition.getUniqueName(), docBuilder);
}
}
}
/**
* Overrides definition document resolver functor for inter-document cross-references from operations files.
* This implementation adapt the relative paths to definitions files
*/
class DefinitionDocumentResolverFromOperation extends DefinitionDocumentResolverDefault {
public DefinitionDocumentResolverFromOperation() {
}
public String apply(String definitionName) {
String defaultResolver = super.apply(definitionName);
if (defaultResolver != null && config.isSeparatedOperationsEnabled())
return defaultString(config.getInterDocumentCrossReferencesPrefix()) + new File("..", defaultResolver).getPath();
else
return defaultResolver;
}
}
}

View File

@@ -1,155 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.document.builder;
import com.google.common.collect.Ordering;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.Swagger2MarkupExtensionRegistry;
import io.github.swagger2markup.internal.document.MarkupDocument;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.markup.builder.MarkupLanguage;
import io.github.swagger2markup.markup.builder.MarkupTableColumn;
import io.github.swagger2markup.spi.SecurityDocumentExtension;
import io.swagger.models.auth.ApiKeyAuthDefinition;
import io.swagger.models.auth.OAuth2Definition;
import io.swagger.models.auth.SecuritySchemeDefinition;
import org.apache.commons.collections4.MapUtils;
import java.nio.file.Path;
import java.util.*;
import static io.github.swagger2markup.internal.utils.MapUtils.toKeySet;
import static io.github.swagger2markup.spi.SecurityDocumentExtension.Context;
import static io.github.swagger2markup.spi.SecurityDocumentExtension.Position;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
/**
* @author Robert Winkler
*/
public class SecurityDocumentBuilder extends MarkupDocumentBuilder {
private static final String SECURITY_ANCHOR = "securityScheme";
private final String SECURITY;
private final String TYPE;
private final String NAME;
private final String IN;
private final String FLOW;
private final String AUTHORIZATION_URL;
private final String TOKEN_URL;
public SecurityDocumentBuilder(Swagger2MarkupConverter.Context context, Swagger2MarkupExtensionRegistry extensionRegistry, Path outputPath) {
super(context, extensionRegistry, outputPath);
ResourceBundle labels = ResourceBundle.getBundle("io/github/swagger2markup/lang/labels", config.getOutputLanguage().toLocale());
SECURITY = labels.getString("security");
TYPE = labels.getString("security_type");
NAME = labels.getString("security_name");
IN = labels.getString("security_in");
FLOW = labels.getString("security_flow");
AUTHORIZATION_URL = labels.getString("security_authorizationUrl");
TOKEN_URL = labels.getString("security_tokenUrl");
}
/**
* Builds the security MarkupDocument.
*
* @return the security MarkupDocument
*/
@Override
public MarkupDocument build(){
Map<String, SecuritySchemeDefinition> definitions = globalContext.getSwagger().getSecurityDefinitions();
if (MapUtils.isNotEmpty(definitions)) {
applySecurityDocumentExtension(new Context(Position.DOCUMENT_BEFORE, this.markupDocBuilder));
buildSecurityTitle(SECURITY);
applySecurityDocumentExtension(new Context(Position.DOCUMENT_BEGIN, this.markupDocBuilder));
buildSecuritySchemeDefinitionsSection(definitions);
applySecurityDocumentExtension(new Context(Position.DOCUMENT_END, this.markupDocBuilder));
applySecurityDocumentExtension(new Context(Position.DOCUMENT_AFTER, this.markupDocBuilder));
}
return new MarkupDocument(markupDocBuilder);
}
private void buildSecurityTitle(String title) {
this.markupDocBuilder.sectionTitleWithAnchorLevel1(title, SECURITY_ANCHOR);
}
private void buildSecuritySchemeDefinitionsSection(Map<String, SecuritySchemeDefinition> securitySchemes) {
Set<String> securitySchemeNames = toKeySet(securitySchemes, Ordering.natural()); // TODO : provide a dedicated ordering configuration for security schemes
for (String securitySchemeName : securitySchemeNames) {
SecuritySchemeDefinition securityScheme = securitySchemes.get(securitySchemeName);
applySecurityDocumentExtension(new Context(Position.SECURITY_SCHEME_BEFORE, markupDocBuilder, securitySchemeName, securityScheme));
buildSecuritySchemeDefinitionTitle(securitySchemeName);
applySecurityDocumentExtension(new Context(Position.SECURITY_SCHEME_BEGIN, markupDocBuilder, securitySchemeName, securityScheme));
buildDescriptionParagraph(securityScheme.getDescription(), this.markupDocBuilder);
buildSecurityScheme(securityScheme);
applySecurityDocumentExtension(new Context(Position.SECURITY_SCHEME_END, markupDocBuilder, securitySchemeName, securityScheme));
applySecurityDocumentExtension(new Context(Position.SECURITY_SCHEME_AFTER, markupDocBuilder, securitySchemeName, securityScheme));
}
}
private MarkupDocBuilder buildSecuritySchemeDefinitionTitle(String securitySchemeName) {
return markupDocBuilder.sectionTitleWithAnchorLevel2(securitySchemeName);
}
private void buildSecurityScheme(SecuritySchemeDefinition securityScheme) {
String type = securityScheme.getType();
MarkupDocBuilder paragraph = copyMarkupDocBuilder();
paragraph.italicText(TYPE).textLine(COLON + type);
if (securityScheme instanceof ApiKeyAuthDefinition) {
paragraph.italicText(NAME).textLine(COLON + ((ApiKeyAuthDefinition) securityScheme).getName());
paragraph.italicText(IN).textLine(COLON + ((ApiKeyAuthDefinition) securityScheme).getIn());
markupDocBuilder.paragraph(paragraph.toString(), true);
} else if (securityScheme instanceof OAuth2Definition) {
OAuth2Definition oauth2Scheme = (OAuth2Definition) securityScheme;
String flow = oauth2Scheme.getFlow();
paragraph.italicText(FLOW).textLine(COLON + flow);
if (isNotBlank(oauth2Scheme.getAuthorizationUrl())) {
paragraph.italicText(AUTHORIZATION_URL).textLine(COLON + oauth2Scheme.getAuthorizationUrl());
}
if (isNotBlank(oauth2Scheme.getTokenUrl())) {
paragraph.italicText(TOKEN_URL).textLine(COLON + oauth2Scheme.getTokenUrl());
}
List<List<String>> cells = new ArrayList<>();
List<MarkupTableColumn> cols = Arrays.asList(
new MarkupTableColumn(NAME_COLUMN).withWidthRatio(3).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^3"),
new MarkupTableColumn(DESCRIPTION_COLUMN).withWidthRatio(17).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^17"));
for (Map.Entry<String, String> scope : oauth2Scheme.getScopes().entrySet()) {
List<String> content = Arrays.asList(scope.getKey(), scope.getValue());
cells.add(content);
}
markupDocBuilder.paragraph(paragraph.toString(), true);
markupDocBuilder.tableWithColumnSpecs(cols, cells);
} else {
markupDocBuilder.paragraph(paragraph.toString(), true);
}
}
/**
* Apply extension context to all SecurityContentExtension
*
* @param context context
*/
private void applySecurityDocumentExtension(Context context) {
for (SecurityDocumentExtension extension : extensionRegistry.getSecurityDocumentExtensions()) {
extension.apply(context);
}
}
}

View File

@@ -1,65 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.type;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
/**
* Array type abstraction
*/
public class ArrayType extends Type {
protected String collectionFormat;
protected Type ofType;
public ArrayType(String name, Type ofType) {
this(name, ofType, null);
}
public ArrayType(String name, Type ofType, String collectionFormat) {
super(name);
this.collectionFormat = collectionFormat;
this.ofType = ofType;
}
@Override
public String displaySchema(MarkupDocBuilder docBuilder) {
String ofTypeDisplay = ofType.displaySchema(docBuilder);
if (isNotBlank(this.collectionFormat))
return String.format("< %s > array(%s)", ofTypeDisplay, collectionFormat);
else
return String.format("< %s > array", ofTypeDisplay);
}
public String getCollectionFormat() {
return collectionFormat;
}
public void setCollectionFormat(String collectionFormat) {
this.collectionFormat = collectionFormat;
}
public Type getOfType() {
return ofType;
}
public void setOfType(Type ofType) {
this.ofType = ofType;
}
}

View File

@@ -1,69 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.type;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import org.apache.commons.lang3.Validate;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
/**
* Base type abstraction (string, integer, ...)
*/
public class BasicType extends Type {
/**
* Basic type
*/
protected String type;
protected String format;
public BasicType(String type, String name) {
this(type, name, null);
}
public BasicType(String type, String name, String format) {
super(name);
Validate.notBlank(type);
this.type = type;
this.format = format;
}
@Override
public String displaySchema(MarkupDocBuilder docBuilder) {
if (isNotBlank(this.format))
return String.format("%s(%s)", this.type, this.format);
else
return this.type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}

View File

@@ -1,24 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.type;
import com.google.common.base.Function;
/**
* A functor to return the document part of an inter-document cross-references, depending on the globalContext.
*/
public interface DefinitionDocumentResolver extends Function<String, String> {}

View File

@@ -1,49 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.type;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import java.util.List;
import static org.apache.commons.lang3.StringUtils.join;
/**
* Enum type abstraction
*/
public class EnumType extends Type {
protected List<String> values;
public EnumType(String name, List<String> values) {
super(name);
this.values = values;
}
@Override
public String displaySchema(MarkupDocBuilder docBuilder) {
return String.format("enum (%s)", join(values, ", "));
}
public List<String> getValues() {
return values;
}
public void setValues(List<String> values) {
this.values = values;
}
}

View File

@@ -1,51 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.type;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
/**
* Array type abstraction
*/
public class MapType extends Type {
protected Type keyType = new BasicType("string", null);
protected Type valueType;
public MapType(String name, Type valueType) {
super(name);
this.valueType = valueType;
}
@Override
public String displaySchema(MarkupDocBuilder docBuilder) {
String keyTypeDisplay = keyType.displaySchema(docBuilder);
return String.format("< %s, %s > map", keyTypeDisplay, valueType.displaySchema(docBuilder));
}
public Type getKeyType() {
return keyType;
}
public Type getValueType() {
return valueType;
}
public void setValueType(Type valueType) {
this.valueType = valueType;
}
}

View File

@@ -1,62 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.type;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.swagger.models.properties.Property;
import java.util.Map;
/**
* Complex object abstraction
*/
public class ObjectType extends Type {
protected Map<String, Property> properties;
protected ObjectTypePolymorphism polymorphism;
public ObjectType(String name, ObjectTypePolymorphism polymorphism, Map<String, Property> properties) {
super(name);
this.polymorphism = polymorphism;
this.properties = properties;
}
public ObjectType(String name, Map<String, Property> properties) {
this(name, new ObjectTypePolymorphism(ObjectTypePolymorphism.Nature.NONE, null), properties);
}
@Override
public String displaySchema(MarkupDocBuilder docBuilder) {
return "object";
}
public ObjectTypePolymorphism getPolymorphism() {
return polymorphism;
}
public void setPolymorphism(ObjectTypePolymorphism polymorphism) {
this.polymorphism = polymorphism;
}
public Map<String, Property> getProperties() {
return properties;
}
public void setProperties(Map<String, Property> properties) {
this.properties = properties;
}
}

View File

@@ -1,51 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.type;
public class ObjectTypePolymorphism {
public enum Nature {
NONE,
COMPOSITION,
INHERITANCE
}
public Nature nature = Nature.NONE;
public String discriminator;
public ObjectTypePolymorphism(Nature nature, String discriminator) {
this.nature = nature;
this.discriminator = discriminator;
}
public Nature getNature() {
return nature;
}
public void setNature(Nature nature) {
this.nature = nature;
}
public String getDiscriminator() {
return discriminator;
}
public void setDiscriminator(String discriminator) {
this.discriminator = discriminator;
}
}

View File

@@ -1,59 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.type;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
/**
* Reference to a type defined elsewhere
*/
public class RefType extends Type {
private String document;
private Type refType;
public RefType(String document, Type refType) {
super(null);
this.document = document;
this.refType = refType;
}
public RefType(Type refType) {
this(null, refType);
}
@Override
public String displaySchema(MarkupDocBuilder docBuilder) {
return docBuilder.copy(false).crossReference(getDocument(), refType.getUniqueName(), refType.getName()).toString();
}
public String getDocument() {
return document;
}
public void setDocument(String document) {
this.document = document;
}
public Type getRefType() {
return refType;
}
public void setRefType(Type refType) {
this.refType = refType;
}
}

View File

@@ -1,55 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.type;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
/**
* Type abstraction for display purpose
*/
public abstract class Type {
protected String name;
protected String uniqueName;
public Type(String name, String uniqueName) {
this.name = name;
this.uniqueName = uniqueName;
}
public Type(String name) {
this(name, name);
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getUniqueName() {
return uniqueName;
}
public void setUniqueName(String uniqueName) {
this.uniqueName = uniqueName;
}
public abstract String displaySchema(MarkupDocBuilder docBuilder);
}

View File

@@ -1,314 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.utils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.model.PathOperation;
import io.swagger.models.*;
import io.swagger.models.parameters.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class ExamplesUtil {
private static Logger logger = LoggerFactory.getLogger(ExamplesUtil.class);
/**
* Generates a map of response examples from the given {@code operation}
*
* @param generateMissingExamples specifies the missing examples should be generated
* @param operation the Swagger Operation
* @param definitions the map of all available definitions
* @param markupDocBuilder the markup builder
* @return map containing response examples.
*/
public static Map<String, Object> generateResponseExampleMap(boolean generateMissingExamples, Operation operation, Map<String, Model> definitions, MarkupDocBuilder markupDocBuilder) {
Map<String, Object> examples = new LinkedHashMap<>();
Map<String, Response> responses = operation.getResponses();
if (responses != null)
for (Map.Entry<String, Response> responseEntry : responses.entrySet()) {
Response response = responseEntry.getValue();
Object example = response.getExamples();
if (example == null) {
Property schema = response.getSchema();
if (schema != null) {
example = schema.getExample();
if (example == null && schema instanceof RefProperty) {
String simpleRef = ((RefProperty) schema).getSimpleRef();
example = generateExampleForRefModel(generateMissingExamples, simpleRef, definitions, markupDocBuilder);
}
if (example == null && generateMissingExamples) {
example = PropertyUtils.generateExample(schema, markupDocBuilder);
}
}
}
if (example != null)
examples.put(responseEntry.getKey(), example);
}
return examples;
}
/**
* Generates a map of request examples from the given {@code operation}
*
* @param generateMissingExamples specifies the missing examples should be generated
* @param pathOperation the Swagger Operation
* @param definitions the map of all available definitions
* @param markupDocBuilder the markup builder
* @return map containing request examples
*/
public static Map<String, Object> generateRequestExampleMap(boolean generateMissingExamples, PathOperation pathOperation, Map<String, Model> definitions, MarkupDocBuilder markupDocBuilder) {
Operation operation = pathOperation.getOperation();
List<Parameter> parameters = operation.getParameters();
Map<String, Object> examples = new LinkedHashMap<>();
// Path example should always be included (if generateMissingExamples):
if (generateMissingExamples)
examples.put("path", pathOperation.getPath());
for (Parameter parameter : parameters) {
Object example = null;
if (parameter instanceof BodyParameter) {
example = ((BodyParameter) parameter).getExamples();
if (example == null) {
Model schema = ((BodyParameter) parameter).getSchema();
if (schema instanceof RefModel) {
String simpleRef = ((RefModel) schema).getSimpleRef();
example = generateExampleForRefModel(generateMissingExamples, simpleRef, definitions, markupDocBuilder);
} else if (generateMissingExamples) {
if (schema instanceof ComposedModel) {
example = exampleMapForProperties(getPropertiesForComposedModel(
(ComposedModel) schema, definitions), definitions, markupDocBuilder);
} else if (schema instanceof ArrayModel) {
example = generateExampleForArrayModel((ArrayModel) schema, definitions, markupDocBuilder);
} else {
example = schema.getExample();
if (example == null) {
example = exampleMapForProperties(schema.getProperties(), definitions, markupDocBuilder);
}
}
}
}
} else if (parameter instanceof AbstractSerializableParameter) {
if (generateMissingExamples) {
Object abstractSerializableParameterExample;
abstractSerializableParameterExample = ((AbstractSerializableParameter) parameter).getExample();
if (abstractSerializableParameterExample == null) {
Property item = ((AbstractSerializableParameter) parameter).getItems();
if (item != null) {
abstractSerializableParameterExample = item.getExample();
if (abstractSerializableParameterExample == null) {
abstractSerializableParameterExample = PropertyUtils.generateExample(item, markupDocBuilder);
}
}
if (abstractSerializableParameterExample == null) {
abstractSerializableParameterExample = ParameterUtils.generateExample((AbstractSerializableParameter)parameter);
}
}
if (parameter instanceof PathParameter) {
String pathExample = (String) examples.get("path");
pathExample = pathExample.replace('{' + parameter.getName() + '}', String.valueOf(abstractSerializableParameterExample));
example = pathExample;
} else {
example = abstractSerializableParameterExample;
}
if (parameter instanceof QueryParameter) {
//noinspection unchecked
@SuppressWarnings("unchecked")
Map<String, Object> queryExampleMap = (Map<String, Object>) examples.get("query");
if (queryExampleMap == null) {
queryExampleMap = new LinkedHashMap<>();
}
queryExampleMap.put(parameter.getName(), abstractSerializableParameterExample);
example = queryExampleMap;
}
}
} else if (parameter instanceof RefParameter) {
String simpleRef = ((RefParameter) parameter).getSimpleRef();
example = generateExampleForRefModel(generateMissingExamples, simpleRef, definitions, markupDocBuilder);
}
if (example != null)
examples.put(parameter.getIn(), example);
}
return examples;
}
/**
* Generates an example object from a simple reference
*
* @param generateMissingExamples specifies the missing examples should be generated
* @param simpleRef the simple reference string
* @param definitions the map of definitions
* @param markupDocBuilder the markup builder
* @return returns an Object or Map of examples
*/
public static Object generateExampleForRefModel(boolean generateMissingExamples, String simpleRef, Map<String, Model> definitions, MarkupDocBuilder markupDocBuilder) {
Model model = definitions.get(simpleRef);
Object example = null;
if (model != null) {
example = model.getExample();
// Workaround for https://github.com/swagger-api/swagger-parser/issues/255 returning a string
if (model instanceof ArrayModel && example instanceof String) {
ObjectMapper mapper = new ObjectMapper();
try {
example = mapper.readTree((String) example);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (example == null && generateMissingExamples) {
if (model instanceof ComposedModel) {
example = exampleMapForProperties(getPropertiesForComposedModel((ComposedModel) model, definitions), definitions, markupDocBuilder);
} else {
example = exampleMapForProperties(model.getProperties(), definitions, markupDocBuilder);
}
}
}
return example;
}
private static Map<String, Property> getPropertiesForComposedModel(ComposedModel model, Map<String, Model> definitions) {
Map<String, Property> combinedProperties;
if (model.getParent() instanceof RefModel) {
Map<String, Property> parentProperties = definitions.get(((RefModel) model.getParent()).getSimpleRef()).getProperties();
if (parentProperties == null) {
return null;
} else {
combinedProperties = new LinkedHashMap<>(parentProperties);
}
} else {
combinedProperties = new LinkedHashMap<>(model.getParent().getProperties());
}
Map<String, Property> childProperties;
if (model.getChild() instanceof RefModel) {
childProperties = definitions.get(((RefModel) model.getChild()).getSimpleRef()).getProperties();
} else {
childProperties = model.getChild().getProperties();
}
if (childProperties != null) {
combinedProperties.putAll(childProperties);
}
return combinedProperties;
}
/**
* Generates a map of examples from a map of properties. If defined examples are found, those are used. Otherwise,
* examples are generated from the type.
*
* @param properties the map of properties
* @param definitions the map of definitions
* @param markupDocBuilder the markup builder
*
* @return a Map of examples
*/
public static Map<String, Object> exampleMapForProperties(Map<String, Property> properties, Map<String, Model> definitions, MarkupDocBuilder markupDocBuilder) {
Map<String, Object> exampleMap = new LinkedHashMap<>();
if (properties != null) {
for (Map.Entry<String, Property> property : properties.entrySet()) {
Object exampleObject = property.getValue().getExample();
if (exampleObject == null) {
if (property.getValue() instanceof RefProperty) {
exampleObject = generateExampleForRefModel(true, ((RefProperty) property.getValue()).getSimpleRef(), definitions, markupDocBuilder);
} else if (property.getValue() instanceof ArrayProperty) {
exampleObject = generateExampleForArrayProperty((ArrayProperty) property.getValue(), definitions, markupDocBuilder);
} else if (property.getValue() instanceof MapProperty) {
exampleObject = generateExampleForMapProperty((MapProperty) property.getValue(), markupDocBuilder);
}
if (exampleObject == null) {
Property valueProperty = property.getValue();
exampleObject = PropertyUtils.generateExample(valueProperty, markupDocBuilder);
}
}
exampleMap.put(property.getKey(), exampleObject);
}
}
return exampleMap;
}
public static Object generateExampleForMapProperty(MapProperty property, MarkupDocBuilder markupDocBuilder) {
if (property.getExample() != null) {
return property.getExample();
}
Map<String, Object> exampleMap = new LinkedHashMap<>();
Property valueProperty = property.getAdditionalProperties();
if (valueProperty.getExample() != null) {
return valueProperty.getExample();
}
exampleMap.put("string", PropertyUtils.generateExample(valueProperty, markupDocBuilder));
return exampleMap;
}
public static Object generateExampleForArrayModel(ArrayModel model, Map<String, Model> definitions, MarkupDocBuilder markupDocBuilder) {
if (model.getExample() != null) {
return model.getExample();
} else if (model.getProperties() != null) {
return new Object[]{exampleMapForProperties(model.getProperties(), definitions, markupDocBuilder)};
} else {
Property itemProperty = model.getItems();
if (itemProperty.getExample() != null) {
return new Object[]{itemProperty.getExample()};
} else if (itemProperty instanceof ArrayProperty) {
return new Object[]{generateExampleForArrayProperty((ArrayProperty) itemProperty, definitions, markupDocBuilder)};
} else if (itemProperty instanceof RefProperty) {
return new Object[]{generateExampleForRefModel(true, ((RefProperty) itemProperty).getSimpleRef(), definitions, markupDocBuilder)};
} else {
return new Object[]{PropertyUtils.generateExample(itemProperty, markupDocBuilder)};
}
}
}
/**
* Generates examples from an ArrayProperty
*
* @param value ArrayProperty
* @param definitions map of definitions
* @param markupDocBuilder the markup builder
* @return array of Object
*/
public static Object[] generateExampleForArrayProperty(ArrayProperty value, Map<String, Model> definitions, MarkupDocBuilder markupDocBuilder) {
Property property = value.getItems();
if (property.getExample() != null) {
return new Object[]{property.getExample()};
} else if (property instanceof ArrayProperty) {
return new Object[]{generateExampleForArrayProperty((ArrayProperty) property, definitions, markupDocBuilder)};
} else if (property instanceof RefProperty) {
return new Object[]{generateExampleForRefModel(true, ((RefProperty) property).getSimpleRef(), definitions, markupDocBuilder)};
} else {
return new Object[]{PropertyUtils.generateExample(property, markupDocBuilder)};
}
}
}

View File

@@ -1,40 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.utils;
import java.util.*;
public class ListUtils {
/**
* Returns the List as an Set either ordered or as-is, if the comparator is null.
*
* @param list the List
* @param comparator the comparator to use.
* @return the Set
*/
public static Set<String> toSet(List<String> list, Comparator<String> comparator){
Set<String> set;
if (comparator == null)
set = new LinkedHashSet<>();
else
set = new TreeSet<>(comparator);
set.addAll(list);
return set;
}
}

View File

@@ -1,38 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.utils;
import java.util.*;
public class MapUtils {
/**
* Returns the keys of the Map either ordered or as-is, if the comparator is null.
*
* @param map the Map
* @param comparator the comparator to use.
* @return the keySet of the Map
*/
public static Set<String> toKeySet(Map<String, ?> map, Comparator<String> comparator){
Set<String> keys;
if (comparator == null)
keys = new LinkedHashSet<>();
else
keys = new TreeSet<>(comparator);
keys.addAll(map.keySet());
return keys;
}
}

View File

@@ -1,120 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.utils;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import io.github.swagger2markup.internal.type.*;
import io.swagger.models.*;
import io.swagger.models.properties.Property;
import io.swagger.models.refs.RefFormat;
import org.apache.commons.lang3.Validate;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public final class ModelUtils {
/**
* Recursively resolve referenced type if {@code type} is of type RefType
* @param type type to resolve
* @return referenced type
*/
public static Type resolveRefType(Type type) {
if (type == null)
return null;
if (type instanceof RefType)
return resolveRefType(((RefType) type).getRefType());
else
return type;
}
/**
* Retrieves the type of a model, or otherwise null
*
* @param model the model
* @param definitionDocumentResolver the definition document resolver
* @return the type of the model, or otherwise null
*/
public static Type getType(Model model, Map<String, Model> definitions, Function<String, String> definitionDocumentResolver) {
Validate.notNull(model, "model must not be null!");
if (model instanceof ModelImpl) {
ModelImpl modelImpl = (ModelImpl) model;
if (modelImpl.getAdditionalProperties() != null)
return new MapType(modelImpl.getTitle(), PropertyUtils.getType(modelImpl.getAdditionalProperties(), definitionDocumentResolver));
else if (modelImpl.getEnum() != null)
return new EnumType(modelImpl.getTitle(), modelImpl.getEnum());
else if (modelImpl.getProperties() != null) {
ObjectType objectType = new ObjectType(modelImpl.getTitle(), model.getProperties());
objectType.getPolymorphism().setDiscriminator(modelImpl.getDiscriminator());
return objectType;
} else
return new BasicType(modelImpl.getType(), modelImpl.getTitle());
} else if (model instanceof ComposedModel) {
ComposedModel composedModel = (ComposedModel) model;
Map<String, Property> allProperties = new LinkedHashMap<>();
ObjectTypePolymorphism polymorphism = new ObjectTypePolymorphism(ObjectTypePolymorphism.Nature.NONE, null);
String name = model.getTitle();
if (composedModel.getAllOf() != null) {
polymorphism.setNature(ObjectTypePolymorphism.Nature.COMPOSITION);
for (Model innerModel : composedModel.getAllOf()) {
Type innerModelType = resolveRefType(getType(innerModel, definitions, definitionDocumentResolver));
name = innerModelType.getName();
if (innerModelType instanceof ObjectType) {
String innerModelDiscriminator = ((ObjectType) innerModelType).getPolymorphism().getDiscriminator();
if (innerModelDiscriminator != null) {
polymorphism.setNature(ObjectTypePolymorphism.Nature.INHERITANCE);
polymorphism.setDiscriminator(innerModelDiscriminator);
}
Map<String, Property> innerModelProperties = ((ObjectType) innerModelType).getProperties();
if (innerModelProperties != null)
allProperties.putAll(ImmutableMap.copyOf(innerModelProperties));
}
}
}
return new ObjectType(name, polymorphism, allProperties);
} else if (model instanceof RefModel) {
RefModel refModel = (RefModel) model;
String refName = refModel.getRefFormat().equals(RefFormat.INTERNAL) ? refModel.getSimpleRef() : refModel.getReference();
Type refType = new ObjectType(refName, null);
if (definitions.containsKey(refName)) {
refType = getType(definitions.get(refName), definitions, definitionDocumentResolver);
refType.setName(refName);
refType.setUniqueName(refName);
}
return new RefType(definitionDocumentResolver.apply(refName), refType);
} else if (model instanceof ArrayModel) {
ArrayModel arrayModel = ((ArrayModel) model);
return new ArrayType(null, PropertyUtils.getType(arrayModel.getItems(), definitionDocumentResolver));
}
return null;
}
}

View File

@@ -1,117 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.utils;
import com.google.common.base.Function;
import io.github.swagger2markup.internal.type.*;
import io.swagger.models.Model;
import io.swagger.models.parameters.AbstractSerializableParameter;
import io.swagger.models.parameters.BodyParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.parameters.RefParameter;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.Validate;
import java.util.List;
import java.util.Map;
public final class ParameterUtils {
/**
* Retrieves the type of a parameter, or otherwise null
*
* @param parameter the parameter
* @param definitionDocumentResolver the defintion document resolver
* @return the type of the parameter, or otherwise null
*/
public static Type getType(Parameter parameter, Map<String, Model> definitions, Function<String, String> definitionDocumentResolver){
Validate.notNull(parameter, "parameter must not be null!");
Type type = null;
if(parameter instanceof BodyParameter){
BodyParameter bodyParameter = (BodyParameter)parameter;
Model model = bodyParameter.getSchema();
if(model != null){
type = ModelUtils.getType(model, definitions, definitionDocumentResolver);
}else{
type = new BasicType("string", null);
}
}
else if(parameter instanceof AbstractSerializableParameter){
AbstractSerializableParameter serializableParameter = (AbstractSerializableParameter)parameter;
@SuppressWarnings("unchecked")
List<String> enums = serializableParameter.getEnum();
if(CollectionUtils.isNotEmpty(enums)){
type = new EnumType(null, enums);
}else{
type = new BasicType(serializableParameter.getType(), null, serializableParameter.getFormat());
}
if(serializableParameter.getType().equals("array")){
String collectionFormat = serializableParameter.getCollectionFormat();
type = new ArrayType(null, PropertyUtils.getType(serializableParameter.getItems(), definitionDocumentResolver), collectionFormat);
}
}
else if(parameter instanceof RefParameter){
String refName = ((RefParameter)parameter).getSimpleRef();
type = new RefType(definitionDocumentResolver.apply(refName), new ObjectType(refName, null /* FIXME, not used for now */));
}
return type;
}
/**
* Retrieves the default value of a parameter, or otherwise returns null
*
* @param parameter the parameter
* @return the default value of the parameter, or otherwise null
*/
public static Object getDefaultValue(Parameter parameter){
Validate.notNull(parameter, "parameter must not be null!");
Object defaultValue = null;
if(parameter instanceof AbstractSerializableParameter){
AbstractSerializableParameter serializableParameter = (AbstractSerializableParameter)parameter;
defaultValue = serializableParameter.getDefaultValue();
}
return defaultValue;
}
/**
* Generate a default example value for parameter.
*
* @param parameter parameter
* @return a generated example for the parameter
*/
public static Object generateExample(AbstractSerializableParameter parameter) {
switch (parameter.getType()) {
case "integer":
return 0;
case "number":
return 0.0;
case "boolean":
return true;
case "string":
return "string";
default:
return parameter.getType();
}
}
}

View File

@@ -1,210 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.utils;
import com.google.common.base.Function;
import io.github.swagger2markup.internal.type.*;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.swagger.models.properties.*;
import io.swagger.models.refs.RefFormat;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.Validate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public final class PropertyUtils {
/**
* Retrieves the type and format of a property.
*
* @param property the property
* @param definitionDocumentResolver the definition document resolver
* @return the type of the property
*/
public static Type getType(Property property, Function<String, String> definitionDocumentResolver) {
Validate.notNull(property, "property must not be null");
Type type;
if (property instanceof RefProperty) {
RefProperty refProperty = (RefProperty) property;
if (refProperty.getRefFormat() == RefFormat.RELATIVE)
type = new ObjectType(refProperty.getTitle(), null); // FIXME : Workaround for https://github.com/swagger-api/swagger-parser/issues/177
else
type = new RefType(definitionDocumentResolver.apply(refProperty.getSimpleRef()), new ObjectType(refProperty.getSimpleRef(), null /* FIXME, not used for now */));
} else if (property instanceof ArrayProperty) {
ArrayProperty arrayProperty = (ArrayProperty) property;
Property items = arrayProperty.getItems();
if (items == null)
type = new ArrayType(arrayProperty.getTitle(), new ObjectType(null, null)); // FIXME : Workaround for Swagger parser issue with composed models (https://github.com/Swagger2Markup/swagger2markup/issues/150)
else
type = new ArrayType(arrayProperty.getTitle(), getType(items, definitionDocumentResolver));
} else if (property instanceof MapProperty) {
MapProperty mapProperty = (MapProperty) property;
Property additionalProperties = mapProperty.getAdditionalProperties();
if (additionalProperties == null)
type = new MapType(mapProperty.getTitle(), new ObjectType(null, null)); // FIXME : Workaround for Swagger parser issue with composed models (https://github.com/Swagger2Markup/swagger2markup/issues/150)
else
type = new MapType(mapProperty.getTitle(), getType(additionalProperties, definitionDocumentResolver));
} else if (property instanceof StringProperty) {
StringProperty stringProperty = (StringProperty) property;
List<String> enums = stringProperty.getEnum();
if (CollectionUtils.isNotEmpty(enums)) {
type = new EnumType(stringProperty.getTitle(), enums);
} else {
type = new BasicType(stringProperty.getType(), stringProperty.getTitle());
}
} else if (property instanceof ObjectProperty) {
type = new ObjectType(property.getTitle(), ((ObjectProperty) property).getProperties());
} else {
if (isNotBlank(property.getFormat())) {
type = new BasicType(property.getType(), property.getTitle(), property.getFormat());
} else {
type = new BasicType(property.getType(), property.getTitle());
}
}
return type;
}
/**
* Retrieves the default value of a property, or otherwise returns null.
*
* @param property the property
* @return the default value of the property, or otherwise null
*/
public static Object getDefaultValue(Property property) {
Validate.notNull(property, "property must not be null");
Object defaultValue = null;
if (property instanceof BooleanProperty) {
BooleanProperty booleanProperty = (BooleanProperty) property;
defaultValue = booleanProperty.getDefault();
} else if (property instanceof StringProperty) {
StringProperty stringProperty = (StringProperty) property;
defaultValue = stringProperty.getDefault();
} else if (property instanceof DoubleProperty) {
DoubleProperty doubleProperty = (DoubleProperty) property;
defaultValue = doubleProperty.getDefault();
} else if (property instanceof FloatProperty) {
FloatProperty floatProperty = (FloatProperty) property;
defaultValue = floatProperty.getDefault();
} else if (property instanceof IntegerProperty) {
IntegerProperty integerProperty = (IntegerProperty) property;
defaultValue = integerProperty.getDefault();
} else if (property instanceof LongProperty) {
LongProperty longProperty = (LongProperty) property;
defaultValue = longProperty.getDefault();
} else if (property instanceof UUIDProperty) {
UUIDProperty uuidProperty = (UUIDProperty) property;
defaultValue = uuidProperty.getDefault();
}
return defaultValue;
}
/**
* Return example display string for the given {@code property}.
*
* @param generateMissingExamples specifies if missing examples should be generated
* @param property property
* @param markupDocBuilder doc builder
* @return property example display string
*/
public static Object getExample(boolean generateMissingExamples, Property property, MarkupDocBuilder markupDocBuilder) {
Validate.notNull(property, "property must not be null");
Object examplesValue = null;
if (property.getExample() != null) {
examplesValue = property.getExample();
} else if (property instanceof MapProperty) {
Property additionalProperty = ((MapProperty) property).getAdditionalProperties();
if (additionalProperty.getExample() != null) {
examplesValue = additionalProperty.getExample();
} else if (generateMissingExamples) {
Map<String, Object> exampleMap = new HashMap<>();
exampleMap.put("string", generateExample(additionalProperty, markupDocBuilder));
examplesValue = exampleMap;
}
} else if (property instanceof ArrayProperty) {
if (generateMissingExamples) {
Property itemProperty = ((ArrayProperty) property).getItems();
List<Object> exampleArray = new ArrayList<>();
exampleArray.add(generateExample(itemProperty, markupDocBuilder));
examplesValue = exampleArray;
}
} else if (generateMissingExamples) {
examplesValue = generateExample(property, markupDocBuilder);
}
return examplesValue;
}
/**
* Generate a default example value for property.
*
* @param property property
* @param markupDocBuilder doc builder
* @return a generated example for the property
*/
public static Object generateExample(Property property, MarkupDocBuilder markupDocBuilder) {
switch (property.getType()) {
case "integer":
return 0;
case "number":
return 0.0;
case "boolean":
return true;
case "string":
return "string";
case "ref":
if (property instanceof RefProperty) {
return markupDocBuilder.copy(false).crossReference(((RefProperty) property).getSimpleRef()).toString();
}
default:
return property.getType();
}
}
/**
* Convert a string {@code value} to specified {@code type}.
*
* @param value value to convert
* @param type target conversion type
* @return converted value as object
*/
public static Object convertExample(String value, String type) {
if (value == null) {
return null;
}
try {
switch (type) {
case "integer":
return Integer.valueOf(value);
case "number":
return Float.valueOf(value);
case "boolean":
return Boolean.valueOf(value);
case "string":
return value;
default:
return value;
}
} catch (NumberFormatException e) {
throw new RuntimeException(String.format("Value '%s' cannot be converted to '%s'", value, type), e);
}
}
}

View File

@@ -1,101 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.internal.utils;
import com.google.common.base.Optional;
import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
import com.google.common.collect.Ordering;
import io.github.swagger2markup.model.PathOperation;
import io.swagger.models.Tag;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class TagUtils {
private static Logger LOG = LoggerFactory.getLogger(TagUtils.class);
/**
* Converts the global Tag list into a Map where the tag name is the key and the Tag the value.
*
* @param tags the List of tags
* @return the Map of tags
*/
public static Map<String, Tag> convertTagsListToMap(List<Tag> tags) {
if (tags == null) {
tags = new ArrayList<>();
}
Map<String, Tag> tagsMap = new HashMap<>();
for (Tag tag : tags) tagsMap.put(tag.getName(), tag);
return tagsMap;
}
/**
* Retrieves the optional description of a tag.
*
* @param tagsMap the Map of tags
* @param tagName the name of the tag
* @return the optional description of the tag
*/
public static Optional<String> getTagDescription(Map<String, Tag> tagsMap, String tagName) {
Tag tag = tagsMap.get(tagName);
if(tag != null){
return Optional.fromNullable(tag.getDescription());
}
return Optional.absent();
}
/**
* Groups the operations by tag. The key of the Multimap is the tag name.
* The value of the Multimap is a PathOperation
*
* @param allOperations all operations
* @param tagOrdering comparator for tags
* @param operationOrdering comparator for operations, for a given tag
* @return Operations grouped by Tag
*/
public static Multimap<String, PathOperation> groupOperationsByTag(Set<PathOperation> allOperations, Comparator<String> tagOrdering, Comparator<PathOperation> operationOrdering) {
MultimapBuilder.MultimapBuilderWithKeys<String> multimapBuilderWithKeys;
if (tagOrdering == null)
multimapBuilderWithKeys = MultimapBuilder.SortedSetMultimapBuilder.treeKeys(Ordering.<String>natural()); // FIXME as-is sorting not supported because of limitations in MultiMap::hashkeys(). Replaced with Ordering.natural()
else
multimapBuilderWithKeys = MultimapBuilder.SortedSetMultimapBuilder.treeKeys(tagOrdering);
Multimap<String, PathOperation> operationsGroupedByTag;
if (operationOrdering == null)
operationsGroupedByTag = multimapBuilderWithKeys.hashSetValues().build();
else
operationsGroupedByTag = multimapBuilderWithKeys.treeSetValues(operationOrdering).build();
for (PathOperation operation : allOperations) {
List<String> tags = operation.getOperation().getTags();
Validate.notEmpty(tags, "Can't GroupBy.TAGS > Operation '%s' has not tags", operation);
for (String tag : tags) {
if (LOG.isInfoEnabled()) {
LOG.info("Added path operation '{}' to tag '{}'", operation, tag);
}
operationsGroupedByTag.put(tag, operation);
}
}
return operationsGroupedByTag;
}
}

View File

@@ -1,79 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.model;
import io.swagger.models.HttpMethod;
import io.swagger.models.Operation;
import static org.apache.commons.lang3.StringUtils.isBlank;
public class PathOperation {
protected HttpMethod method;
protected String path;
protected Operation operation;
public PathOperation(HttpMethod method, String path, Operation operation) {
this.method = method;
this.path = path;
this.operation = operation;
}
public HttpMethod getMethod() {
return method;
}
public String getPath() {
return path;
}
/**
* Returns the display title for an operation
* @return the operation title
*/
public String getTitle() {
String operationName = operation.getSummary();
if (isBlank(operationName)) {
operationName = getMethod().toString() + " " + getPath();
}
return operationName;
}
/**
* Returns an unique id for the operation.<br>
* Use {@code <operation id>}, then {@code <operation path> lowercase(<operation method>)} if operation id is not set.
*
* @return operation unique id
*/
public String getId() {
String id = operation.getOperationId();
if (id == null)
id = getPath() + " " + getMethod().toString().toLowerCase();
return id;
}
public Operation getOperation() {
return operation;
}
@Override
public String toString() {
return getId();
}
}

View File

@@ -1,47 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.spi;
import io.github.swagger2markup.Swagger2MarkupConverter;
/**
* An abstract extension which must be extended by an extension
*/
abstract class AbstractExtension implements Extension {
protected Swagger2MarkupConverter.Context globalContext;
/**
* Global context lazy initialization
*
* @param globalContext Global context
*/
public void setGlobalContext(Swagger2MarkupConverter.Context globalContext) {
this.globalContext = globalContext;
init(globalContext);
}
/**
* Overridable init event listener.
*
* @param globalContext Global context
*/
public void init(Swagger2MarkupConverter.Context globalContext) {
/* must be left empty */
}
}

View File

@@ -1,31 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.spi;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
public class ContentContext {
private MarkupDocBuilder docBuilder;
ContentContext(MarkupDocBuilder docBuilder) {
this.docBuilder = docBuilder;
}
public MarkupDocBuilder getMarkupDocBuilder() {
return docBuilder;
}
}

View File

@@ -1,124 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.spi;
import com.google.common.base.Optional;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.swagger.models.Model;
import org.apache.commons.lang3.Validate;
/**
* DefinitionsDocumentExtension extension point can be used to extend the definitions document content.
*/
public abstract class DefinitionsDocumentExtension extends AbstractExtension {
public enum Position {
DOCUMENT_BEFORE,
DOCUMENT_BEGIN,
DOCUMENT_END,
DOCUMENT_AFTER,
DEFINITION_BEFORE,
DEFINITION_BEGIN,
DEFINITION_END,
DEFINITION_AFTER
}
public static class Context extends ContentContext {
private Position position;
/**
* null if position == DOCUMENT_*
*/
private String definitionName;
/**
* null if position == DOCUMENT_*
*/
private Model model;
/**
* @param position the current position
* @param docBuilder the MarkupDocBuilder
*/
public Context(Position position, MarkupDocBuilder docBuilder) {
super(docBuilder);
Validate.inclusiveBetween(Position.DOCUMENT_BEFORE, Position.DOCUMENT_AFTER, position);
this.position = position;
}
/**
* @param position the current position
* @param docBuilder the MarkupDocBuilder
* @param definitionName the name of the current definition
* @param model the current Model of the definition
*/
public Context(Position position, MarkupDocBuilder docBuilder, String definitionName, Model model) {
super(docBuilder);
Validate.inclusiveBetween(Position.DEFINITION_BEFORE, Position.DEFINITION_AFTER, position);
Validate.notNull(definitionName);
Validate.notNull(model);
this.position = position;
this.definitionName = definitionName;
this.model = model;
}
public Position getPosition() {
return position;
}
public Optional<String> getDefinitionName() {
return Optional.fromNullable(definitionName);
}
public Optional<Model> getModel() {
return Optional.fromNullable(model);
}
}
public DefinitionsDocumentExtension() {
}
public abstract void apply(Context context);
/**
* Returns title level offset from 1 to apply to content
* @param context context
* @return title level offset
*/
protected int levelOffset(Context context) {
int levelOffset;
switch (context.position) {
case DOCUMENT_BEFORE:
case DOCUMENT_AFTER:
levelOffset = 0;
break;
case DOCUMENT_BEGIN:
case DOCUMENT_END:
case DEFINITION_BEFORE:
case DEFINITION_AFTER:
levelOffset = 1;
break;
case DEFINITION_BEGIN:
case DEFINITION_END:
levelOffset = 2;
break;
default:
throw new RuntimeException(String.format("Unknown position '%s'", context.position));
}
return levelOffset;
}
}

View File

@@ -1,33 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.spi;
import io.github.swagger2markup.Swagger2MarkupConverter;
/**
* A marker interface which must be implemented by an extension
*/
interface Extension {
/**
* Global context lazy initialization
*
* @param globalContext Global context
*/
void setGlobalContext(Swagger2MarkupConverter.Context globalContext);
}

View File

@@ -1,78 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.spi;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
/**
* OverviewDocumentExtension extension point can be used to extend the overview document content.
*/
public abstract class OverviewDocumentExtension extends AbstractExtension {
public enum Position {
DOCUMENT_BEFORE,
DOCUMENT_AFTER,
DOCUMENT_BEGIN,
DOCUMENT_END
}
public static class Context extends ContentContext {
private Position position;
/**
* @param position the current position
* @param docBuilder the MarkupDocBuilder
*/
public Context(Position position, MarkupDocBuilder docBuilder) {
super(docBuilder);
this.position = position;
}
public Position getPosition() {
return position;
}
}
public OverviewDocumentExtension() {
}
public abstract void apply(Context context);
/**
* Returns title level offset from 1 to apply to content
* @param context context
* @return title level offset
*/
protected int levelOffset(Context context) {
int levelOffset;
switch (context.position) {
case DOCUMENT_BEFORE:
case DOCUMENT_AFTER:
levelOffset = 0;
break;
case DOCUMENT_BEGIN:
case DOCUMENT_END:
levelOffset = 1;
break;
default:
throw new RuntimeException(String.format("Unknown position '%s'", context.position));
}
return levelOffset;
}
}

View File

@@ -1,160 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.spi;
import com.google.common.base.Optional;
import io.github.swagger2markup.GroupBy;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.model.PathOperation;
import org.apache.commons.lang3.Validate;
/**
* PathsDocumentExtension extension point can be used to extend the paths document content.
*/
public abstract class PathsDocumentExtension extends AbstractExtension {
public enum Position {
DOCUMENT_BEFORE,
DOCUMENT_BEGIN,
DOCUMENT_END,
DOCUMENT_AFTER,
OPERATION_BEFORE,
OPERATION_BEGIN,
OPERATION_END,
OPERATION_AFTER,
OPERATION_DESCRIPTION_BEFORE,
OPERATION_DESCRIPTION_BEGIN,
OPERATION_DESCRIPTION_END,
OPERATION_DESCRIPTION_AFTER,
OPERATION_PARAMETERS_BEFORE,
OPERATION_PARAMETERS_BEGIN,
OPERATION_PARAMETERS_END,
OPERATION_PARAMETERS_AFTER,
OPERATION_RESPONSES_BEFORE,
OPERATION_RESPONSES_BEGIN,
OPERATION_RESPONSES_END,
OPERATION_RESPONSES_AFTER,
OPERATION_SECURITY_BEFORE,
OPERATION_SECURITY_BEGIN,
OPERATION_SECURITY_END,
OPERATION_SECURITY_AFTER
}
public static class Context extends ContentContext {
private Position position;
/**
* null if position == DOCUMENT_*
*/
private PathOperation operation;
/**
* Context for positions DOCUMENT_*
*
* @param position the current position
* @param docBuilder the MarkupDocBuilder
*/
public Context(Position position, MarkupDocBuilder docBuilder) {
super(docBuilder);
Validate.inclusiveBetween(Position.DOCUMENT_BEFORE, Position.DOCUMENT_AFTER, position);
this.position = position;
}
/**
* Context for all other positions
* @param position the current position
* @param docBuilder the MarkupDocBuilder
* @param operation the current path operation
*/
public Context(Position position, MarkupDocBuilder docBuilder, PathOperation operation) {
super(docBuilder);
Validate.inclusiveBetween(Position.OPERATION_BEFORE, Position.OPERATION_SECURITY_AFTER, position);
Validate.notNull(operation);
this.position = position;
this.operation = operation;
}
public Position getPosition() {
return position;
}
public Optional<PathOperation> getOperation() {
return Optional.fromNullable(operation);
}
}
public PathsDocumentExtension() {
}
public abstract void apply(Context context);
/**
* Returns title level offset from 1 to apply to content
*
* @param context context
* @return title level offset
*/
protected int levelOffset(Context context) {
int levelOffset;
switch (context.position) {
case DOCUMENT_BEFORE:
case DOCUMENT_AFTER:
levelOffset = 0;
break;
case DOCUMENT_BEGIN:
case DOCUMENT_END:
case OPERATION_BEFORE:
case OPERATION_AFTER:
levelOffset = 1;
break;
case OPERATION_BEGIN:
case OPERATION_END:
levelOffset = increaseLevelOffset(2);
break;
case OPERATION_DESCRIPTION_BEFORE:
case OPERATION_DESCRIPTION_AFTER:
case OPERATION_PARAMETERS_BEFORE:
case OPERATION_PARAMETERS_AFTER:
case OPERATION_RESPONSES_BEFORE:
case OPERATION_RESPONSES_AFTER:
case OPERATION_SECURITY_BEFORE:
case OPERATION_SECURITY_AFTER:
levelOffset = increaseLevelOffset(2);
break;
case OPERATION_DESCRIPTION_BEGIN:
case OPERATION_DESCRIPTION_END:
case OPERATION_PARAMETERS_BEGIN:
case OPERATION_PARAMETERS_END:
case OPERATION_RESPONSES_BEGIN:
case OPERATION_RESPONSES_END:
case OPERATION_SECURITY_BEGIN:
case OPERATION_SECURITY_END:
levelOffset = 3;
break;
default:
throw new RuntimeException(String.format("Unknown position '%s'", context.position));
}
return levelOffset;
}
private int increaseLevelOffset(int levelOffset) {
if (globalContext.getConfig().getPathsGroupedBy() == GroupBy.TAGS) {
return ++levelOffset;
}else {
return levelOffset;
}
}
}

View File

@@ -1,124 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.spi;
import com.google.common.base.Optional;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.swagger.models.auth.SecuritySchemeDefinition;
import org.apache.commons.lang3.Validate;
/**
* SecurityContentExtension extension point can be used to extend the security document content.
*/
public abstract class SecurityDocumentExtension extends AbstractExtension {
public enum Position {
DOCUMENT_BEFORE,
DOCUMENT_BEGIN,
DOCUMENT_END,
DOCUMENT_AFTER,
SECURITY_SCHEME_BEFORE,
SECURITY_SCHEME_BEGIN,
SECURITY_SCHEME_END,
SECURITY_SCHEME_AFTER
}
public static class Context extends ContentContext {
private Position position;
/**
* null if position == DOCUMENT_*
*/
private String securitySchemeName;
/**
* null if position == DOCUMENT_*
*/
private SecuritySchemeDefinition securityScheme;
/**
* @param position the current position
* @param docBuilder the MarkupDocBuilder
*/
public Context(Position position, MarkupDocBuilder docBuilder) {
super(docBuilder);
Validate.inclusiveBetween(Position.DOCUMENT_BEFORE, Position.DOCUMENT_AFTER, position);
this.position = position;
}
/**
* @param position the current position
* @param docBuilder the MarkupDocBuilder
* @param securitySchemeName the name of the current securityScheme
* @param securityScheme the current security scheme securityScheme
*/
public Context(Position position, MarkupDocBuilder docBuilder, String securitySchemeName, SecuritySchemeDefinition securityScheme) {
super(docBuilder);
Validate.inclusiveBetween(Position.SECURITY_SCHEME_BEFORE, Position.SECURITY_SCHEME_AFTER, position);
Validate.notNull(securitySchemeName);
Validate.notNull(securityScheme);
this.position = position;
this.securitySchemeName = securitySchemeName;
this.securityScheme = securityScheme;
}
public Position getPosition() {
return position;
}
public Optional<String> getSecuritySchemeName() {
return Optional.fromNullable(securitySchemeName);
}
public Optional<SecuritySchemeDefinition> getSecurityScheme() {
return Optional.fromNullable(securityScheme);
}
}
public SecurityDocumentExtension() {
}
public abstract void apply(Context context);
/**
* Returns title level offset from 1 to apply to content
* @param context context
* @return title level offset
*/
protected int levelOffset(Context context) {
int levelOffset;
switch (context.position) {
case DOCUMENT_BEFORE:
case DOCUMENT_AFTER:
levelOffset = 0;
break;
case DOCUMENT_BEGIN:
case DOCUMENT_END:
case SECURITY_SCHEME_BEFORE:
case SECURITY_SCHEME_AFTER:
levelOffset = 1;
break;
case SECURITY_SCHEME_BEGIN:
case SECURITY_SCHEME_END:
levelOffset = 2;
break;
default:
throw new RuntimeException(String.format("Unknown position '%s'", context.position));
}
return levelOffset;
}
}

View File

@@ -1,31 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.spi;
import io.swagger.models.Swagger;
/**
* SwaggerModelExtension extension point can be used to preprocess the Swagger model.
*/
public abstract class SwaggerModelExtension extends AbstractExtension {
public SwaggerModelExtension() {
}
public abstract void apply(Swagger swagger);
}

View File

@@ -1,59 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.utils;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;
public class IOUtils {
private static final Pattern NAME_FORBIDDEN_PATTERN = Pattern.compile("[^0-9A-Za-z-_]+");
/**
* Create a normalized name from an arbitrary string.<br>
* Paths separators are replaced, so this function can't be applied on a whole path, but must be called on each path sections.
*
* @param name current name of the file
* @return a normalized filename
*/
public static String normalizeName(String name) {
String fileName = NAME_FORBIDDEN_PATTERN.matcher(name).replaceAll("_");
fileName = fileName.replaceAll(String.format("([%1$s])([%1$s]+)", "-_"), "$1");
fileName = StringUtils.strip(fileName, "_-");
fileName = fileName.trim();
return fileName;
}
/**
* Create a reader from specified {@code source}.<br>
* Returned reader should be explicitly closed after use.
*
* @param uri source URI
* @return reader
* @throws IOException if the connection cannot be opened
*/
public static Reader uriReader(URI uri) throws IOException {
return new BufferedReader(new InputStreamReader(uri.toURL().openStream(), StandardCharsets.UTF_8));
}
}

View File

@@ -1,79 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup.utils;
import java.net.URI;
import java.nio.file.Paths;
public class URIUtils {
/**
* Return URI parent
* @param uri source URI
* @return URI parent
*/
public static URI uriParent(URI uri) {
return uri.getPath().endsWith("/") ? uri.resolve("..") : uri.resolve(".");
}
/**
* Convert an URI without a scheme to a file scheme.
*
* @param uri the source URI
* @return the converted URI
*/
public static URI convertUriWithoutSchemeToFileScheme(URI uri){
if (uri.getScheme() == null) {
return Paths.get(uri.getPath()).toUri();
}
return uri;
}
/**
* Creates a URI from a String representation of a URI or a Path.
*
* @param input String representation of a URI or a Path.
* @return the URI
*/
public static URI create(String input){
if(isFile(input) || isURL(input)){
return URI.create(input);
}else{
return Paths.get(input).toUri();
}
}
/**
* Check if the input is a String representation of a file URI.
*
* @param input the String
* @return true if the input is a String representation of a file URI.
*/
private static boolean isFile(String input) {
return input.toLowerCase().startsWith("file");
}
/**
* Check if the input is a String representation of a URL.
*
* @param input the String
* @return true if the input is a String representation of a URL.
*/
private static boolean isURL(String input) {
return input.toLowerCase().startsWith("http");
}
}

View File

@@ -1,24 +0,0 @@
swagger2markup.markupLanguage=ASCIIDOC
swagger2markup.swaggerMarkupLanguage=MARKDOWN
swagger2markup.generatedExamplesEnabled=false
swagger2markup.operationExtensionsEnabled=false
swagger2markup.definitionExtensionsEnabled=false
swagger2markup.separatedDefinitionsEnabled=false
swagger2markup.separatedOperationsEnabled=false
swagger2markup.pathsGroupedBy=AS_IS
swagger2markup.outputLanguage=EN
swagger2markup.inlineSchemaEnabled=true
swagger2markup.interDocumentCrossReferencesEnabled=false
swagger2markup.flatBodyEnabled=false
swagger2markup.overviewDocument=overview
swagger2markup.pathsDocument=paths
swagger2markup.definitionsDocument=definitions
swagger2markup.securityDocument=security
swagger2markup.separatedOperationsFolder=operations
swagger2markup.separatedDefinitionsFolder=definitions
swagger2markup.tagOrderBy=NATURAL
swagger2markup.operationOrderBy=NATURAL
swagger2markup.definitionOrderBy=NATURAL
swagger2markup.parameterOrderBy=NATURAL
swagger2markup.propertyOrderBy=NATURAL
swagger2markup.responseOrderBy=NATURAL

View File

@@ -1,56 +0,0 @@
definitions=Definitionen
default_column=Standard
example_column=Beispiel
flags.column=Flags
flags.required=Required
flags.optional=Optional
flags.read_only=Read-only
flags.read_write=Read-write
schema_column=Schema
name_column=Name
description_column=Beschreibung
headers_column=Headers
scopes_column=Scopes
produces=Erzeugt
consumes=Verarbeitet
tags=Tags
overview=<EFBFBD>bersicht
current_version=Aktuelle Version
version=Version
contact_information=Kontaktinformationen
contact_name=Kontakt
contact_email=Kontakt E-Mail
license_information=Lizenzinformationen
license=Linzenz
license_url=Lizenz-URL
terms_of_service=Nutzungsbedingungen
uri_scheme=URI Schema
host=Host
base_path=Basis-Pfad
schemes=Schemata
security_name=
security_type=Typ
security_in=In
security_flow=Flow
security_authorizationUrl=Token URL
security_tokenUrl=Token URL
paths=Pfade
resources=Ressourcen
security=Sicherheit
body_parameter=Body Parameter
parameters=Parameter
responses=Antworten
response=Antwort
request=Anfrage
example_request=Beispiel HTTP Anfrage
example_response=Beispiel HTTP Antwort
type_column=Typ
http_code_column=HTTP Code
parameter=Parameter
unknown=Unbekannt
no_content=Kein Inhalt
operation.deprecated=Diese Operation ist veraltet.
polymorphism.column=Polymorphism
polymorphism.discriminator=Discriminator
polymorphism.nature.INHERITANCE=Inheritance
polymorphism.nature.COMPOSITION=Composition

View File

@@ -1,60 +0,0 @@
definitions=Definitions
default_column=Default
example_column=Example
flags.column=Flags
flags.required=Required
flags.optional=Optional
flags.read_only=Read-only
flags.read_write=Read-write
schema_column=Schema
name_column=Name
description_column=Description
headers_column=Headers
scopes_column=Scopes
produces=Produces
consumes=Consumes
tags=Tags
overview=Overview
current_version=Version information
version=Version
contact_information=Contact information
contact_name=Contact
contact_email=Contact Email
license_information=License information
license=License
license_url=License URL
terms_of_service=Terms of service
uri_scheme=URI scheme
host=Host
base_path=BasePath
schemes=Schemes
security_type=Type
security_name=Name
security_in=In
security_flow=Flow
security_authorizationUrl=Token URL
security_tokenUrl=Token URL
paths=Paths
resources=Resources
security=Security
parameters=Parameters
body_parameter=Body parameter
responses=Responses
response=Response
request=Request
example_request=Example HTTP request
example_response=Example HTTP response
type_column=Type
http_code_column=HTTP Code
parameter=Parameter
unknown=Unknown
no_content=No Content
operation.deprecated=This operation is deprecated.
polymorphism.column=Polymorphism
polymorphism.discriminator=Discriminator
polymorphism.nature.INHERITANCE=Inheritance
polymorphism.nature.COMPOSITION=Composition

View File

@@ -1,60 +0,0 @@
definitions=D\u00E9finitions
default_column=D\u00E9faut
example_column=Exemple
flags.column=Modificateurs
flags.required=Requis
flags.optional=Optionnel
flags.read_only=Lecture seule
flags.read_write=Lecture/\u00E9criture
schema_column=Sch\u00E9ma
name_column=Nom
description_column=Description
headers_column=En-t\u00EAtes
scopes_column=P\u00E9rim\u00E8tre
produces=Produit
consumes=Consomme
tags=Tags
overview=Vue g\u00E9n\u00E9rale
current_version=Information de version
version=Version
contact_information=Information de contact
contact_name=Contact
contact_email=Email de contact
license_information=Information de licence
license=Licence
license_url=Licence URL
terms_of_service=Conditions de service
uri_scheme=Sch\u00E9ma d'URI
host=Serveur
base_path=Chemin de base
schemes=Sch\u00E9ma
security_type=Type
security_name=Nom
security_in=Position
security_flow=Flux
security_authorizationUrl=URL d'autorisation
security_tokenUrl=URL de jeton
paths=Op\u00E9rations
resources=Ressources
security=S\u00E9curit\u00E9
parameters=Param\u00E8tres
body_parameter=Contenu
responses=R\u00E9ponses
response=R\u00E9ponse
request=Requ\u00EAte
example_request=Exemple de requ\u00EAte HTTP
example_response=Exemple de r\u00E9ponse HTTP
type_column=Type
http_code_column=Code HTTP
parameter=Param\u00E8tre
unknown=Unknown
no_content=Pas de contenu
operation.deprecated=Cette op\u00E9ration est obsol\u00E8te.
polymorphism.column=Polymorphisme
polymorphism.discriminator=Discriminateur
polymorphism.nature.INHERITANCE=H\u00E9ritage
polymorphism.nature.COMPOSITION=Composition

View File

@@ -1,60 +0,0 @@
definitions=\u041E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u044F
default_column=\u041F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E
flags.column=Flags
flags.required=\u041E\u0431\u044F\u0437\u0430\u0442\u0435\u043B\u044C\u043D\u043E
flags.optional=Optional
flags.read_only=Read-only
flags.read_write=Read-write
example_column=\u041F\u0440\u0438\u043C\u0435\u0440
schema_column=\u0421\u0445\u0435\u043C\u0430
name_column=\u0418\u043C\u044F
description_column=\u041E\u043F\u0438\u0441\u0430\u043D\u0438\u0435
headers_column=Headers
scopes_column=\u041E\u0431\u043B\u0430\u0441\u0442\u0438 \u043F\u0440\u0438\u043C\u0435\u043D\u0435\u043D\u0438\u044F
produces=\u0412\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442
consumes=\u041F\u0440\u0438\u043D\u0438\u043C\u0430\u0435\u0442
tags=\u0422\u044D\u0433\u0438
overview=\u041E\u0431\u0437\u043E\u0440
current_version=\u0418\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F \u043E \u0432\u0435\u0440\u0441\u0438\u0438
version=\u0412\u0435\u0440\u0441\u0438\u044F
contact_information=\u041A\u043E\u043D\u0442\u0430\u043A\u0442\u043D\u0430\u044F \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F
contact_name=\u041A\u043E\u043D\u0442\u0430\u043A\u0442
contact_email=Email \u043A\u043E\u043D\u0442\u0430\u043A\u0442\u0430
license_information=\u0418\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F \u043E \u043B\u0438\u0446\u0435\u043D\u0446\u0438\u0438
license=\u041B\u0438\u0446\u0435\u043D\u0437\u0438\u044F
license_url=URL \u043B\u0438\u0446\u0435\u043D\u0437\u0438\u0438
terms_of_service=\u0423\u0441\u043B\u043E\u0432\u0438\u044F \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F
uri_scheme=\u0421\u0445\u0435\u043C\u0430 URI
host=\u0423\u0437\u0435\u043B
base_path=\u041E\u0441\u043D\u043E\u0432\u043D\u043E\u0439 \u043F\u0443\u0442\u044C
schemes=\u0421\u0445\u0435\u043C\u044B
security_type=\u0422\u0438\u043F
security_name=\u0418\u043C\u044F
security_in=\u0421\u043E\u0434\u0435\u0440\u0436\u0438\u0442\u0441\u044F \u0432
security_flow=\u041F\u043E\u0442\u043E\u043A
security_authorizationUrl=URL \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438
security_tokenUrl=URL \u0442\u043E\u043A\u0435\u043D\u0430
paths=\u041F\u0443\u0442\u0438
resources=\u041E\u0442\u0432\u0435\u0442\u044B
security=\u0411\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E\u0441\u0442\u044C
response=\u041E\u0442\u0432\u0435\u0442
request=\u0417\u0430\u043F\u0440\u043E\u0441
parameters=\u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B
body_parameter=\u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440 \u0442\u0435\u043B\u0430 \u0437\u0430\u043F\u0440\u043E\u0441\u0430
responses=\u041E\u0442\u0432\u0435\u0442\u044B
example_request=\u041F\u0440\u0438\u043C\u0435\u0440 HTTP \u0437\u0430\u043F\u0440\u043E\u0441\u0430
example_response=\u041F\u0440\u0438\u043C\u0435\u0440 HTTP \u0437\u0430\u043F\u0440\u043E\u0441\u0430
type_column=\u0422\u0438\u043F
http_code_column=HTTP \u043A\u043E\u0434
parameter=\u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440
unknown=Unknown
no_content=\u0411\u0435\u0437 \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0433\u043E
operation.deprecated=\u042D\u0442\u0430 \u043E\u043F\u0435\u0440\u0430\u0446\u0438\u044F \u0443\u0441\u0442\u0430\u0440\u0435\u043B\u0430.
polymorphism.column=Polymorphism
polymorphism.discriminator=Discriminator
polymorphism.nature.INHERITANCE=Inheritance
polymorphism.nature.COMPOSITION=Composition

View File

@@ -1,60 +0,0 @@
definitions=Tan\u0131mlar
default_column=Varsay\u0131lan
example_column=\u00D6rnek
flags.column=Bayraklar
flags.required=Gerekli
flags.optional=Opsiyonel
flags.read_only=Sadece okuma
flags.read_write=Okuma ve yazma
schema_column=\u015Eema
name_column=\u0130sim
description_column=A\u00E7\u0131klama
headers_column=Ba\u015Fl\u0131klar
scopes_column=Kapsamlar
produces=\u00DCretilenler
consumes=Kullan\u0131lanlar
tags=Etiketler
overview=Genel Bak\u0131\u015F
current_version=Versiyon bilgisi
version=Versiyon
contact_information=\u0130leti\u015Fim bilgisi
contact_name=\u0130leti\u015Fim
contact_email=\u0130leti\u015Fim E-postas\u0131
license_information=Lisans bilgisi
license=Lisans
license_url=Lisans adresi
terms_of_service=Kullan\u0131m ko\u015Fullar\u0131
uri_scheme=URI \u015Femas\u0131
host=Sunucu
base_path=K\u00F6k Dizin
schemes=\u015Eemalar
security_type=Tip
security_name=\u0130sim
security_in=Yer
security_flow=Ak\u0131\u015F
security_authorizationUrl=Yetkilendirme adresi
security_tokenUrl=Token adresi
paths=Dizinler
resources=Kaynaklar
security=G\u00FCvenlik
parameters=Parametreler
body_parameter=G\u00F6vde parametresi
responses=Cevaplar
response=Cevap
request=\u0130stek
example_request=\u00D6rnek HTTP iste\u011Fi
example_response=\u00D6rnek HTTP cevab\u0131
type_column=Tip
http_code_column=HTTP Kodu
parameter=Parametre
unknown=Bilinmeyen
no_content=\u0130\u00E7erik yok
operation.deprecated=Bu i\u015Flem \u00F6nerilmemektedir.
polymorphism.column=\u00C7okbi\u00E7imlilik
polymorphism.discriminator=Ayr\u0131\u015Ft\u0131r\u0131c\u0131
polymorphism.nature.INHERITANCE=Kal\u0131t\u0131m
polymorphism.nature.COMPOSITION=Birle\u015Ftirme

View File

@@ -1,530 +0,0 @@
/*
* Copyright 2016 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.swagger2markup;
import io.github.swagger2markup.assertions.DiffUtils;
import io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.assertj.core.api.BDDAssertions.assertThat;
public class AsciidocConverterTest {
private static final Logger LOG = LoggerFactory.getLogger(AsciidocConverterTest.class);
private static final String[] EXPECTED_FILES = new String[]{"definitions.adoc", "overview.adoc", "paths.adoc", "security.adoc"};
private List<String> expectedFiles;
@Before
public void setUp(){
expectedFiles = new ArrayList<>(asList(EXPECTED_FILES));
}
@Test
public void testSwagger2AsciiDocConversionAsString() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
//When
String asciiDocAsString = Swagger2MarkupConverter.from(file).build()
.toString();
//Then
assertThat(asciiDocAsString).isNotEmpty();
}
@Test
public void testSwagger2AsciiDocConversion() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/default");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConverter.from(file).build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
assertThat(files).hasSize(4).containsAll(expectedFiles);
Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/default").toURI());
DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversion.html");
}
@Test
public void testSwagger2AsciiDocConversionInstagram() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_instagram.yaml").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/instagram");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConverter.from(file).build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
assertThat(files).hasSize(4).containsAll(expectedFiles);
Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/instagram").toURI());
DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionInstagram.html");
}
@Test
public void testSwagger2AsciiDocConversionWithInterDocumentCrossReferences() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/idxref");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withInterDocumentCrossReferences()
.build();
Swagger2MarkupConverter.from(file).withConfig(config).build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
assertThat(files).hasSize(4).containsAll(expectedFiles);
Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/idxref").toURI());
DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionWithInterDocumentCrossReferences.html");
}
@Test
public void testSwagger2AsciiDocConversionFromString() throws IOException, URISyntaxException {
//Given
String swaggerJsonString = IOUtils.toString(getClass().getResourceAsStream("/yaml/swagger_petstore.yaml"));
Path outputDirectory = Paths.get("build/test/asciidoc/default");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConverter.from(swaggerJsonString).build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
assertThat(files).hasSize(4).containsAll(expectedFiles);
Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/default").toURI());
DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversion.html");
}
@Test
public void testSwagger2AsciiDocConversionWithExamples() throws IOException, URISyntaxException {
//Given
String swaggerJsonString = IOUtils.toString(getClass().getResourceAsStream("/json/swagger_examples.json"));
Path outputDirectory = Paths.get("build/test/asciidoc/examples");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withoutInlineSchema()
.build();
Swagger2MarkupConverter.from(swaggerJsonString)
.withConfig(config)
.build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
assertThat(files).hasSize(4).containsAll(expectedFiles);
Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/examples").toURI());
DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionWithExamples.html");
}
@Test
public void testSwagger2AsciiDocConversionWithGeneratedExamples() throws IOException, URISyntaxException {
//Given
String swaggerJsonString = IOUtils.toString(getClass().getResourceAsStream("/json/swagger_examples.json"));
Path outputDirectory = Paths.get("build/test/asciidoc/generated_examples");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withGeneratedExamples()
.build();
Swagger2MarkupConverter.from(swaggerJsonString)
.withConfig(config)
.build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
assertThat(files).hasSize(4).containsAll(expectedFiles);
Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/generated_examples").toURI());
DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionWithGeneratedExamples.html");
}
@Ignore("swagger-parser-1.0.21 ignore Location def because it's referenced from an external ref (ExternalLocation)")
@Test
public void testSwagger2AsciiDocWithInlineSchema() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_inlineSchema.yaml").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/inline_schema");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.build();
Swagger2MarkupConverter.from(file)
.withConfig(config)
.build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
assertThat(files).hasSize(4).containsAll(expectedFiles);
Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/inline_schema").toURI());
DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocWithInlineSchema.html");
}
@Ignore("swagger-parser-1.0.21 ignore Location def because it's referenced from an external ref (ExternalLocation)")
@Test
public void testSwagger2AsciiDocWithInlineSchemaAndFlatBody() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_inlineSchema.yaml").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/inline_schema_flat_body");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withFlatBody()
.build();
Swagger2MarkupConverter.from(file)
.withConfig(config)
.build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
assertThat(files).hasSize(4).containsAll(expectedFiles);
Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/inline_schema_flat_body").toURI());
DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocWithInlineSchemaAndFlatBody.html");
}
@Test
public void testSwagger2AsciiDocGroupedByTags() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/group_by_tags");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withPathsGroupedBy(GroupBy.TAGS)
.build();
Swagger2MarkupConverter.from(file)
.withConfig(config)
.build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
assertThat(files).hasSize(4).containsAll(expectedFiles);
Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/group_by_tags").toURI());
DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocGroupedByTags.html");
}
@Test
public void testSwagger2AsciiDocGroupedByTagsWithMissingTag() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/json/swagger_missing_tag.json").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/generated");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
try {
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withPathsGroupedBy(GroupBy.TAGS)
.build();
Swagger2MarkupConverter.from(file)
.withConfig(config)
.build()
.toFolder(outputDirectory);
// If NullPointerException was not thrown, test would fail the specified message
failBecauseExceptionWasNotThrown(NullPointerException.class);
} catch (Exception e) {
assertThat(e).hasMessage("Can't GroupBy.TAGS > Operation 'updatePet' has not tags");
}
}
@Test
public void testSwagger2AsciiDocConversionDoesNotContainUriScheme() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_should_not_contain_uri_scheme.yaml").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/generated");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConverter.from(file).build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
assertThat(files).hasSize(4).containsAll(expectedFiles);
assertThat(new String(Files.readAllBytes(outputDirectory.resolve("overview.adoc"))))
.doesNotContain("=== URI scheme");
}
@Test
public void testSwagger2AsciiDocConversionContainsUriScheme() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_should_contain_uri_scheme.yaml").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/generated");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConverter.from(file).build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
assertThat(files).hasSize(4).containsAll(expectedFiles);
assertThat(new String(Files.readAllBytes(outputDirectory.resolve("overview.adoc"))))
.contains("=== URI scheme");
}
@Test
public void testSwagger2AsciiDocConversionWithSeparatedDefinitions() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/generated");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withSeparatedDefinitions()
.build();
Swagger2MarkupConverter.from(file).withConfig(config).build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
expectedFiles.add("definitions");
assertThat(files).hasSize(5).containsAll(expectedFiles);
Path definitionsDirectory = outputDirectory.resolve("definitions");
String[] definitions = definitionsDirectory.toFile().list();
assertThat(definitions).hasSize(5).containsAll(
asList("Category.adoc", "Order.adoc", "Pet.adoc", "Tag.adoc", "User.adoc"));
}
@Test
public void testSwagger2AsciiDocConversionWithSeparatedOperations() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/generated");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withSeparatedOperations()
.build();
Swagger2MarkupConverter.from(file).withConfig(config).build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
expectedFiles.add("operations");
assertThat(files).hasSize(5).containsAll(expectedFiles);
Path pathsDirectory = outputDirectory.resolve("operations");
String[] paths = pathsDirectory.toFile().list();
assertThat(paths).hasSize(18);
}
@Test
public void testSwagger2AsciiDocConversionWithRussianOutputLanguage() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/generated");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withOutputLanguage(Language.RU)
.build();
Swagger2MarkupConverter.from(file)
.withConfig(config)
.build()
.toFolder(outputDirectory);
//Then
assertThat(new String(Files.readAllBytes(outputDirectory.resolve("definitions.adoc")), Charset.forName("UTF-8")))
.contains("== Определения");
}
@Test
public void testSwagger2AsciiDocConversionWithFrenchOutputLanguage() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/generated");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withOutputLanguage(Language.FR)
.build();
Swagger2MarkupConverter.from(file)
.withConfig(config)
.build()
.toFolder(outputDirectory);
//Then
assertThat(new String(Files.readAllBytes(outputDirectory.resolve("overview.adoc")), Charset.forName("UTF-8")))
.contains("== Sch\u00E9ma d'URI");
}
@Test
public void testSwagger2AsciiDocConversionWithMaps() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/json/swagger_maps.json").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/maps");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.build();
Swagger2MarkupConverter.from(file)
.withConfig(config)
.build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
assertThat(files).hasSize(4).containsAll(expectedFiles);
Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/maps").toURI());
DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionWithMaps.html");
}
@Test
public void testSwagger2AsciiDocConversionWithEnums() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/json/swagger_enums.json").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/enums");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.build();
Swagger2MarkupConverter.from(file)
.withConfig(config)
.build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
assertThat(files).hasSize(4).containsAll(expectedFiles);
Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/enums").toURI());
DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionWithEnums.html");
}
@Test
public void testSwagger2AsciiDocConversionWithPolymorphism() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/json/swagger_polymorphism.json").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/polymorphism");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.build();
Swagger2MarkupConverter.from(file)
.withConfig(config)
.build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
assertThat(files).hasSize(4).containsAll(expectedFiles);
Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/polymorphism").toURI());
DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionWithPolymorphism.html");
}
@Test
public void testSwagger2AsciiDocConversionWithPolymorphismAsIsOrdering() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/json/swagger_polymorphism.json").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/polymorphismAsIsOrdering");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withPropertyOrdering(OrderBy.AS_IS)
.build();
Swagger2MarkupConverter.from(file)
.withConfig(config)
.build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
assertThat(files).hasSize(4).containsAll(expectedFiles);
Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/polymorphismAsIsOrdering").toURI());
DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionWithPolymorphismAsIsOrdering.html");
}
@Test
public void testSwagger2AsciiDocConversionWithResponseHeaders() throws IOException, URISyntaxException {
//Given
Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_response_headers.yaml").toURI());
Path outputDirectory = Paths.get("build/test/asciidoc/response_headers");
FileUtils.deleteQuietly(outputDirectory.toFile());
//When
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.build();
Swagger2MarkupConverter.from(file)
.withConfig(config)
.build()
.toFolder(outputDirectory);
//Then
String[] files = outputDirectory.toFile().list();
assertThat(files).hasSize(4).containsAll(expectedFiles);
Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/response_headers").toURI());
DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testSwagger2AsciiDocConversionWithResponseHeaders.html");
}
}

Some files were not shown because too many files have changed in this diff Show More