Compare commits

...

358 Commits

Author SHA1 Message Date
Robert Winkler
63b5cd3bfb Release 1.3.0 2017-02-20 08:37:02 +01:00
Robert Winkler
12e851c127 Refactored Swagger2MarkupConfigBuilder 2017-02-03 09:33:49 +01:00
kruffin
20fa72b613 Multi-Valued Dynamic Content Folders (#240)
* Adds in the capability to have array valued properties. Mostly only affects extensions that may
need this. It is disabled by default and should work the same as it currently does. Array values
can be enabled by setting a separator character in the "swagger2markup.documentFolderSeparator"
configuration attribute.

* Modifications from code review:

* Altered the "documentFolderSeparator" name to "listDelimiter"
* Added an additional property to enable/disable the list delimiter "listDelimiterEnabled"
* Defaulted the "listDelimiter" to ','
* Updated logic that assumed the configuration was derived from AbstractConfiguration to explicitly check before casting
* Added a couple "withListDelimiter" methods to the builder

* Modifies the list delimiter parsing logic (how the delimiter is determined from properties) to be more
of a Java 8 style.
2017-02-03 09:06:49 +01:00
jbrugge
36bee8070a Fix position reference for parameters table. (#241) 2017-02-02 08:57:04 +01:00
fooinha
9a85612b8a * fix NPE for response headers with relative definitions 2017-01-21 10:34:08 +01:00
Robert Winkler
2bc18f7d90 Updated RELEASENOTES 2017-01-19 14:24:41 +01:00
Robert Winkler
6f6428543d The Number Formatter must use the Locale of the Swagger2MarkupConfig output language. 2017-01-19 14:17:17 +01:00
Robert Winkler
d03087c1b8 Fixed version in changelog 2017-01-19 14:00:39 +01:00
Robert Winkler
d2d47cf8ee Updated javslang from 2.0.4 to 2.0.5
Updated paleo-core from 0.10.1 to 0.10.2
Updated swagger-parser from v1.0.23 to v1.0.25
2017-01-19 13:59:23 +01:00
Robert Winkler
7a0f4490de Updated copyright statement 2017-01-19 11:30:50 +01:00
Cas Eliëns
d2b3c9472a Close #180. 2017-01-19 10:24:04 +01:00
Cas Eliëns
3a0b9a00a3 Improve generated examples for arrays 2017-01-19 10:24:04 +01:00
Cas Eliëns
d5cf4ad9e5 Add unit test for #180 2017-01-19 10:24:04 +01:00
Cas Eliëns
2899b2f263 Use shorter sorting syntax and update javadoc 2017-01-13 14:12:41 +01:00
Cas Eliëns
7475321e97 Add ISAAC to 'Companies who use Swagger2Markup' 2017-01-13 14:12:33 +01:00
Cas Eliëns
88a24d7bdd Add space between schema type and format 2017-01-09 12:19:41 +01:00
Robert Winkler
f798a51edc Release v1.2.0 2017-01-05 14:27:53 +01:00
Robert Winkler
81edab38f3 The notBlank validation of the type should tell which parameter is not valid. 2017-01-03 15:58:43 +01:00
Robert Winkler
039607a294 Updated version to 1.2.0-SNAPSHOT 2017-01-03 15:27:32 +01:00
Cas Eliëns
2f33522e6d Issue #214 Added support for page breaks (#226)
* Added support for page breaks
* Added documentation and config file support for page breaks and regex
2017-01-03 11:21:31 +01:00
Cas Eliëns
76c54a713a use raw JSON object instead of converting to string 2017-01-02 13:47:02 +01:00
Cas Eliëns
dcebed2d42 split reused code into methods 2017-01-02 13:47:02 +01:00
Cas Eliëns
dbf9afa8da Remove unused import 2017-01-02 13:47:02 +01:00
Cas Eliëns
f7f397b5f2 Improve printing for different ways of defining examples 2017-01-02 13:47:02 +01:00
Cas Eliëns
44f852ad42 Improve example printing for $ref'd examples 2017-01-02 13:47:02 +01:00
Cas Eliëns
e1be2f2130 Great Expectations 2017-01-02 13:47:02 +01:00
Cas Eliëns
8468607703 Improve example rendering for hardcoded examples 2017-01-02 13:47:02 +01:00
Cas Eliëns
f981318142 Example responses now display correctly 2017-01-02 13:47:02 +01:00
Cas Eliëns
e1d0d7b293 Add FIXME comment 2017-01-02 13:47:02 +01:00
Cas Eliëns
d118a0cf74 Further work on Swagger2Markup/swagger2markup#223 2017-01-02 13:47:02 +01:00
Cas Eliëns
7cb1095465 Begin work on Swagger2Markup/swagger2markup#223 2017-01-02 13:47:02 +01:00
Cas Eliëns
595b885b9a Close Swagger2Markup/swagger2markup#220 2016-12-20 14:07:27 +01:00
Cas Eliëns
b1c219bc1b Remove unused code, optimize imports, fix Codacy issues
* Begin working on Swagger2Markup/swagger2markup#215

* Begin looking for methods that need to be modified for Swagger2Markup/swagger2markup#215

* Begin working on Swagger2Markup/swagger2markup#215

* Begin looking for methods that need to be modified for Swagger2Markup/swagger2markup#215

* Work on implementing regex sorting

* Add regex ordering translations and unit test

* Improve Regex grouping

* Make regex sorting test more like a real-world example

* Remove unused imports

* Improve code style consistency

* Improve code style consistency

* Remove empty statement

* Resolve some Codacy issues

* Remove empty constructors

* Remove unused fields

* Merge nested IF statements

* Improve method scopes

* Remove unused classes

* Remove unused imports

* Remove fixed TODO comment

* Fix codacy issues

* Fix codacy issues (reverted from commit 43f27e7fc6)

* Improve code style consistency

* Resolve some Codacy issues

* Remove empty constructors

* Remove unused fields

* Merge nested IF statements

* Improve method scopes

* Remove unused classes

* Remove unused imports

* Remove fixed TODO comment

* Fix codacy issues
2016-12-19 16:04:17 +01:00
Cas Eliëns
852b2ac3b4 PR#218 Improve code style consistency
Improved code style consistency
2016-12-13 10:44:31 +01:00
Cas Eliëns
937cded2aa Issue #215: Path grouping via a RegEx pattern
* Begin working on Swagger2Markup/swagger2markup#215

* Begin looking for methods that need to be modified for Swagger2Markup/swagger2markup#215

* Begin working on Swagger2Markup/swagger2markup#215

* Begin looking for methods that need to be modified for Swagger2Markup/swagger2markup#215

* Work on implementing regex sorting

* Add regex ordering translations and unit test

* Improve Regex grouping

* Make regex sorting test more like a real-world example

* Remove unused imports
2016-12-13 09:58:12 +01:00
Robert Winkler
022d2453d2 Issee #216: Replace slash with system file separator in unit tests. 2016-12-09 09:17:55 +01:00
Robert Winkler
e5a187cc24 Updated version to 1.1.2-SNAPSHOT 2016-11-30 09:18:22 +01:00
Robert Winkler
83bb63321a Updated markup-document-builder from 1.0.0 to 1.1.0 2016-11-30 08:20:04 +01:00
Robert Winkler
cd5b5c9240 Refactored ParameterAdapter and created MarkupDocBuilderUtils. 2016-11-18 12:36:39 +01:00
Robert Winkler
2096ec0d5d Refactored ParameterAdapter and moved ParameterAdapter and PropertyAdapter into a new package. 2016-11-16 12:54:32 +01:00
Robert Winkler
25d4311237 Added a modularized Swagger spec test 2016-11-16 12:54:03 +01:00
Robert Winkler
7e07c2fc81 Fixed method name in DefinitionsDocument 2016-11-15 14:50:45 +01:00
Robert Winkler
5a8a618e6b Refactored document resolver and added tests. 2016-11-15 14:47:11 +01:00
Robert Winkler
f072fc99b9 Refactored Documents. Documents are also components now and can be composed of components. 2016-11-15 11:12:17 +01:00
Robert Winkler
54e881fc58 Fixed wrong import in SecuritySchemeComponent 2016-11-14 16:14:16 +01:00
Robert Winkler
cd6a3ed724 Refactored Components to be more functional. 2016-11-14 16:08:24 +01:00
Robert Winkler
5a00dde912 Refactored Components to be more functional. 2016-11-14 16:02:49 +01:00
Robert Winkler
876d7b2f7b Moved code into BodyParameterComponent 2016-11-11 14:21:43 +01:00
Robert Winkler
4b74ec0e54 Moved code into PathOperationComponent 2016-11-11 13:30:04 +01:00
Robert Winkler
a719e33332 Moved code into SecuritySchemeComponent 2016-11-11 10:29:51 +01:00
Robert Winkler
86a727f097 Refactored DocumentBuilder into components. 2016-11-10 15:48:03 +01:00
Robert Winkler
2670780076 Enhancement #206 Updated to markup-document-builder v1.1.0 which renders bold text as **text** and italic text as __text__. 2016-11-10 12:42:52 +01:00
Robert Winkler
ebf9912269 Bug #205: Fix ordering of operations when grouped by tags. 2016-11-10 12:41:26 +01:00
Robert Winkler
11549ab64e Bug #205: Fix ordering of operations when grouped by tags. 2016-11-10 10:43:12 +01:00
Robert Winkler
d128146952 Added a component API to split a document into components and improve component testability 2016-11-09 16:30:02 +01:00
Robert Winkler
686abd8842 Added a component API to split a document into components and improve component testability 2016-11-09 15:02:28 +01:00
Robert Winkler
551aeed835 Removed ListUtils and changed MapUtils.toKeySet to MapUtils.toSortedMap 2016-11-08 12:28:27 +01:00
Robert Winkler
5b1a1a2bcf Migrated some collections to Javaslang 2016-11-08 10:18:07 +01:00
Robert Winkler
09d2474a9a Added javaslang and paleo-core to improve Table rendering 2016-11-04 15:32:17 +01:00
Robert Winkler
5c00e5493c Removed ExternalLocation model from inlineSchema test. 2016-11-04 15:32:17 +01:00
Robert Winkler
c343af8f5a Updated Gradle to v3.1 2016-11-04 15:32:17 +01:00
yewton
4af7eb5b89 Add support for Japanese 2016-11-02 08:45:42 +01:00
Robert Winkler
aa9a340144 Added a config parameter which allows to prepend the basePath to all paths. 2016-11-01 14:42:46 +01:00
Robert Winkler
35ae68ceee Fixed german and spanish language files 2016-11-01 08:55:04 +01:00
Robert Winkler
560fb4ece6 Added language file for Portuguese (Brazilian) 2016-11-01 08:30:28 +01:00
Cleydson Júnior
8eb494cd5b Converting special characters to ASCII escape codes 2016-11-01 07:05:19 +01:00
Cleydson Júnior
0766336a56 Adding support for Brazilian Portuguese 2016-11-01 07:05:19 +01:00
TzeKai Lee
24352f4d1c Add format tests on request param in query and body 2016-10-28 09:07:56 +02:00
TzeKei Lee
adb0fee973 Added displaying format for string type and definitions only contains string or integer type. 2016-10-28 09:07:56 +02:00
Robert Winkler
13a7113aa7 Fixes #197 Converted ZH-language file from UTF-8 to latin1 using native2asciidoc 2016-10-25 15:25:27 +02:00
Robert Winkler
e882975726 Updated README 2016-10-18 15:27:06 +02:00
Robert Winkler
12209fe923 Updated version to 1.1.0 2016-10-18 15:14:05 +02:00
Robert Winkler
8a63744198 Updated releases notes 2016-10-18 15:11:52 +02:00
James Bassett
5871f0c9b0 Added support for exclusiveMin and exclusiveMax 2016-10-14 07:12:53 +02:00
James Bassett
908f524c64 Updated min/max value to format correctly based on the data type 2016-10-12 08:47:54 +02:00
Francisco José Bermejo Herrera
9fa0ee3def Add support for Spanish language 2016-10-03 13:46:12 +02:00
Robert Winkler
35e9450f74 Updated docker documentation 2016-09-23 10:29:46 +02:00
Robert Winkler
6033ea5a98 Updated docker documentation 2016-09-23 10:21:02 +02:00
Robert Winkler
6f24c3cb39 Merge remote-tracking branch 'origin/master' 2016-09-23 08:54:37 +02:00
Robert Winkler
e975e49d3e Added docker documentation 2016-09-23 08:54:18 +02:00
Robert Winkler
c5cfe10fa6 Merge pull request #187 from KristinaGen/master
update labels_ru
2016-09-14 09:55:56 +02:00
KristinaGen
7c988460f0 update labels_ru 2016-09-13 16:20:57 +02:00
Robert Winkler
21f1892de0 Added chinese language 2016-09-12 10:02:02 +02:00
Robert Winkler
b97344849d Merge pull request #186 from mingkaili/patch-1
labels_zh.properties
2016-09-12 09:49:43 +02:00
Mingkai Lee
935d48d4cc labels_zh.properties
Add chinese labels.properties. Add chinese language.
2016-09-12 10:26:16 +08:00
Robert Winkler
73ba233f9e Merge pull request #181 from iwannayoyo/Remove_empty_columns
eliminate empty columns in tables
2016-08-31 10:20:25 +02:00
Chris Hartman
ff955d392b eliminate empty columns in tables 2016-08-25 16:43:17 -04:00
Robert Winkler
19fde31f67 Merge pull request #177 from mhswisscom/Fix_without_reformat
recursive examples patch without reformatting
2016-08-25 13:49:45 +02:00
Marc Habegger
b3f368ac37 recursive examples patch without reformatting 2016-08-25 13:33:27 +02:00
Robert Winkler
c5efb401b4 Added releaseVersion to build.gradle and documentation.gradle scripts so that the AsciiDoc documentation always refers to the release version and not to the SNAPSHOT version. 2016-08-04 12:10:08 +02:00
Robert Winkler
f386e6ed91 Updated version to 1.0.2-SNAPSHOT 2016-08-04 10:28:30 +02:00
Robert Winkler
55b323c063 Merge pull request #171 from zerok/fix/emptycontact
Allow empty contact objects
2016-08-04 10:25:14 +02:00
Robert Winkler
6f286b52d8 Prepare release v1.0.1 2016-08-04 10:03:08 +02:00
Horst Gutmann
4850673b96 Allow empty contact objects
According to the spec the contact object can be empty (it doesn't have
any required properties). Previously, the markup generation failed in
that situation due to an empty paragraph being generated. This change
fixes that.
2016-08-04 10:00:33 +02:00
Robert Winkler
353af537ba Prepare release v1.0.1 2016-08-04 09:49:35 +02:00
Robert Winkler
2367d86eb7 Merge pull request #170 from zerok/fix/instagram-fenced-code-adoc
Fixes expected output of testSwagger2AsciiDocConversionInstagram
2016-08-03 10:11:43 +02:00
Horst Gutmann
1aec46a57c Fixes expected output of testSwagger2AsciiDocConversionInstagram
The fenced code block in the original specification was previously
converted to something resembling an inline code element, while
the new output now contains an actual code block.

This closes #168.
2016-08-03 09:38:33 +02:00
Robert Winkler
f650fb7b3e Fixed wrong expected test files after merging PR #149 and PR #156 2016-08-02 19:35:27 +02:00
Robert Winkler
568d6a6441 Failed tests shouldn't be ignored 2016-07-30 20:52:54 +02:00
Robert Winkler
630e86cd31 Merge pull request #167 from afdia/master
new property "pathSecuritySectionEnabled" (default: true)
2016-07-30 20:31:14 +02:00
Andreas
0e3e229434 + new property "pathSecuritySectionEnabled" (default: true)
The property decides whether to add the security section for every path
(introduced in pull request #63)
2016-07-30 12:18:12 +02:00
Hugo de Paix de Coeur
f41d1cbcb0 missing FR translations 2016-06-21 13:47:09 +02:00
Hugo de Paix de Coeur
20b653086d Merge pull request #156 from jfiala/master
validation constraints, german translations
2016-06-17 11:16:46 +02:00
Johannes Fiala
ae4cf35de4 validation constraints, german translations (#156) 2016-06-16 19:04:58 +02:00
Johannes Fiala
86fc9a9746 add expected results #160 2016-06-15 22:41:17 +02:00
Johannes Fiala
1b4626d9ca update test cases #160 2016-06-15 22:36:40 +02:00
Johannes Fiala
7528b34ba3 Merge branch 'master' of https://github.com/jfiala/swagger2markup 2016-06-15 22:35:23 +02:00
Johannes Fiala
ebecde1768 update test cases #160 2016-06-15 22:35:00 +02:00
Johannes Fiala
2301de6466 update test examples #160 2016-06-15 22:32:34 +02:00
Johannes Fiala
f7efad2480 Merge branch 'master' of https://github.com/jfiala/swagger2markup
Conflicts:
	src/test/resources/expected/asciidoc/validators/definitions.adoc
	src/test/resources/json/swagger_validators.json
2016-06-15 22:29:12 +02:00
Johannes Fiala
c23bd01495 add more cases to minimum/maximum tests 2016-06-15 22:28:42 +02:00
Johannes Fiala
7e5986237a Merge branch 'master' of https://github.com/jfiala/swagger2markup
Conflicts:
	src/test/resources/expected/asciidoc/validators/definitions.adoc
	src/test/resources/json/swagger_validators.json
2016-06-15 22:25:24 +02:00
Johannes Fiala
1bf26c95e3 Added simple json + test cases for validators #160´ 2016-06-15 22:19:56 +02:00
Johannes Fiala
3888e67d02 Added simple json + test cases for validators #160´ 2016-06-15 22:18:10 +02:00
Johannes Fiala
54e17321b6 Fixed check for description 2016-06-13 12:01:50 +02:00
Johannes Fiala
90f56cfe61 Merge branch 'master' of https://github.com/jfiala/swagger2markup 2016-06-13 11:56:21 +02:00
Johannes Fiala
44e33ad6f3 Fixed line-break issue if no description is present - should always
check for descriptionContent instead of description
2016-06-13 11:55:59 +02:00
Johannes Fiala
65d4e0c225 Merge branch 'master' of https://github.com/jfiala/swagger2markup 2016-06-12 18:53:59 +02:00
Johannes Fiala
d37a374d02 added example for min/max at order.quantity #160 2016-06-12 18:53:12 +02:00
Johannes Fiala
5bb5e5ff29 added new definition of swagger petstore #159 in separate file 2016-06-12 18:20:23 +02:00
Johannes Fiala
de1f84d2aa reseted to original swagger_petstore.yaml, added example for
minlength/maxlength/pattern
2016-06-12 18:12:55 +02:00
Johannes Fiala
aa35c0169c Update swagger_petstore.yaml to current version #159 2016-06-12 17:49:52 +02:00
Johannes Fiala
b53727842a Suggest adding eclipse plugin to support gradle eclipse #158 2016-06-12 17:17:56 +02:00
Johannes Fiala
f88e3d2ed4 added check if minlength equals maxlength 2016-06-12 17:15:07 +02:00
Johannes Fiala
eefda62d99 Added query if minlength equals maxlength #147 2016-06-12 17:08:56 +02:00
Johannes Fiala
592446f714 Removed quotes for Minlength/Maxlength #147 2016-06-12 17:05:45 +02:00
Johannes Fiala
3275a07325 German translations - fine tuning #157 2016-06-12 16:56:03 +02:00
Johannes Fiala
1c2b9eee26 validation constraints don't appear in generated docs #147 2016-06-12 16:50:25 +02:00
Hugo de Paix de Coeur
3a5533447b Merge pull request #149 from filip-owczarzak/Columns-Width-Too-Small
1st column in table extended width in order to avoid text wrapping
2016-06-01 14:59:50 +02:00
Filip Owczarzak
2fcd2d1a79 1st column in tables width set to 2 2016-06-01 13:49:15 +02:00
Robert Winkler
07d878be35 Added release Version to docs 2016-05-29 07:11:25 +02:00
Robert Winkler
7a75d7874b Added release Version to docs 2016-05-28 21:17:42 +02:00
Robert Winkler
99c3044218 Added release Version to docs 2016-05-28 20:49:46 +02:00
Robert Winkler
fec5fb54bb Added release Version to docs 2016-05-28 20:48:34 +02:00
Robert Winkler
031051f1f9 Added release Version to docs 2016-05-28 20:47:52 +02:00
Robert Winkler
d432c398cf Added release Version to docs 2016-05-28 20:35:07 +02:00
Robert Winkler
8eb44c26d2 Added release Version to docs 2016-05-28 20:25:23 +02:00
Robert Winkler
3a76a3e920 Added release Version to docs 2016-05-28 20:24:14 +02:00
Robert Winkler
52e80e7af6 Updated readme 2016-05-28 20:21:00 +02:00
Hugo de Paix de Coeur
1eac6a63d9 set development version to 1.0.1-SNAPSHOT 2016-05-26 16:21:42 +02:00
Hugo de Paix de Coeur
6e379042a0 #152 keep track of properties order in Composed models so that OrderBy.AS_IS works as expected 2016-05-26 13:22:37 +02:00
hdr
8367195315 fixes #150 create empty object when Swagger Parser fails to convert composed items
Added Instagram API conversion to tests next to PetStore
2016-05-26 11:23:26 +02:00
Hugo de Paix de Coeur
7de954958d Merge pull request #151 from johanhammar/master
Fix invalid XML in documentation
2016-05-26 08:24:39 +02:00
Johan Hammar
a161924a7f Fix invalid XML in documentation 2016-05-25 21:24:19 +02:00
hdr
9568f3a960 #148 Removed NPE in ExamplesUtil::exampleMapForProperties 2016-05-24 14:20:37 +02:00
Filip Owczarzak
fdb24fdf33 1st column in table extended width in order to avoid text wrapping 2016-05-24 10:28:12 +02:00
Robert Winkler
3c0f935e99 Merge remote-tracking branch 'origin/master' 2016-05-12 09:54:49 +02:00
Robert Winkler
826f4ff762 Updated images 2016-05-12 09:54:39 +02:00
Robert Winkler
ed926139b8 Updated readme 2016-05-04 21:05:59 +02:00
Robert Winkler
cb23bfe1a4 Updated Bintray badge 2016-05-02 13:22:04 +02:00
Robert Winkler
ab7d355fe4 Prepare release v1.0.0 2016-05-02 13:06:54 +02:00
Robert Winkler
87ccc182f1 Prepare release v1.0.0 2016-04-29 14:12:21 +02:00
Robert Winkler
ff21d7c985 Fixes #136: Moved default value of a property into the description column. 2016-04-19 13:09:03 +02:00
Robert Winkler
b69797ef51 Fixed levelOffset calculation when using paths grouped by TAGS 2016-04-19 10:52:38 +02:00
Robert Winkler
f1614fe81a Fixed levelOffset calculation when using paths grouped by TAGS 2016-04-19 10:38:54 +02:00
Robert Winkler
d5c9116dc7 Merge remote-tracking branch 'origin/master'
Conflicts:
	src/main/java/io/github/swagger2markup/spi/PathsDocumentExtension.java
2016-04-19 10:36:57 +02:00
Robert Winkler
5aaff59f71 Fixed levelOffset calculation when using paths grouped by TAGS 2016-04-19 10:30:57 +02:00
Robert Winkler
a20ed66400 Merge pull request #131 from ozanyildiz/master
Add Turkish language support
2016-04-15 12:24:53 +02:00
Ozan Yildiz
6312c2f3e0 add Turkish language support 2016-04-15 11:35:07 +03:00
Hugo de Paix de Coeur
2e2bd7d6c5 Enable inline schemas by default. No more depth level control. 2016-04-14 17:51:47 +02:00
Hugo de Paix de Coeur
dd7de8fe08 Added new DEFINITION_{BEFORE,AFTER} positions to DefinitionsDocumentExtension 2016-04-14 16:46:53 +02:00
Hugo de Paix de Coeur
934039bcd4 Renamed SecurityDocumentExtension positions DEFINITION -> SECURITY_SCHEME for clarity
Added new SECURITY_SCHEME_{BEFORE,AFTER} positions
2016-04-14 16:38:59 +02:00
Hugo de Paix de Coeur
98efe9543d #130 : Documentation for new PathsDocumentExtension positions 2016-04-14 15:52:24 +02:00
Hugo de Paix de Coeur
b68c0031a7 fix #130 : Supports for new PathsDocumentExtension positions (descriptions, responses, parameters, security) + OPERATION_{BEFORE,AFTER}
Fixed OPERATION_BEGIN hook call location
2016-04-14 15:32:54 +02:00
Hugo de Paix de Coeur
a587899976 Extension documentation : recommend to use different contentPaths for import files extension 2016-04-14 15:32:54 +02:00
Robert Winkler
4528f2aa0e Merge remote-tracking branch 'origin/master' 2016-04-14 12:37:35 +02:00
Robert Winkler
b2e6f498be Fixed credentials 2016-04-14 12:37:23 +02:00
Hugo de Paix de Coeur
d32179009d Created separate doc for extensions
Extensions documents enhancements
reverted to coderay until AsciiDoctor 1.5.5 (supports for highlightjs-langs attribute)
2016-04-14 12:04:17 +02:00
Hugo de Paix de Coeur
c815318972 missing language 2016-04-14 12:04:17 +02:00
Robert Winkler
7cbb52094d Changed documentation source-highlighter back to coderay, because groovy listings look strange with highlight.js 2016-04-13 14:25:12 +02:00
Hugo de Paix de Coeur
7c8dfb520f Dynamic file content extension detailed documentation 2016-04-13 14:05:01 +02:00
Hugo de Paix de Coeur
6395adddb6 Dynamic file content extension detailed documentation 2016-04-13 13:43:20 +02:00
Hugo de Paix de Coeur
01a63f895c always add space at the beginning and at the end of array/map < target type > for symmetry 2016-04-12 20:07:59 +02:00
Hugo de Paix de Coeur
5d2ba5b21e refactored PropertyUtils.getDefaultValue & ParameterUtils.getDefaultValue to return Objects.
default values are now displayed with literalText + Json.pretty
swaggerMarkupDescription now returns null when there's no description.
2016-04-12 19:16:03 +02:00
Hugo de Paix de Coeur
6e4c0c1498 refactored responses header display
fixed tests after column width update
fixed defaultString in swaggerMarkupDescription
2016-04-12 18:50:25 +02:00
Hugo de Paix de Coeur
dce6b4183a update column width using values sum = 20 for better granularity on col width 2016-04-12 18:50:25 +02:00
Hugo de Paix de Coeur
1bf36592ef advanced_usage documentation (cosmetic) 2016-04-12 18:50:25 +02:00
Robert Winkler
24d9218d14 Show stacktrace of TravisCI publishGhPages task 2016-04-12 16:07:09 +02:00
Robert Winkler
9ee6c96a3a Merge remote-tracking branch 'origin/master' 2016-04-12 15:57:10 +02:00
Robert Winkler
507307308d Fixed index.adoc 2016-04-12 15:57:03 +02:00
Hugo de Paix de Coeur
14d4268cc3 advanced_usage documentation (fixed index) 2016-04-12 15:56:24 +02:00
Hugo de Paix de Coeur
aade4453e1 advanced_usage documentation (fixed tests) 2016-04-12 15:51:19 +02:00
Robert Winkler
232a635c06 Merge remote-tracking branch 'origin/master' 2016-04-12 15:46:36 +02:00
Robert Winkler
545cf13584 Publish documentation on each commit 2016-04-12 15:46:26 +02:00
Hugo de Paix de Coeur
b7ef781fda advanced_usage documentation (cosmetic) 2016-04-12 15:06:35 +02:00
Hugo de Paix de Coeur
3f18a446af advanced_usage documentation (with examples) 2016-04-12 14:55:59 +02:00
Hugo de Paix de Coeur
391bb20de2 advanced_usage documentation (with all files) 2016-04-12 14:28:18 +02:00
Hugo de Paix de Coeur
aafac7821c advanced_usage documentation 2016-04-12 14:27:25 +02:00
Hugo de Paix de Coeur
103aef6cd6 issue template fix 2016-04-08 17:44:21 +02:00
Hugo de Paix de Coeur
6282459905 fixed #124 : fix inter-document cross-references in security schemes
Added inter-document cross-references tests in AsciiDoc and Markdown format
2016-04-08 17:39:52 +02:00
Robert Winkler
293132e6a4 Created an issue template 2016-04-08 16:59:18 +02:00
Hugo de Paix de Coeur
0e4b193d70 Use JSON schema title value to name inline schema intermediary objects, or, if not provided, generate a virtual name based on definition/property/parameter/response name
fixed column widths
fixed bug with <> and cross-references
added type to BasicType to clearly distinct type and name
refactored RefType to use referenced type name/uniqueName instead of a copy of them.
2016-04-08 15:44:38 +02:00
Robert Winkler
277e452a73 Changed gitter to slack integration 2016-04-08 14:40:13 +02:00
Hugo de Paix de Coeur
80e96933b0 missing expected files for inline_schema_flat_body test 2016-04-06 22:08:41 +02:00
Hugo de Paix de Coeur
1ab4f8ff6c fixed javadoc 2016-04-06 22:02:52 +02:00
Hugo de Paix de Coeur
9a67581ad9 fixed javadoc 2016-04-06 22:02:01 +02:00
Hugo de Paix de Coeur
9ef34dd853 fixed inlineSchema depth constant 1 -> configured depth level in definitions
fixed tests
2016-04-06 22:00:10 +02:00
Hugo de Paix de Coeur
b37c173e07 fixed inlineSchemas in collections (array and map, recursive collections, and object/collection mix) in parameters, responses and definitions
fixed missing support for withInlineSchemaDepth when withFlatBody enabled
fixed inline definitions unicity with depth > 1
2016-04-06 21:47:18 +02:00
Hugo de Paix de Coeur
105ac545b3 Moved Example column to description content 2016-04-06 19:16:17 +02:00
Hugo de Paix de Coeur
ae3f9aa353 Removed Required column and render required flag in NAME_COLUMN.
Removed header style on columns in tables.
Support for read-only property flags.
2016-04-06 18:15:09 +02:00
Hugo de Paix de Coeur
3e9fca8a0d SecurityDocument : WorkAround AsciiDoctor HTML conversion bug with + on the last paragraph line when using hardbreaks
SecurityDocument : Use italic for informations keys.
2016-04-06 14:27:04 +02:00
Hugo de Paix de Coeur
1a45054b5d fixed missing DOCUMENT_AFTER extension point call
fixed SecurityDocument DEFINITION_BEGIN->DEFINITION_END extension point call
2016-04-06 14:09:23 +02:00
Robert Winkler
be56290257 Updated documentation 2016-04-06 09:32:03 +02:00
Robert Winkler
64195e095b Updated documentation 2016-04-06 09:03:59 +02:00
Robert Winkler
5a33b3473e Merge remote-tracking branch 'origin/master' 2016-04-06 08:12:35 +02:00
Robert Winkler
df23dc09e8 Updated documentation 2016-04-06 08:12:07 +02:00
Robert Winkler
2a3ac1e6d0 Updated readme 2016-04-05 19:08:36 +02:00
Hugo de Paix de Coeur
bad8cde186 missing placeholder quoting 2016-04-05 16:08:07 +02:00
Hugo de Paix de Coeur
d9adcc2016 log normalized operation id to the console for external content, etc ... 2016-04-05 16:08:07 +02:00
Hugo de Paix de Coeur
7b59a069ef escape consume/produce in overview too (#28).
WorkAround AsciiDoctor HTML conversion bug with + on the last paragraph line.
Use italic for overview informations keys.
fixed termsOfService layout.
2016-04-05 16:08:07 +02:00
Robert Winkler
310a2e47b6 Updated documentation 2016-04-05 15:50:52 +02:00
Robert Winkler
954e302467 Updated documentation 2016-04-05 15:46:34 +02:00
Robert Winkler
abb77b7c5f Updated documentation 2016-04-05 15:36:13 +02:00
Robert Winkler
aaac78f985 Merge remote-tracking branch 'origin/master' 2016-04-05 15:05:53 +02:00
Robert Winkler
e959c9ed59 Updated documentation 2016-04-05 15:05:45 +02:00
Hugo de Paix de Coeur
1965110df9 typos 2016-04-05 15:04:39 +02:00
Hugo de Paix de Coeur
1300249555 cosmetic 2016-04-05 15:02:11 +02:00
Hugo de Paix de Coeur
05a4ee230c Remove hand-written definition/operation descriptions from code, to prepare extension (#108) 2016-04-05 14:53:41 +02:00
Robert Winkler
78411de398 Merge remote-tracking branch 'origin/master' 2016-04-05 14:52:49 +02:00
Robert Winkler
e697815c0c Updated documentation 2016-04-05 14:52:43 +02:00
Hugo de Paix de Coeur
fbd22779ee revert buildOperationTitle block from SIDEBAR to LITERAL style
fixed #28 : */* (consume/produce) not escaped
fixed tests
2016-04-05 14:25:01 +02:00
Robert Winkler
b13c57ea35 Merge remote-tracking branch 'origin/master' 2016-04-05 13:40:36 +02:00
Robert Winkler
0b38f2a91c Updated documentation 2016-04-05 13:40:30 +02:00
Robert Winkler
db36397e81 Fixed getRequiredURI and getURI in Swagger2MarkupProperties 2016-04-05 13:40:21 +02:00
Hugo de Paix de Coeur
066fd597da fix bad refactoring in URIUtils 2016-04-05 13:38:06 +02:00
Hugo de Paix de Coeur
e979d2b45b adapt to latest MDB modifications 2016-04-05 13:33:39 +02:00
Robert Winkler
4fa9f0d645 Updated documentation 2016-04-05 13:17:12 +02:00
Robert Winkler
fecf6c6161 Added a check to the static factory method fromPath to check if the input file does exist. 2016-04-05 11:12:46 +02:00
Robert Winkler
7eecba583d Added a static factory method in URIUtils to create a URI from a String representation of a URI or a Path. 2016-04-05 11:06:37 +02:00
Robert Winkler
9c6111da3e Removed checks to the static factory method fromPath to check if the input file does exist and is readable.
They are not working as expected.
2016-04-05 10:46:34 +02:00
Robert Winkler
f10882d14d Fixed checks to the static factory method fromPath to check if the input file does exist and is readable. 2016-04-05 10:25:39 +02:00
Robert Winkler
0ac9e13948 Fixed checks to the static factory method fromPath to check if the input file does exist and is readable. 2016-04-05 10:20:04 +02:00
Robert Winkler
fb3ef974a3 Added checks to the static factory method fromPath to check if the input file does exist and is readable. 2016-04-05 09:19:00 +02:00
Robert Winkler
65522e4569 Fixed static factory method fromUri so that it also excepts URIs without a scheme. 2016-04-05 08:30:59 +02:00
Hugo de Paix de Coeur
ae8961d43c fixed #44 : added a non-regression test 2016-04-04 20:14:52 +02:00
Robert Winkler
c131a8cad8 Merge pull request #123 from Swagger2Markup/features/polymorphism
fixed #22 : Add discriminator field to the output
2016-04-04 20:04:20 +02:00
Hugo de Paix de Coeur
7ad8ef8d18 fixed #22 : Add discriminator field to the output 2016-04-04 19:58:29 +02:00
Hugo de Paix de Coeur
539520903f enhanced maps test using integer with format int32 2016-04-04 17:55:53 +02:00
Hugo de Paix de Coeur
566300a598 fixed missing line breaks in overview document 2016-04-04 17:55:53 +02:00
Robert Winkler
b64bbee4b4 Merge pull request #122 from Swagger2Markup/features/enums
fixes #111 : Enum definition type values not rendered
2016-04-04 17:49:32 +02:00
Robert Winkler
8c005466c6 Updated documentation 2016-04-04 16:37:53 +02:00
Robert Winkler
d222e01466 Updated javadoc of toPath method in Swagger2MarkupConverter. 2016-04-04 16:26:17 +02:00
Hugo de Paix de Coeur
d692f616ba getTypeProperties documentation 2016-04-04 16:25:00 +02:00
Hugo de Paix de Coeur
656ebde58c fixes #111 : Enum definition type values not rendered
getAllProperties logic as been factored in ModelUtils
2016-04-04 16:16:41 +02:00
Robert Winkler
4973f9674a Added Gradle Plugin documentation 2016-04-04 13:55:52 +02:00
Robert Winkler
9fe3bf9ec0 Merge branch 'master' of https://github.com/Swagger2Markup/swagger2markup 2016-04-04 13:36:49 +02:00
Robert Winkler
074794830f Merge pull request #121 from Swagger2Markup/features/maps
fixes #113 : Support for maps (additionalProperties) in parameters, defs and responses
2016-04-04 13:36:17 +02:00
Hugo de Paix de Coeur
1f4fd9f115 cosmetic 2016-04-04 13:35:21 +02:00
Hugo de Paix de Coeur
82ac10c7a5 fixes #113 : Support for maps (additionalProperties) in parameters, definitions and responses 2016-04-04 13:31:56 +02:00
Robert Winkler
505b9047ba Updated javadoc of toPath 2016-04-04 13:04:05 +02:00
Robert Winkler
735123749e Added Gradle Plugin documentation 2016-04-04 12:18:22 +02:00
Robert Winkler
df3c8f51d5 Merge remote-tracking branch 'origin/master' 2016-04-04 12:15:16 +02:00
Robert Winkler
6de159fa7d Moved Swagger2MarkupProperties into another package. 2016-04-04 12:15:08 +02:00
Hugo de Paix de Coeur
119b190585 fixed content extensions positions documentation 2016-04-04 11:31:38 +02:00
Robert Winkler
14c0be59dd Updated documentation 2016-04-04 11:18:16 +02:00
Robert Winkler
fd2ae92663 Updated documentation 2016-04-04 11:16:29 +02:00
Robert Winkler
a57b16504f Added a check that the input file must not be a hidden file. 2016-04-04 10:49:01 +02:00
Robert Winkler
ee36c1b9f3 Added a toPath methods to the Swagger2MarkupConverter which converts the Swagger specification either into a folder or a file. 2016-04-04 10:42:25 +02:00
Robert Winkler
928ec8b325 Added a static factory method "fromURI" method to the Swagger2MarkupConverter 2016-04-04 10:31:43 +02:00
Robert Winkler
3d720f2c81 Merge branch 'master' of https://github.com/Swagger2Markup/swagger2markup 2016-04-04 08:11:03 +02:00
Robert Winkler
040c60a9ba Merged swagger-parser 1.0.18 2016-04-04 08:10:59 +02:00
Robert Winkler
2e874957fb Updated documentation 2016-04-02 20:16:40 +02:00
Robert Winkler
3ed94986ed Updated documentation 2016-04-02 20:09:21 +02:00
Robert Winkler
32f7561e26 Updated documentation 2016-04-02 20:02:07 +02:00
Robert Winkler
dbaaa195b5 Updated documentation 2016-04-02 19:56:11 +02:00
Robert Winkler
7f01e9beaa Updated documentation 2016-04-02 17:44:07 +02:00
Robert Winkler
2e95cf6b25 Updated documentation 2016-04-02 17:24:11 +02:00
Robert Winkler
23314507db Merge pull request #120 from Swagger2Markup/features/sparser-1.0.18
Features/sparser 1.0.18
2016-04-02 13:18:18 +02:00
Hugo de Paix de Coeur
cfbff5402c Reintroduce DOCUMENT_AFTER position for content extensions 2016-04-01 16:22:03 +02:00
Hugo de Paix de Coeur
6c6c625273 use released io.swagger:swagger-compat-spec-parser:1.0.18 2016-04-01 15:16:57 +02:00
Robert Winkler
a66560a255 Updated documentation 2016-04-01 14:59:27 +02:00
Robert Winkler
5ff5fc8f0f Updated documentation 2016-04-01 14:55:53 +02:00
Robert Winkler
f001b5bb7c Updated documentation 2016-04-01 14:53:56 +02:00
Hugo de Paix de Coeur
403b8fcfc7 Merge branch 'master' into features/sparser-1.0.18
# Conflicts:
#	build.gradle
2016-04-01 14:11:34 +02:00
Robert Winkler
456625ae4b Simplified loading of the default properties file. 2016-04-01 13:11:09 +02:00
Robert Winkler
5dd9163610 Merge remote-tracking branch 'origin/master' 2016-04-01 10:38:35 +02:00
Robert Winkler
3953b3328a Added commons-collections4:4.1 2016-04-01 10:38:28 +02:00
Robert Winkler
124be6c37a Added Codacy badge 2016-04-01 10:19:52 +02:00
Robert Winkler
6fc474ac09 Fixed JavaDoc 2016-04-01 10:00:57 +02:00
Robert Winkler
49ccad694e Fixed JavaDoc 2016-03-31 16:30:46 +02:00
Robert Winkler
370fa5eb8d Merge remote-tracking branch 'origin/master' 2016-03-31 16:25:12 +02:00
Robert Winkler
df61f140ca Upgrade to JDK8 2016-03-31 16:25:03 +02:00
Robert Winkler
b80b16d03f Updated readme 2016-03-24 20:08:24 +01:00
Robert Winkler
97c75c306f Updated readme 2016-03-24 20:04:21 +01:00
Robert Winkler
30258c7e75 Updated documentation. 2016-03-23 16:31:33 +01:00
Robert Winkler
e66feb5a27 Updated documentation. 2016-03-23 14:46:16 +01:00
Robert Winkler
972f2c2d6d Updated documentation. 2016-03-23 14:43:05 +01:00
Hugo de Paix de Coeur
fcf46c1588 small doc changes 2016-03-22 17:24:43 +01:00
Robert Winkler
cd38ed01a4 Updated documentation. 2016-03-22 16:38:20 +01:00
Robert Winkler
5f965e6378 Updated documentation. 2016-03-22 16:33:20 +01:00
Robert Winkler
d20bce81f0 Merge remote-tracking branch 'origin/master' 2016-03-21 16:44:52 +01:00
Robert Winkler
d9e2397f48 Updated documentation. 2016-03-21 16:43:42 +01:00
Robert Winkler
6fe35c34be Updated readme 2016-03-19 15:22:01 +01:00
Hugo de Paix de Coeur
05924c5813 Merge branch 'master' into features/sparser-1.0.18
# Conflicts:
#	build.gradle
2016-03-18 15:48:43 +01:00
Robert Winkler
b931d7f3af Fixes #116 Section titles of generated HTTP request/response have the same level 2016-03-18 15:39:03 +01:00
Robert Winkler
5b970eb2c8 Merge remote-tracking branch 'origin/master' 2016-03-18 15:06:24 +01:00
Robert Winkler
52b5bf2361 Renamed operationsGroupedBy to pathsGroupedBy to be backward compatible. 2016-03-18 15:06:17 +01:00
Hugo de Paix de Coeur
8eee21baf0 renamed intoFolder -> toFolder, asString -> toString for consistency 2016-03-18 13:20:36 +01:00
Robert Winkler
e99656704f Merge pull request #114 from ahus1/translation_to_german
translation of labels to German
2016-03-18 13:05:37 +01:00
Alexander Schwartz
235e5b7ddf translation of labels to German 2016-03-18 12:50:27 +01:00
Robert Winkler
69e7992f3e Updated markup-document-builder to 1.0.0-SNAPSHOT 2016-03-18 10:39:14 +01:00
Robert Winkler
29bfddc8d2 DiffUtils assertThatAllFilesAreEqual iterates over the expectedDirectory instead of the actualDirectory now. This allows to check only 2 files instead of always all 4 S2M documents. 2016-03-18 08:22:59 +01:00
Robert Winkler
3fc8a897a1 Removed mavenLocal() in build.gradle. 2016-03-18 08:12:41 +01:00
Hugo de Paix de Coeur
451e377cac inverted actual/expected in DiffUtils.assertThatAllFilesAreEqual for consistency with tests habits 2016-03-17 17:15:44 +01:00
Hugo de Paix de Coeur
6379b3ccf1 fixed #107 : Possibility to write the output into just one file instead of a folder 2016-03-17 17:10:53 +01:00
Hugo de Paix de Coeur
456f27c85b Merge branch 'master' into features/sparser-1.0.18 2016-03-17 15:38:06 +01:00
Hugo de Paix de Coeur
c739649f20 fixed typo bug in withSwaggerMarkupLanguage which was setting the bad markupLanguage variable 2016-03-17 15:37:37 +01:00
Hugo de Paix de Coeur
3dceb21bd5 Merge branch 'master' into features/sparser-1.0.18 2016-03-16 19:16:08 +01:00
Hugo de Paix de Coeur
23331930cc introduced .withSwaggerMarkupLanguage configuration to automatically convert Swagger file description into the target S2M language 2016-03-16 19:13:57 +01:00
Hugo de Paix de Coeur
da48f49a25 Merge branch 'master' into features/sparser-1.0.18 2016-03-16 16:32:36 +01:00
Hugo de Paix de Coeur
3775f26458 fixed refactoring bug in PathsDocumentBuilder::DefinitionDocumentResolverFromOperation 2016-03-16 16:30:20 +01:00
Robert Winkler
365d3278ff Added getRequiredMarkupLanguage method to Swagger2MarkupProperties 2016-03-16 16:09:01 +01:00
Robert Winkler
7cc9742530 Merge remote-tracking branch 'origin/master' 2016-03-16 15:51:01 +01:00
Robert Winkler
0648a9cbea Added two getPath methods to Swagger2MarkupProperties. 2016-03-16 15:50:48 +01:00
Hugo de Paix de Coeur
7766276abc Merge branch 'master' into features/sparser-1.0.18
# Conflicts:
#	build.gradle
2016-03-16 15:50:41 +01:00
Hugo de Paix de Coeur
19bc2dd0e2 moved generated test results to build/test for consistency with MDB 2016-03-16 15:37:37 +01:00
Robert Winkler
6126260aae Added a URIUtils class with a new convertUriWithoutSchemeToFileScheme method. 2016-03-16 15:15:30 +01:00
Robert Winkler
cdd0bc52e2 Added a getRequiredURI and updated the getURI method in Swagger2MarkupProperties 2016-03-16 14:07:24 +01:00
Hugo de Paix de Coeur
ccf3ee8e7d use new MDB .withHeaderColumn 2016-03-16 13:51:55 +01:00
Robert Winkler
54147bbddb Merge remote-tracking branch 'origin/master' 2016-03-16 12:42:33 +01:00
Robert Winkler
914fa2da0f Refactored Swagger2MarkupConfigBuilder to use Apache Commons configuration. 2016-03-16 12:42:27 +01:00
Hugo de Paix de Coeur
d41b14bbff added anchors for operations and definitions in !separated mode too
switched paths anchors to getId() instead of getTitle()
2016-03-16 11:39:37 +01:00
Robert Winkler
354d2167fb Added enum examples to swagger_petstore.yaml. 2016-03-16 08:52:09 +01:00
Hugo de Paix de Coeur
9eb7c671cd Merge branch 'master' into features/sparser-1.0.18 2016-03-15 18:14:48 +01:00
Hugo de Paix de Coeur
aee7708cd1 Use swagger-compat-spec-parser:1.0.18-SNAPSHOT 2016-03-15 18:07:20 +01:00
Robert Winkler
e3f946ecf8 Added missing javadoc to Swagger2MarkupConfig. 2016-03-15 15:51:08 +01:00
Robert Winkler
c25b6be1f3 Moved String constants PROPERTIES_PREFIX and EXTENSION_PREFIX into Swagger2MarkupConfig interfaces 2016-03-15 15:49:27 +01:00
Hugo de Paix de Coeur
eff69079a6 added Swagger2MarkupConfig, Swagger2MarkupExtensionRegistry documentation 2016-03-15 14:44:42 +01:00
Robert Winkler
8d8d4cd5d0 Added a method getExtensionsProperties to Swagger2MarkupConfig and withExtensionProperties to Swagger2MarkupConfigBuilder so that a user is able to configure its Swagger2Markup extension. 2016-03-15 13:42:36 +01:00
Hugo de Paix de Coeur
4bce1234af fixes package paths after massive package refactoring (2/2) 2016-03-15 12:12:44 +01:00
Hugo de Paix de Coeur
d892f0b39d fixes package paths after massive package refactoring 2016-03-15 11:23:52 +01:00
Robert Winkler
831e949d91 Uncommented tests which are not necessary anymore. 2016-03-15 11:04:53 +01:00
Robert Winkler
d48b9c217b The S2MConfig and S2MRegistry are interfaces now so that other users can develop their own implementations and don't have to use our default implementations. 2016-03-15 09:59:32 +01:00
Robert Winkler
124a66aaa9 Merge branch 'master' of https://github.com/Swagger2Markup/swagger2markup 2016-03-15 08:43:31 +01:00
Robert Winkler
08eb6841fc Refactor extension SPI to use the ServiceLoader by default 2016-03-15 08:43:26 +01:00
Hugo de Paix de Coeur
e74ac9fda5 fixes copy code to support last mdb commits 2016-03-14 19:28:07 +01:00
Robert Winkler
d4bbcc3acc Allow to use http proxy settings in unit tests. 2016-03-14 15:43:40 +01:00
Robert Winkler
9655e113c0 Fixed order of examples and security scheme definitions. 2016-03-14 15:43:20 +01:00
Robert Winkler
54c7682f00 Fixed compile issue in Swagger2MarkupConverter 2016-03-14 15:14:56 +01:00
Robert Winkler
7c8efa1060 Fixed failing Swagger2MarkupExtensionRegistryTest after moving the extensions into another repo. 2016-03-14 15:12:14 +01:00
Robert Winkler
0caf2d7a43 Merge remote-tracking branch 'origin/master' 2016-03-14 15:03:31 +01:00
Robert Winkler
533590656f Fixes #110 Move Extensions into swagger2markup-extensions repo 2016-03-14 15:03:19 +01:00
Robert Winkler
fe0fa8a9ce Moved classes from 'io.github.robwin.swagger2markup' to 'io.github.swagger2markup' 2016-03-14 15:01:32 +01:00
Robert Winkler
a85b695c80 Changed artifact group from group = 'io.github.robwin' to 'io.github.swagger2markup'.
Refactored gradle scripts.
2016-03-14 15:00:17 +01:00
Hugo de Paix de Coeur
251a6b7e73 fixes merge from master (missing some convertExample) 2016-03-14 12:10:31 +01:00
Hugo de Paix de Coeur
08b0d085db Merge branch 'master' into features/sparser-1.0.18
# Conflicts:
#	build.gradle
#	src/main/java/io/github/robwin/swagger2markup/Swagger2MarkupConfig.java
2016-03-14 11:43:04 +01:00
Hugo de Paix de Coeur
0b95f35a61 Removes formatting from RU localization 2016-03-14 11:28:23 +01:00
Robert Winkler
4073b7627d Fixes #60: Add support of Response Headers
The description of response headers was not rendered correctly.
2016-03-11 08:37:32 +01:00
Robert Winkler
2c2b599528 Fixed expected result files. 2016-03-10 16:14:31 +01:00
Robert Winkler
eb86d6f1d0 Moved buildDescriptionParagraph method ino MarkupDocumentBuilder so that it can be reused by all other builders. 2016-03-10 15:39:07 +01:00
Robert Winkler
2d74e441dc Replaced colon separator by a static final string. 2016-03-10 15:38:11 +01:00
Robert Winkler
8145dea0d5 Added gh-pages gradle-git plugin. 2016-03-10 15:37:38 +01:00
Robert Winkler
a4a217a223 Fixed security scheme title anchor. 2016-03-10 15:37:03 +01:00
Hugo de Paix de Coeur
4283b2489d Merge branch 'develop' into features/sparser-1.0.18 2016-03-03 18:05:06 +01:00
Hugo de Paix de Coeur
c6e21b9ed1 fixes configuration validators and doc 2016-03-03 18:04:15 +01:00
Hugo de Paix de Coeur
c61a94495f Merge branch 'develop' into features/sparser-1.0.18
# Conflicts:
#	src/main/java/io/github/robwin/swagger2markup/utils/ExamplesUtil.java
2016-03-03 17:49:53 +01:00
Hugo de Paix de Coeur
3e5df92223 Merge branch 'develop' into features/sparser-1.0.18
# Conflicts:
#	src/main/java/io/github/robwin/swagger2markup/utils/ExamplesUtil.java
2016-03-03 14:04:43 +01:00
Hugo de Paix de Coeur
e96dd94ee9 Support Swagger Parser 1.0.18 interfaces changes 2016-03-02 11:57:28 +01:00
378 changed files with 34051 additions and 14300 deletions

3
.gitignore vendored
View File

@@ -3,3 +3,6 @@
.gradle
build
/bin/
/.classpath
/.project
/.settings/

View File

@@ -1,19 +1,18 @@
language: java
jdk:
- oraclejdk7
- 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:
webhooks:
urls:
- https://webhooks.gitter.im/e/9c620e84679284b7d621
on_success: change
on_failure: always
on_start: false
slack: swagger2markup:Zz5kz0SnvtG6aVvZUM8yMkER
env:
global:
- secure: "SPKolgUdjIa/uJ+7/B/GPFlsa8IZg7NuZdFA8zROTaqew/xu+oX7qVGImseeBpPIEPJb02ac6hr7Y3/zvv0GJxIPtIbyDzVh73ImQUhT1ttLYGJfITAWqAPFF7RNNMtuOl3S2DLZ5OMJddkcFp00pa9nyI82Gk47B8GsaGIntAI="
- secure: "nXXuHfvFACZwdiFM3Ta0x/f49N7cAgi0AMkgEnQrh/2xWlvQk2z2ySGJQLkhJ7Wy8LDY7Yt1b1GUt6DlP3PuFFMW/cT4iARewqiJRXZXxUQz8fpTDeTo1nmVmW/zzII6Qj3QHM3NRbR/xDOVSJiT30Hnq2hcCBQJWYsTICmzjRk="
- 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=

5
ISSUE_TEMPLATE Normal file
View File

@@ -0,0 +1,5 @@
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

@@ -2,7 +2,7 @@
: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.bintray.com/packages/robwin/maven/swagger2markup/images/download.svg[link="https://bintray.com/robwin/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"]
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
@@ -18,7 +18,7 @@ http://asciidoctor.org/docs/asciidoc-writers-guide/[AsciiDoc] is preferable to M
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 7.
The project requires at least JDK 8.
== Example
@@ -27,7 +27,7 @@ image::src/docs/asciidoc/images/Swagger2Markup.PNG[]
image::src/docs/asciidoc/images/Swagger2Markup_definitions.PNG[]
== Reference documentation
- http://swagger2markup.readme.io/[Reference Documentation]
- http://swagger2markup.github.io/swagger2markup/1.2.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]
@@ -37,14 +37,6 @@ image::src/docs/asciidoc/images/Swagger2Markup_definitions.PNG[]
Pull requests are welcome.
* New feature https://github.com/Swagger2Markup/swagger2markup/issues/18[Swagger2Markup/swagger2Markup#18] by https://github.com/sg-ad[@sg-ad]: In addition to the definitions.adoc you can also generate separate files for each definition model (ex: person.adoc, address.adoc, purchase.adoc).
* New feature https://github.com/Swagger2Markup/swagger2markup/issues/21[Swagger2Markup/swagger2Markup#21] by https://github.com/redowl[@redowl]: Support for both reference models and composed models.
* New feature https://github.com/Swagger2Markup/swagger2markup/issues/27[Swagger2Markup/swagger2Markup#27] by https://github.com/zmitrok[@zmitrok]: Added a hook to preprocess a Swagger Model before it is converted.
* New feature https://github.com/Swagger2Markup/swagger2markup/issues/48[Swagger2Markup/swagger2Markup#48] by https://github.com/MeteorBoom[@MeteorBoom]: Multi language support.
=== Questions
You can ask questions about Swagger2Markup in https://gitter.im/Swagger2Markup/swagger2markup[Gitter].
@@ -61,6 +53,9 @@ If youd like an enhancement to be made to Swagger2Markup, pull requests are m
* 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]
* https://www.isaac.nl[ISAAC]
* https://www.spreadshirt.de[Spreadshirt]
== License

View File

@@ -78,9 +78,54 @@
=== 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 #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
=== Version 1.0.1
* Enhancement: Support to render validation constraints of properties
* Enhancement: Possibility to disable rendering of the security chapter below operations
== Version 1.1.0
* PR #177: Fixed rendering of recursive examples
* PR #186: Add support for Chinese language
* PR #190: Add support for Spanish language
* PR #192: Updated min/max value to format correctly based on the data type
* PR #193: Added support for exclusiveMin and exclusiveMax
=== Version 1.1.1
* Issue #194: Added a config parameter which allows to prepend the basePath to all paths.
* Updated swagger-parser from v1.0.16 to v1.0.23
* Added javslang v2.0.4 as a dependency
* Added paleo-core v0.10.1 as a dependency
* Updated markup-document-builder from 1.0.0 to 1.1.0
* PR #201: Add support for Brazilian Portuguese language
* PR #202: Add support for Japanese language
* Issue #205: Fixed the option to influence resource ordering
* Issue #198: Chinese chinese language encoding
* Issue #207: Properties that start with an underscore are displayed correctly now
* Refactored Swagger2Markup to use a Component-Based design. A document can be composed of components and components can be composed of other components.
== Version 1.2.0
* Issue #214: Add page break locations
* Issue #223: Improve example rendering
* Issue #215: Add ability to group operations by RegEx
* Added new configuration options: pageBreakLocations, headerRegex
* Added new valid value for configuration headerRegex: REGEX
* Updated markup-document-builder from 1.1.0 to 1.1.1
== Version 1.3.0
* Updated javslang from 2.0.4 to 2.0.5
* Updated paleo-core from 0.10.1 to 0.10.2
* Updated swagger-parser from v1.0.23 to v1.0.25
* Decimal numbers are formatted into locale-specific strings

View File

@@ -7,27 +7,25 @@ buildscript {
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 'org.asciidoctor:asciidoctorj:1.5.2'
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.2'
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.0-SNAPSHOT'
group = 'io.github.robwin'
version = '1.3.0'
ext.releaseVersion = '1.3.0'
group = 'io.github.swagger2markup'
apply plugin: 'java'
apply plugin: 'maven-publish'
apply plugin: 'org.asciidoctor.convert'
apply plugin: 'jacoco'
apply plugin: 'com.github.kt3k.coveralls'
apply plugin: 'com.jfrog.bintray'
apply plugin: "com.jfrog.artifactory"
apply plugin: 'eclipse'
apply from: 'gradle/publishing.gradle'
apply from: 'gradle/coverage.gradle'
apply from: 'gradle/documentation.gradle'
tasks.withType(JavaCompile) {
sourceCompatibility = "1.7"
targetCompatibility = "1.7"
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
options.deprecation = true
options.encoding = 'UTF-8'
options.compilerArgs << "-Xlint:unchecked"
@@ -43,92 +41,30 @@ repositories {
}
dependencies {
compile 'io.github.robwin:markup-document-builder:0.1.6-SNAPSHOT'
compile 'io.swagger:swagger-compat-spec-parser:1.0.17'
compile 'io.github.swagger2markup:markup-document-builder:1.1.1'
compile 'io.swagger:swagger-compat-spec-parser:1.0.25'
compile 'org.apache.commons:commons-configuration2:2.1'
compile 'commons-beanutils:commons-beanutils:1.9.2'
compile 'org.apache.commons:commons-collections4:4.1'
compile 'io.javaslang:javaslang:2.0.5'
compile 'ch.netzwerg:paleo-core:0.10.2'
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:2.2.0'
testCompile 'com.sksamuel.diff:diff:1.1.11'
testCompile 'org.assertj:assertj-core:3.5.2'
testCompile 'io.github.robwin:assertj-diff:0.1.1'
}
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
}
ext {
generatedDocumentation = file('build/docs/asciidoc/generated')
}
asciidoctor {
sources {
include 'index.adoc'
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']
}
backends = ['html5', 'pdf']
attributes = [
doctype: 'book',
toc: 'left',
toclevels: '3',
numbered: '',
sectlinks: '',
sectanchors: '',
hardbreaks: '',
generated: generatedDocumentation
]
systemProperty 'file.encoding', 'UTF-8'
}
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()
}
}
jacocoTestReport {
reports {
xml.enabled = true // coveralls plugin depends on xml format report
html.enabled = true
}
}
tasks.coveralls {
dependsOn 'check'
}
tasks.artifactoryPublish {
dependsOn 'check'
}
task wrapper(type: Wrapper) {
gradleVersion = '2.10'
gradleVersion = '3.3'
}

13
gradle/coverage.gradle Normal file
View File

@@ -0,0 +1,13 @@
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

@@ -0,0 +1,35 @@
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: '',
'release-version': project.releaseVersion
]
}
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.releaseVersion
}
}

View File

@@ -1,24 +1,44 @@
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'
}
def projectArtifactId = 'swagger2markup'
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(
'Built-By': 'Robert Winkler',
'Created-By': System.properties['java.version'] + " (" + System.properties['java.vendor'] + " " + System.properties['java.vm.version'] + ")",
'Build-Date': project.buildDate,
'Build-Time': project.buildTime,
'Specification-Title': projectArtifactId,
'Specification-Version': project.version,
'Implementation-Title': projectArtifactId,
'Implementation-Version': project.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()
)
}
}
@@ -29,35 +49,6 @@ if (!project.hasProperty('gpgPassphrase')) ext.gpgPassphrase = ''
if (!project.hasProperty('ossUser')) ext.ossUser = ''
if (!project.hasProperty('ossPassword')) ext.ossPassword = ''
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'
websiteUrl = 'https://github.com/Swagger2Markup/swagger2markup'
issueTrackerUrl = 'https://github.com/Swagger2Markup/swagger2markup/issues'
vcsUrl = 'https://github.com/Swagger2Markup/swagger2markup.git'
desc = 'A Swagger to Markup (AsciiDoc and Markdown) converter.'
licenses = ['Apache-2.0']
version {
vcsTag = project.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
}
}
}
}
publishing {
publications {
mavenJava(MavenPublication) {
@@ -74,17 +65,17 @@ publishing {
it.scope*.value = 'compile'
}
root.appendNode('name', 'swagger2markup')
root.appendNode('name', project.name)
root.appendNode('packaging', 'jar')
root.appendNode('url', 'https://github.com/Swagger2Markup/swagger2markup')
root.appendNode('description', 'A Swagger to Markup (AsciiDoc and Markdown) converter.')
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', 'https://github.com/Swagger2Markup/swagger2markup/blob/master/LICENSE.txt')
license.appendNode('url', licenseUrl)
license.appendNode('distribution', 'repo')
root.appendNode('scm').appendNode('url', 'https://github.com/Swagger2Markup/swagger2markup.git')
root.appendNode('scm').appendNode('url', scmUrl)
def developers = root.appendNode('developers')
devs.each {
@@ -97,4 +88,64 @@ publishing {
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 +1,6 @@
#Wed Feb 10 11:09:13 CET 2016
#Thu Jan 05 14:27:30 CET 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-bin.zip

51
gradlew vendored
View File

@@ -6,12 +6,30 @@
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# 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
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
@@ -30,6 +48,7 @@ die ( ) {
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
@@ -40,26 +59,11 @@ case "`uname`" in
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=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.
@@ -85,7 +89,7 @@ location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
@@ -157,4 +161,9 @@ function splitJvmOpts() {
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

14
gradlew.bat vendored
View File

@@ -8,14 +8,14 @@
@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 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=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
@@ -46,10 +46,9 @@ echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
@rem Get command-line arguments, handling Windows 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.
@@ -60,11 +59,6 @@ set _SKIP=2
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

View File

@@ -0,0 +1,94 @@
== 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

@@ -0,0 +1,103 @@
== 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-{release-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-{release-version}.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-{release-version}.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-{release-version}.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-{release-version}.jar convert -i /path/to/swagger_petstore.yaml -o /tmp -c /path/to/config.properties
----

View File

@@ -0,0 +1,10 @@
== 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

@@ -0,0 +1,82 @@
== 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

@@ -0,0 +1,13 @@
== Docker image
The Swagger2Markup-CLI has been published as a Docker image on DockerHub.
=== Usage guide
You can pull the Swagger2Markup image as follows:
`docker pull swagger2markup/swagger2markup`
You can convert a Swagger Spec by running a Docker container as follows:
`docker run --rm -v $(pwd):/opt swagger2markup/swagger2markup convert -i /opt/swagger.yaml -f /opt/swagger -c /opt/config.properties`

View File

@@ -0,0 +1,187 @@
== 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

@@ -0,0 +1,117 @@
[[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

@@ -0,0 +1,29 @@
[[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

@@ -0,0 +1,74 @@
[[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,36 +1,71 @@
== Getting started
The project is published in JCenter and Maven Central. If you use Gradle or Maven, you can include Swagger2Markup as follows.
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 {
mavenCentral()
jCenter()
}
compile "io.github.robwin:swagger2markup:{project-version}"
compile "io.github.swagger2markup:swagger2markup:{release-version}"
----
==== Snapshot
[source,groovy]
----
repositories {
maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
}
----
=== Maven
[source,xml, subs="attributes, verbatim"]
==== Release
[source,xml, subs="specialcharacters,attributes"]
----
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
central
<name>bintray</name>
<id>jcenter-releases</id>
<name>jcenter</name>
<url>http://jcenter.bintray.com</url>
</repository>
</repositories>
<dependency>
<groupId>io.github.robwin</groupId>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup</artifactId>
<version>{project-version}</version>
<version>{release-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

@@ -0,0 +1,62 @@
== 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:{release-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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 124 KiB

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

View File

@@ -1,11 +1,11 @@
= Swagger2Markup User Guide
= Swagger2Markup Documentation
Robert Winkler
:toc: left
:toclevels: 3
:source-highlighter: coderay
:numbered:
:hardbreaks:
:revnumber: {project-version}
:revnumber: {release-version}
:revdate: {localdate}
:icons: font
:pagenums:
@@ -16,5 +16,21 @@ 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::docker.adoc[]
include::demo.adoc[]
include::contributing.adoc[]
include::license.adoc[]

View File

@@ -4,20 +4,20 @@ The primary goal of this project is to **simplify the generation of an up-to-dat
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 file into several **AsciiDoc** or **GitHub Flavored Markdown** 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 the __official__ https://github.com/swagger-api/swagger-parser[swagger-parser] and my https://github.com/Swagger2Markup/markup-document-builder[markup-document-builder].
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 7.
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**.
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
.HTML example using AsciiDoctor - path section
image::images/Swagger2Markup.PNG[]
.HTML example using AsciiDoctor - definition section
image::images/Swagger2Markup_definitions.PNG[]

View File

@@ -1,6 +1,6 @@
== License
Copyright 2016 Robert Winkler
Copyright 2017 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

View File

@@ -0,0 +1,86 @@
== 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>{release-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, subs="specialcharacters,attributes"]
----
<build>
<plugins>
<plugin>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup-maven-plugin</artifactId>
<version>{release-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

@@ -0,0 +1,206 @@
== 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, REGEX | 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.pathSecuritySectionEnabled| Optionally disable the security section for path sections | true, false | true
|swagger2markup.anchorPrefix| Optionally prefix all anchors for uniqueness if you want to include generated documents into a global documentation | Any String |
|swagger2markup.basePathPrefixEnabled| Prepend the basePath to all paths | true, false | false
|swagger2markup.headerRegex | Regular expression to use when grouping by RegEx | Any valid RegEx pattern with at least one capture group |
|===
[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
|===
[options="header"]
.Properties which configure page breaking
|===
|Name | Description | Possible Values | Default
|swagger2markup.pageBreakLocations | Specifies where page breaks should be inserted. | BEFORE_OPERATION, BEFORE_OPERATION_DESCRIPTION, BEFORE_OPERATION_PARAMETERS, BEFORE_OPERATION_RESPONSES, BEFORE_OPERATION_CONSUMES, BEFORE_OPERATION_PRODUCES, BEFORE_OPERATION_EXAMPLE_REQUEST, BEFORE_OPERATION_EXAMPLE_RESPONSE, BEFORE_DEFINITION, AFTER_OPERATION, AFTER_OPERATION_DESCRIPTION, AFTER_OPERATION_PARAMETERS, AFTER_OPERATION_RESPONSES, AFTER_OPERATION_CONSUMES, AFTER_OPERATION_PRODUCES, AFTER_OPERATION_EXAMPLE_REQUEST, AFTER_OPERATION_EXAMPLE_RESPONSE, AFTER_DEFINITION | empty
|===
=== 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,764 +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.robwin.swagger2markup;
import com.google.common.base.Function;
import com.google.common.collect.Ordering;
import io.github.robwin.markup.builder.LineSeparator;
import io.github.robwin.markup.builder.MarkupLanguage;
import io.github.robwin.swagger2markup.internal.model.PathOperation;
import io.github.robwin.swagger2markup.internal.utils.IOUtils;
import io.swagger.models.HttpMethod;
import io.swagger.models.parameters.Parameter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.Properties;
public class Swagger2MarkupConfig {
private static final Logger logger = LoggerFactory.getLogger(Swagger2MarkupConfig.class);
private MarkupLanguage markupLanguage;
private boolean generatedExamplesEnabled;
private boolean operationDescriptionsEnabled;
private URI operationDescriptionsUri;
private boolean definitionDescriptionsEnabled;
private URI definitionDescriptionsUri;
private boolean separatedDefinitionsEnabled;
private boolean separatedOperationsEnabled;
private GroupBy operationsGroupedBy;
private Language outputLanguage;
private int inlineSchemaDepthLevel;
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;
public static Builder ofDefaults() {
return new Builder();
}
public static Builder ofProperties(Properties properties) {
return new Builder(properties);
}
/**
* Global context lazy initialization
*
* @param globalContext Partially initialized global context (globalContext.extensionRegistry == null)
*/
public void setGlobalContext(Swagger2MarkupConverter.Context globalContext) {
configureDefaultContentPaths(globalContext.getSwaggerLocation());
}
/**
* Automatically set default path for external content files based on specified {@code swaggerLocation}.<br/>
* If {@code swaggerLocation} is null, default path can't be set and features are disabled.<br/>
* Paths have to be explicitly set when swaggerLocation.scheme != 'file' to limit the number of URL requests.
*
* @param swaggerLocation base path to set default paths
* @throws RuntimeException if basePath == null and any path is not configured
*/
private void configureDefaultContentPaths(URI swaggerLocation) {
URI baseURI = null;
if (swaggerLocation != null) {
if (swaggerLocation.getScheme().equals("file"))
baseURI = IOUtils.uriParent(swaggerLocation);
}
if (operationDescriptionsEnabled && operationDescriptionsUri == null) {
if (baseURI == null) {
if (logger.isWarnEnabled())
logger.warn("Disable {} > No explicit '{}' set and no default available > Disable {}", "operationDescriptionsEnabled", "operationDescriptionsUri");
operationDescriptionsEnabled = false;
} else
operationDescriptionsUri = baseURI;
}
if (definitionDescriptionsEnabled && definitionDescriptionsUri == null) {
if (baseURI == null) {
if (logger.isWarnEnabled())
logger.warn("Disable {} > No explicit '{}' set and no default available > Disable {}", "definitionDescriptionsEnabled", "definitionDescriptionsUri");
definitionDescriptionsEnabled = false;
} else
definitionDescriptionsUri = baseURI;
}
}
public MarkupLanguage getMarkupLanguage() {
return markupLanguage;
}
public boolean isGeneratedExamplesEnabled() {
return generatedExamplesEnabled;
}
public boolean isOperationDescriptionsEnabled() {
return operationDescriptionsEnabled;
}
public URI getOperationDescriptionsUri() {
return operationDescriptionsUri;
}
public boolean isDefinitionDescriptionsEnabled() {
return definitionDescriptionsEnabled;
}
public URI getDefinitionDescriptionsUri() {
return definitionDescriptionsUri;
}
public boolean isSeparatedDefinitionsEnabled() {
return separatedDefinitionsEnabled;
}
public boolean isSeparatedOperationsEnabled() {
return separatedOperationsEnabled;
}
public GroupBy getOperationsGroupedBy() {
return operationsGroupedBy;
}
public Language getOutputLanguage() {
return outputLanguage;
}
public int getInlineSchemaDepthLevel() {
return inlineSchemaDepthLevel;
}
public OrderBy getTagOrderBy() {
return tagOrderBy;
}
public Comparator<String> getTagOrdering() {
return tagOrdering;
}
public OrderBy getOperationOrderBy() {
return operationOrderBy;
}
public Comparator<PathOperation> getOperationOrdering() {
return operationOrdering;
}
public OrderBy getDefinitionOrderBy() {
return definitionOrderBy;
}
public Comparator<String> getDefinitionOrdering() {
return definitionOrdering;
}
public OrderBy getParameterOrderBy() {
return parameterOrderBy;
}
public Comparator<Parameter> getParameterOrdering() {
return parameterOrdering;
}
public OrderBy getPropertyOrderBy() {
return propertyOrderBy;
}
public Comparator<String> getPropertyOrdering() {
return propertyOrdering;
}
public OrderBy getResponseOrderBy() {
return responseOrderBy;
}
public Comparator<String> getResponseOrdering() {
return responseOrdering;
}
public boolean isInterDocumentCrossReferencesEnabled() {
return interDocumentCrossReferencesEnabled;
}
public String getInterDocumentCrossReferencesPrefix() {
return interDocumentCrossReferencesPrefix;
}
public boolean isFlatBodyEnabled() {
return flatBodyEnabled;
}
public String getAnchorPrefix() {
return anchorPrefix;
}
public String getOverviewDocument() {
return overviewDocument;
}
public String getPathsDocument() {
return pathsDocument;
}
public String getDefinitionsDocument() {
return definitionsDocument;
}
public String getSecurityDocument() {
return securityDocument;
}
public String getSeparatedOperationsFolder() {
return separatedOperationsFolder;
}
public String getSeparatedDefinitionsFolder() {
return separatedDefinitionsFolder;
}
public LineSeparator getLineSeparator() {
return lineSeparator;
}
public static class Builder {
private static final String PROPERTIES_PREFIX = "swagger2markup.";
private static final String PROPERTIES_DEFAULT = "/io/github/robwin/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();
}
});
Swagger2MarkupConfig config = new Swagger2MarkupConfig();
Builder() {
this(new Properties());
}
Builder(Properties properties) {
Properties safeProperties = new Properties(defaultProperties());
safeProperties.putAll(properties);
config.markupLanguage = MarkupLanguage.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "markupLanguage"));
config.generatedExamplesEnabled = Boolean.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "generatedExamplesEnabled"));
config.operationDescriptionsEnabled = Boolean.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "operationDescriptionsEnabled"));
if (safeProperties.containsKey(PROPERTIES_PREFIX + "operationDescriptionsUri"))
config.operationDescriptionsUri = URI.create(safeProperties.getProperty(PROPERTIES_PREFIX + "operationDescriptionsUri"));
config.definitionDescriptionsEnabled = Boolean.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "definitionDescriptionsEnabled"));
if (safeProperties.containsKey(PROPERTIES_PREFIX + "definitionDescriptionsUri"))
config.definitionDescriptionsUri = URI.create(safeProperties.getProperty(PROPERTIES_PREFIX + "definitionDescriptionsUri"));
config.separatedDefinitionsEnabled = Boolean.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "separatedDefinitionsEnabled"));
config.separatedOperationsEnabled = Boolean.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "separatedOperationsEnabled"));
config.operationsGroupedBy = GroupBy.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "operationsGroupedBy"));
config.outputLanguage = Language.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "outputLanguage"));
config.inlineSchemaDepthLevel = Integer.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "inlineSchemaDepthLevel"));
config.interDocumentCrossReferencesEnabled = Boolean.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "interDocumentCrossReferencesEnabled"));
config.interDocumentCrossReferencesPrefix = safeProperties.getProperty(PROPERTIES_PREFIX + "interDocumentCrossReferencesPrefix");
config.flatBodyEnabled = Boolean.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "flatBodyEnabled"));
config.anchorPrefix = safeProperties.getProperty(PROPERTIES_PREFIX + "anchorPrefix");
config.overviewDocument = safeProperties.getProperty(PROPERTIES_PREFIX + "overviewDocument");
config.pathsDocument = safeProperties.getProperty(PROPERTIES_PREFIX + "pathsDocument");
config.definitionsDocument = safeProperties.getProperty(PROPERTIES_PREFIX + "definitionsDocument");
config.securityDocument = safeProperties.getProperty(PROPERTIES_PREFIX + "securityDocument");
config.separatedOperationsFolder = safeProperties.getProperty(PROPERTIES_PREFIX + "separatedOperationsFolder");
config.separatedDefinitionsFolder = safeProperties.getProperty(PROPERTIES_PREFIX + "separatedDefinitionsFolder");
config.tagOrderBy = OrderBy.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "tagOrderBy"));
config.operationOrderBy = OrderBy.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "operationOrderBy"));
config.definitionOrderBy = OrderBy.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "definitionOrderBy"));
config.parameterOrderBy = OrderBy.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "parameterOrderBy"));
config.propertyOrderBy = OrderBy.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "propertyOrderBy"));
config.responseOrderBy = OrderBy.valueOf(safeProperties.getProperty(PROPERTIES_PREFIX + "responseOrderBy"));
String lineSeparator = safeProperties.getProperty(PROPERTIES_PREFIX + "lineSeparator");
if(StringUtils.isNoneBlank(lineSeparator)){
config.lineSeparator = LineSeparator.valueOf(lineSeparator);
}
}
private Properties defaultProperties() {
Properties defaultProperties = new Properties();
try {
InputStream defaultPropertiesStream = Swagger2MarkupConfig.class.getResourceAsStream(PROPERTIES_DEFAULT);
if (defaultPropertiesStream == null)
throw new RuntimeException(String.format("Can't load default properties '%s'", PROPERTIES_DEFAULT));
defaultProperties.load(defaultPropertiesStream);
} catch (IOException e) {
throw new RuntimeException(String.format("Can't load default properties '%s'", PROPERTIES_DEFAULT), e);
}
return defaultProperties;
}
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 Builder withMarkupLanguage(MarkupLanguage markupLanguage) {
Validate.notNull(markupLanguage, "%s must not be null", "markupLanguage");
config.markupLanguage = markupLanguage;
return this;
}
/**
* Include generated examples into the Paths document
*
* @return this builder
*/
public Builder withGeneratedExamples() {
config.generatedExamplesEnabled = true;
return this;
}
/**
* Include hand-written descriptions into the Paths document
*
* @param operationDescriptionsUri the URI to the folder where the description documents reside.
* @return this builder
*/
public Builder withOperationDescriptions(URI operationDescriptionsUri) {
Validate.notNull(operationDescriptionsUri, "%s must not be null", "operationDescriptionsUri");
config.operationDescriptionsEnabled = true;
config.operationDescriptionsUri = operationDescriptionsUri;
return this;
}
/**
* Include hand-written descriptions into the Paths document
*
* @param operationDescriptionsPath the path to the folder where the description documents reside.
* @return this builder
*/
public Builder withOperationDescriptions(Path operationDescriptionsPath) {
Validate.notNull(operationDescriptionsPath, "%s must not be null", "operationDescriptionsPath");
return withOperationDescriptions(operationDescriptionsPath.toUri());
}
/**
* Include hand-written descriptions into the Paths document.<br/>
* Use default URI.
*
* @return this builder
*/
public Builder withOperationDescriptions() {
config.operationDescriptionsEnabled = true;
return this;
}
/**
* Include hand-written descriptions into the Definitions document
*
* @param definitionDescriptionsUri the URI to the folder where the description documents reside.
* @return this builder
*/
public Builder withDefinitionDescriptions(URI definitionDescriptionsUri) {
Validate.notNull(definitionDescriptionsUri, "%s must not be null", "definitionDescriptionsUri");
config.definitionDescriptionsEnabled = true;
config.definitionDescriptionsUri = definitionDescriptionsUri;
return this;
}
/**
* Include hand-written descriptions into the Definitions document
*
* @param definitionDescriptionsPath the path to the folder where the description documents reside.
* @return this builder
*/
public Builder withDefinitionDescriptions(Path definitionDescriptionsPath) {
Validate.notNull(definitionDescriptionsPath, "%s must not be null", "definitionDescriptionsPath");
return withDefinitionDescriptions(definitionDescriptionsPath.toUri());
}
/**
* Include hand-written descriptions into the Definitions document.<br/>
* Use default URI.
*
* @return this builder
*/
public Builder withDefinitionDescriptions() {
config.definitionDescriptionsEnabled = true;
return this;
}
/**
* In addition to the definitions file, also create separate definition files for each model definition.
*
* @return this builder
*/
public Builder withSeparatedDefinitions() {
config.separatedDefinitionsEnabled = true;
return this;
}
/**
* In addition to the paths file, also create separate path files for each path.
*
* @return this builder
*/
public Builder 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 Builder withPathsGroupedBy(GroupBy pathsGroupedBy) {
Validate.notNull(pathsGroupedBy, "%s must not be null", "pathsGroupedBy");
config.operationsGroupedBy = pathsGroupedBy;
return this;
}
/**
* Specifies labels language of output files
*
* @param language the enum
* @return this builder
*/
public Builder withOutputLanguage(Language language) {
Validate.notNull(language, "%s must not be null", "language");
config.outputLanguage = language;
return this;
}
/**
* Specifies maximum depth level for inline object schema displaying (0 = no inline schemasEnabled)
*
* @param inlineSchemaDepthLevel number of recursion levels for inline schemasEnabled display
* @return this builder
*/
public Builder withInlineSchemaDepthLevel(int inlineSchemaDepthLevel) {
Validate.isTrue(inlineSchemaDepthLevel >= 0, "%s must be >= 0", "inlineSchemaDepthLevel");
config.inlineSchemaDepthLevel = inlineSchemaDepthLevel;
return this;
}
/**
* Specifies tag ordering.<br/>
* By default tag ordering == {@link io.github.robwin.swagger2markup.OrderBy#NATURAL}.<br/>
* Use {@link #withTagOrdering(Comparator)} to set a custom ordering.
*
* @param orderBy tag ordering
* @return this builder
*/
public Builder 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 Builder 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.robwin.swagger2markup.OrderBy#AS_IS}.<br/>
* Use {@link #withOperationOrdering(Comparator)} to set a custom ordering.
*
* @param orderBy operation ordering
* @return this builder
*/
public Builder 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 Builder 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.robwin.swagger2markup.OrderBy#NATURAL}.<br/>
* Use {@link #withDefinitionOrdering(Comparator)} to set a custom ordering.
*
* @param orderBy definition ordering
* @return this builder
*/
public Builder 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 Builder 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 io.github.robwin.swagger2markup.OrderBy#NATURAL}.<br/>
* Use {@link #withParameterOrdering(Comparator)} to set a custom ordering.
*
* @param orderBy parameter ordering
* @return this builder
*/
public Builder 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 Builder 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.robwin.swagger2markup.OrderBy#NATURAL}.<br/>
* Use {@link #withPropertyOrdering(Comparator)} to set a custom ordering.
*
* @param orderBy property ordering
* @return this builder
*/
public Builder 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 propertys.
*
* @param propertyOrdering property ordering
* @return this builder
*/
public Builder 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.robwin.swagger2markup.OrderBy#NATURAL}.<br/>
* Use {@link #withResponseOrdering(Comparator)} to set a custom ordering.
*
* @param orderBy response ordering
* @return this builder
*/
public Builder 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 Builder 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 Builder 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 Builder withInterDocumentCrossReferences() {
config.interDocumentCrossReferencesEnabled = true;
return this;
}
/**
* Optionally isolate the body parameter, if any, from other parameters
*
* @return this builder
*/
public Builder withFlatBody() {
config.flatBodyEnabled = true;
return this;
}
/**
* Optionally prefix all anchors for unicity
*.
* @param anchorPrefix anchor prefix.
* @return this builder
*/
public Builder 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 Builder withLineSeparator(LineSeparator lineSeparator) {
Validate.notNull(lineSeparator, "%s must no be null", "lineSeparator");
config.lineSeparator = lineSeparator;
return this;
}
}
}

View File

@@ -1,292 +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.robwin.swagger2markup;
import com.google.common.annotations.VisibleForTesting;
import io.github.robwin.swagger2markup.internal.document.builder.DefinitionsDocumentBuilder;
import io.github.robwin.swagger2markup.internal.document.builder.OverviewDocumentBuilder;
import io.github.robwin.swagger2markup.internal.document.builder.PathsDocumentBuilder;
import io.github.robwin.swagger2markup.internal.document.builder.SecurityDocumentBuilder;
import io.github.robwin.swagger2markup.spi.Extension;
import io.github.robwin.swagger2markup.spi.SwaggerModelExtension;
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.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
/**
* @author Robert Winkler
*/
public class Swagger2MarkupConverter {
private Context context;
public Swagger2MarkupConverter(Context globalContext) {
this.context = globalContext;
}
/**
* Returns the global Context
*
* @return the global Context
*/
@VisibleForTesting
Context getContext(){
return context;
}
/**
* 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");
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
* @throws java.io.IOException if String can not be parsed
*/
public static Builder from(String swaggerString) throws IOException {
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
* @throws java.io.IOException if source can not be parsed
*/
public static Builder from(Reader swaggerReader) throws IOException {
Validate.notNull(swaggerReader, "swaggerReader must not be null");
Swagger swagger = new SwaggerParser().parse(IOUtils.toString(swaggerReader));
if (swagger == null)
throw new IllegalArgumentException("Swagger source is in a wrong format");
return new Builder(swagger);
}
/**
* Builds the document with the given markup language and stores
* the files in the given folder.
*
* @param outputPath the output directory path
* @throws IOException if the files cannot be written
*/
public void intoFolder(Path outputPath) throws IOException {
Validate.notNull(outputPath, "outputPath must not be null");
applySwaggerExtensions();
buildDocuments(outputPath);
}
/**
* Builds the document with the given markup language and returns it as a String
*
* @return a the document as a String
* @throws java.io.IOException if files can not be read
*/
public String asString() throws IOException {
applySwaggerExtensions();
return buildDocuments();
}
private void applySwaggerExtensions() {
for (SwaggerModelExtension swaggerModelExtension : context.extensionRegistry.getExtensions(SwaggerModelExtension.class)) {
swaggerModelExtension.apply(context.getSwagger());
}
}
/**
* Builds all documents and writes them to a directory
*
* @param outputPath the directory path where the generated file should be stored
* @throws IOException if a file cannot be written
*/
private void buildDocuments(Path outputPath) throws IOException {
new OverviewDocumentBuilder(context, outputPath).build().writeToFile(outputPath.resolve(context.config.getOverviewDocument()), StandardCharsets.UTF_8);
new PathsDocumentBuilder(context, outputPath).build().writeToFile(outputPath.resolve(context.config.getPathsDocument()), StandardCharsets.UTF_8);
new DefinitionsDocumentBuilder(context, outputPath).build().writeToFile(outputPath.resolve(context.config.getDefinitionsDocument()), StandardCharsets.UTF_8);
new SecurityDocumentBuilder(context, outputPath).build().writeToFile(outputPath.resolve(context.config.getSecurityDocument()), StandardCharsets.UTF_8);
}
/**
* Returns all documents as a String
*
* @return a the document as a String
*/
private String buildDocuments() {
StringBuilder sb = new StringBuilder();
sb.append(new OverviewDocumentBuilder(context, null).build().toString());
sb.append(new PathsDocumentBuilder(context, null).build().toString());
sb.append(new DefinitionsDocumentBuilder(context, null).build().toString());
sb.append(new SecurityDocumentBuilder(context, 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(config, "registry must not be null");
this.extensionRegistry = registry;
return this;
}
public Swagger2MarkupConverter build() {
if (config == null)
config = Swagger2MarkupConfig.ofDefaults().build();
if (extensionRegistry == null)
extensionRegistry = Swagger2MarkupExtensionRegistry.ofDefaults().build();
Context context = new Context(config, extensionRegistry, swagger, swaggerLocation);
config.setGlobalContext(context);
for (Extension extension : extensionRegistry.getExtensions())
extension.setGlobalContext(context);
return new Swagger2MarkupConverter(context);
}
}
public static class Context {
private Swagger2MarkupConfig config;
private Swagger2MarkupExtensionRegistry extensionRegistry;
private Swagger swagger;
private URI swaggerLocation;
Context(Swagger2MarkupConfig config, Swagger2MarkupExtensionRegistry extensionRegistry, Swagger swagger, URI swaggerLocation) {
this.config = config;
this.extensionRegistry = extensionRegistry;
this.swagger = swagger;
this.swaggerLocation = swaggerLocation;
}
public Swagger2MarkupConfig getConfig() {
return config;
}
public Swagger2MarkupExtensionRegistry getExtensionRegistry() {
return extensionRegistry;
}
public Swagger getSwagger() {
return swagger;
}
public URI getSwaggerLocation() {
return swaggerLocation;
}
}
}

View File

@@ -1,112 +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.robwin.swagger2markup;
import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
import io.github.robwin.swagger2markup.internal.extensions.DynamicDefinitionsDocumentExtension;
import io.github.robwin.swagger2markup.internal.extensions.DynamicPathsDocumentExtension;
import io.github.robwin.swagger2markup.internal.extensions.DynamicOverviewDocumentExtension;
import io.github.robwin.swagger2markup.internal.extensions.DynamicSecurityDocumentExtension;
import io.github.robwin.swagger2markup.spi.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class Swagger2MarkupExtensionRegistry {
protected static final List<Class<? extends Extension>> EXTENSION_POINTS = Arrays.<Class<? extends Extension>>asList(
SwaggerModelExtension.class,
OverviewDocumentExtension.class,
SecurityDocumentExtension.class,
DefinitionsDocumentExtension.class,
PathsDocumentExtension.class
);
protected final Multimap<Class<? extends Extension>, Extension> extensions;
public Swagger2MarkupExtensionRegistry(Multimap<Class<? extends Extension>, Extension> extensions) {
this.extensions = extensions;
}
public static Builder ofEmpty() {
return new Builder(false);
}
public static Builder ofDefaults() {
return new Builder(true);
}
public static class Builder {
private final Multimap<Class<? extends Extension>, Extension> extensions;
Builder(boolean useDefaults) {
extensions = MultimapBuilder.hashKeys().arrayListValues().build();
if (useDefaults) {
withExtension(new DynamicOverviewDocumentExtension());
withExtension(new DynamicSecurityDocumentExtension());
withExtension(new DynamicPathsDocumentExtension());
withExtension(new DynamicDefinitionsDocumentExtension());
}
}
public Swagger2MarkupExtensionRegistry build() {
return new Swagger2MarkupExtensionRegistry(extensions);
}
public Builder withExtension(Extension extension) {
registerExtension(extension);
return this;
}
public void registerExtension(Extension extension) {
for (Class<? extends Extension> extensionPoint : EXTENSION_POINTS) {
if (extensionPoint.isInstance(extension)) {
extensions.put(extensionPoint, extension);
return;
}
}
throw new IllegalArgumentException("Provided extension class does not extend any of the supported extension points");
}
}
@SuppressWarnings(value = "unchecked")
public <T extends Extension> List<T> getExtensions(Class<T> extensionClass) {
List<T> ret = new ArrayList<>();
for (Map.Entry<Class<? extends Extension>, Extension> entry : extensions.entries()) {
if (extensionClass.isAssignableFrom(entry.getKey())) {
if (extensionClass.isInstance(entry.getValue()))
ret.add((T) entry.getValue());
}
}
return ret;
}
/**
* Get all extensions
* @return all extensions
*/
public List<Extension> getExtensions() {
return getExtensions(Extension.class);
}
}

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.robwin.swagger2markup.internal.document;
import io.github.robwin.markup.builder.MarkupDocBuilder;
import java.io.IOException;
import java.nio.charset.Charset;
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.
*
* @param file the generated file
* @param charset the the charset to use for encoding
* @throws IOException if the file cannot be written
*/
public void writeToFile(Path file, Charset charset) throws IOException {
markupDocBuilder.writeToFile(file, charset);
}
}

View File

@@ -1,398 +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.robwin.swagger2markup.internal.document.builder;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import io.github.robwin.markup.builder.MarkupDocBuilder;
import io.github.robwin.swagger2markup.Swagger2MarkupConverter;
import io.github.robwin.swagger2markup.internal.document.MarkupDocument;
import io.github.robwin.swagger2markup.spi.DefinitionsDocumentExtension;
import io.github.robwin.swagger2markup.internal.type.ObjectType;
import io.github.robwin.swagger2markup.internal.type.Type;
import io.swagger.models.ComposedModel;
import io.swagger.models.Model;
import io.swagger.models.RefModel;
import io.swagger.models.properties.Property;
import io.swagger.models.refs.RefFormat;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.Validate;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.*;
import static io.github.robwin.swagger2markup.internal.utils.IOUtils.normalizeName;
import static io.github.robwin.swagger2markup.spi.DefinitionsDocumentExtension.*;
import static org.apache.commons.lang3.StringUtils.defaultString;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static io.github.robwin.swagger2markup.internal.utils.MapUtils.toKeySet;
/**
* @author Robert Winkler
*/
public class DefinitionsDocumentBuilder extends MarkupDocumentBuilder {
private static final String DEFINITIONS_ANCHOR = "definitions";
private final String DEFINITIONS;
private static final List<String> IGNORED_DEFINITIONS = Collections.singletonList("Void");
private static final String DESCRIPTION_FILE_NAME = "description";
public DefinitionsDocumentBuilder(Swagger2MarkupConverter.Context context, Path outputPath) {
super(context, outputPath);
ResourceBundle labels = ResourceBundle.getBundle("io/github/robwin/swagger2markup/lang/labels", config.getOutputLanguage().toLocale());
DEFINITIONS = labels.getString("definitions");
if (config.isDefinitionDescriptionsEnabled()) {
if (logger.isDebugEnabled()) {
logger.debug("Include hand-written definition descriptions is enabled.");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Include hand-written definition descriptions is disabled.");
}
}
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() {
Map<String, Model> definitions = globalContext.getSwagger().getDefinitions();
if (MapUtils.isNotEmpty(definitions)) {
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_BEFORE, this.markupDocBuilder));
buildDefinitionsTitle(DEFINITIONS);
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_BEGIN, this.markupDocBuilder));
buildDefinitionsSection(definitions);
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_END, this.markupDocBuilder));
}
return new MarkupDocument(markupDocBuilder);
}
private void buildDefinitionsSection(Map<String, Model> definitions) {
Set<String> definitionNames = toKeySet(definitions, config.getDefinitionOrdering());
for (String definitionName : definitionNames) {
Model model = definitions.get(definitionName);
if (isNotBlank(definitionName)) {
if (checkThatDefinitionIsNotInIgnoreList(definitionName)) {
buildDefinition(definitions, 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 : globalContext.getExtensionRegistry().getExtensions(DefinitionsDocumentExtension.class)) {
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 definitions all available definitions to be able to verify references
* @param definitionName definition name to process
* @param model definition model to process
*/
private void buildDefinition(Map<String, Model> definitions, String definitionName, Model model) {
if (config.isSeparatedDefinitionsEnabled()) {
MarkupDocBuilder defDocBuilder = this.markupDocBuilder.copy();
buildDefinition(definitions, definitionName, model, defDocBuilder);
Path definitionFile = outputPath.resolve(resolveDefinitionDocument(definitionName));
try {
defDocBuilder.writeToFileWithoutExtension(definitionFile, StandardCharsets.UTF_8);
} catch (IOException e) {
if (logger.isWarnEnabled()) {
logger.warn(String.format("Failed to write definition file: %s", definitionFile), e);
}
}
if (logger.isInfoEnabled()) {
logger.info("Separate definition file produced: {}", definitionFile);
}
definitionRef(definitionName, this.markupDocBuilder);
} else {
buildDefinition(definitions, 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(Map<String, Model> definitions, String definitionName, Model model, MarkupDocBuilder docBuilder) {
buildDefinitionTitle(definitionName, null, docBuilder);
applyDefinitionsDocumentExtension(new Context(Position.DEFINITION_BEGIN, docBuilder, definitionName, model));
buildDescriptionParagraph(definitionName, model, docBuilder);
inlineDefinitions(propertiesSection(definitions, definitionName, model, docBuilder), definitionName, config.getInlineSchemaDepthLevel(), docBuilder);
applyDefinitionsDocumentExtension(new Context(Position.DEFINITION_END, 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(docBuilder.copy().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);
}
/**
* Override Property description functor for definitions.
* This implementation handles optional handwritten descriptions.
*/
private class DefinitionPropertyDescriptor extends PropertyDescriptor {
public DefinitionPropertyDescriptor(Type type) {
super(type);
}
@Override
public String getDescription(Property property, String propertyName) {
if (config.isDefinitionDescriptionsEnabled()) {
Optional<String> description = handWrittenDefinitionDescription(new File(normalizeName(type.getName()), normalizeName(propertyName)).toString(), DESCRIPTION_FILE_NAME);
if (description.isPresent()) {
return description.get();
} else {
return defaultString(property.getDescription());
}
} else {
return defaultString(property.getDescription());
}
}
}
/**
* Builds the properties of a definition and inline schemas.
*
* @param definitions all available definitions
* @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> propertiesSection(Map<String, Model> definitions, String definitionName, Model model, MarkupDocBuilder docBuilder) {
Map<String, Property> properties = getAllProperties(definitions, model);
ObjectType type = new ObjectType(definitionName, properties);
return buildPropertiesTable(type, definitionName, 1, new PropertyDescriptor(type), new DefinitionDocumentResolverFromDefinition(), docBuilder);
}
private Map<String, Property> getAllProperties(Map<String, Model> definitions, Model model) {
if (model instanceof RefModel) {
RefModel refModel = (RefModel) model;
String ref;
if (refModel.getRefFormat().equals(RefFormat.INTERNAL)) {
ref = refModel.getSimpleRef();
} else {
ref = model.getReference();
}
return definitions.containsKey(ref)
? getAllProperties(definitions, definitions.get(ref))
: null;
} else if (model instanceof ComposedModel) {
ComposedModel composedModel = (ComposedModel) model;
Map<String, Property> allProperties = new HashMap<>();
if (composedModel.getAllOf() != null) {
for (Model innerModel : composedModel.getAllOf()) {
Map<String, Property> innerProperties = getAllProperties(definitions, innerModel);
if (innerProperties != null) {
allProperties.putAll(innerProperties);
}
}
}
return ImmutableMap.copyOf(allProperties);
} else {
return model.getProperties();
}
}
private void buildDescriptionParagraph(String definitionName, Model model, MarkupDocBuilder docBuilder) {
if (config.isDefinitionDescriptionsEnabled()) {
Optional<String> description = handWrittenDefinitionDescription(normalizeName(definitionName), DESCRIPTION_FILE_NAME);
if (description.isPresent()) {
docBuilder.paragraph(description.get());
} else {
modelDescription(model, docBuilder);
}
} else {
modelDescription(model, docBuilder);
}
}
private void modelDescription(Model model, MarkupDocBuilder docBuilder) {
String description = model.getDescription();
if (isNotBlank(description)) {
docBuilder.paragraph(description);
}
}
/**
* Reads a hand-written description
*
* @param descriptionFolder the name of the folder where the description file resides
* @param descriptionFileName the name of the description file
* @return the content of the file
*/
private Optional<String> handWrittenDefinitionDescription(String descriptionFolder, String descriptionFileName) {
for (String fileNameExtension : config.getMarkupLanguage().getFileNameExtensions()) {
URI contentUri = config.getDefinitionDescriptionsUri().resolve(descriptionFolder).resolve(descriptionFileName + fileNameExtension);
try (Reader reader = io.github.robwin.swagger2markup.internal.utils.IOUtils.uriReader(contentUri)) {
if (logger.isInfoEnabled()) {
logger.info("Definition description content processed {}", contentUri);
}
return Optional.of(IOUtils.toString(reader).trim());
} catch (IOException e) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to read Operation description content {} > {}", contentUri, e.getMessage());
}
}
}
return Optional.absent();
}
/**
* 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 depth current inline schema depth
* @param docBuilder the docbuilder do use for output
*/
private void inlineDefinitions(List<ObjectType> definitions, String uniquePrefix, int depth, MarkupDocBuilder docBuilder) {
if (CollectionUtils.isNotEmpty(definitions)) {
for (ObjectType definition : definitions) {
addInlineDefinitionTitle(definition.getName(), definition.getUniqueName(), docBuilder);
List<ObjectType> localDefinitions = buildPropertiesTable(definition, uniquePrefix, depth, new DefinitionPropertyDescriptor(definition), new DefinitionDocumentResolverFromDefinition(), docBuilder);
for (ObjectType localDefinition : localDefinitions)
inlineDefinitions(Collections.singletonList(localDefinition), uniquePrefix, depth - 1, 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,188 +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.robwin.swagger2markup.internal.document.builder;
import io.github.robwin.markup.builder.MarkupDocBuilder;
import io.github.robwin.markup.builder.MarkupDocBuilders;
import io.github.robwin.markup.builder.MarkupLanguage;
import io.github.robwin.markup.builder.MarkupTableColumn;
import io.github.robwin.swagger2markup.Swagger2MarkupConfig;
import io.github.robwin.swagger2markup.Swagger2MarkupConverter;
import io.github.robwin.swagger2markup.internal.document.MarkupDocument;
import io.github.robwin.swagger2markup.internal.type.DefinitionDocumentResolver;
import io.github.robwin.swagger2markup.internal.type.ObjectType;
import io.github.robwin.swagger2markup.internal.type.RefType;
import io.github.robwin.swagger2markup.internal.type.Type;
import io.github.robwin.swagger2markup.internal.utils.IOUtils;
import io.github.robwin.swagger2markup.internal.utils.PropertyUtils;
import io.swagger.models.properties.Property;
import io.swagger.util.Json;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.*;
import static io.github.robwin.swagger2markup.internal.utils.MapUtils.toKeySet;
import static org.apache.commons.lang3.StringUtils.defaultString;
/**
* @author Robert Winkler
*/
public abstract class MarkupDocumentBuilder {
protected final String DEFAULT_COLUMN;
protected final String EXAMPLE_COLUMN;
protected final String REQUIRED_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 Logger logger = LoggerFactory.getLogger(getClass());
protected Swagger2MarkupConverter.Context globalContext;
protected Swagger2MarkupConfig config;
protected MarkupDocBuilder markupDocBuilder;
protected Path outputPath;
MarkupDocumentBuilder(Swagger2MarkupConverter.Context globalContext, Path outputPath) {
this.globalContext = globalContext;
this.config = globalContext.getConfig();
this.outputPath = outputPath;
this.markupDocBuilder = MarkupDocBuilders.documentBuilder(config.getMarkupLanguage(), config.getLineSeparator()).withAnchorPrefix(config.getAnchorPrefix());
ResourceBundle labels = ResourceBundle.getBundle("io/github/robwin/swagger2markup/lang/labels", config.getOutputLanguage().toLocale());
DEFAULT_COLUMN = labels.getString("default_column");
EXAMPLE_COLUMN = labels.getString("example_column");
REQUIRED_COLUMN = labels.getString("required_column");
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;
/**
* Build a generic property table for any ObjectType
*
* @param type to display
* @param uniquePrefix unique prefix to prepend to inline object names to enforce unicity
* @param depth current inline schema object depth
* @param propertyDescriptor property descriptor to apply to properties
* @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(ObjectType type, String uniquePrefix, int depth, PropertyDescriptor propertyDescriptor, DefinitionDocumentResolver definitionDocumentResolver, MarkupDocBuilder docBuilder) {
List<ObjectType> localDefinitions = new ArrayList<>();
List<List<String>> cells = new ArrayList<>();
List<MarkupTableColumn> cols = Arrays.asList(
new MarkupTableColumn(NAME_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1h"),
new MarkupTableColumn(DESCRIPTION_COLUMN, 6).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^6"),
new MarkupTableColumn(REQUIRED_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1"),
new MarkupTableColumn(SCHEMA_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1"),
new MarkupTableColumn(DEFAULT_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1"),
new MarkupTableColumn(EXAMPLE_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1"));
if (MapUtils.isNotEmpty(type.getProperties())) {
Set<String> propertyNames = toKeySet(type.getProperties(), config.getPropertyOrdering());
for (String propertyName : propertyNames) {
Property property = type.getProperties().get(propertyName);
Type propertyType = PropertyUtils.getType(property, definitionDocumentResolver);
if (depth > 0 && propertyType instanceof ObjectType) {
if (MapUtils.isNotEmpty(((ObjectType) propertyType).getProperties())) {
propertyType.setName(propertyName);
propertyType.setUniqueName(uniquePrefix + " " + propertyName);
localDefinitions.add((ObjectType) propertyType);
propertyType = new RefType(propertyType);
}
}
Object example = PropertyUtils.getExample(config.isGeneratedExamplesEnabled(), property, markupDocBuilder);
List<String> content = Arrays.asList(
propertyName,
propertyDescriptor.getDescription(property, propertyName),
Boolean.toString(property.getRequired()),
propertyType.displaySchema(docBuilder),
PropertyUtils.getDefaultValue(property),
example != null ? Json.pretty(example) : ""
);
cells.add(content);
}
docBuilder.tableWithColumnSpecs(cols, cells);
} else {
docBuilder.textLine(NO_CONTENT);
}
return localDefinitions;
}
/**
* A functor to return descriptions for a given property
*/
class PropertyDescriptor {
protected Type type;
public PropertyDescriptor(Type type) {
this.type = type;
}
public String getDescription(Property property, String propertyName) {
return defaultString(property.getDescription());
}
}
/**
* 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,204 +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.robwin.swagger2markup.internal.document.builder;
import io.github.robwin.swagger2markup.Swagger2MarkupConverter;
import io.github.robwin.swagger2markup.internal.document.MarkupDocument;
import io.github.robwin.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.robwin.swagger2markup.spi.OverviewDocumentExtension.*;
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, Path outputPath){
super(context, outputPath);
ResourceBundle labels = ResourceBundle.getBundle("io/github/robwin/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));
buildDescription(info.getDescription());
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));
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);
this.markupDocBuilder.textLine(VERSION + " : " + version);
}
}
private void buildDescription(String description) {
if(isNotBlank(description)){
this.markupDocBuilder.textLine(description);
}
}
private void buildContactInfoSection(Contact contact) {
if(contact != null){
this.markupDocBuilder.sectionTitleLevel2(CONTACT_INFORMATION);
if(isNotBlank(contact.getName())){
this.markupDocBuilder.textLine(CONTACT_NAME + " : " + contact.getName());
}
if(isNotBlank(contact.getEmail())){
this.markupDocBuilder.textLine(CONTACT_EMAIL + " : " + contact.getEmail());
}
}
}
private void buildLicenseInfoSection(License license, String termOfService) {
if(license != null && (isNotBlank(license.getName()) || isNotBlank(license.getUrl()))) {
this.markupDocBuilder.sectionTitleLevel2(LICENSE_INFORMATION);
if (isNotBlank(license.getName())) {
this.markupDocBuilder.textLine(LICENSE + " : " + license.getName());
}
if (isNotBlank(license.getUrl())) {
this.markupDocBuilder.textLine(LICENSE_URL + " : " + license.getUrl());
}
}
if(isNotBlank(termOfService)){
this.markupDocBuilder.textLine(TERMS_OF_SERVICE + " : " + termOfService);
}
}
private void buildUriSchemeSection(Swagger swagger) {
if(isNotBlank(swagger.getHost()) || isNotBlank(swagger.getBasePath()) || isNotEmpty(swagger.getSchemes())) {
this.markupDocBuilder.sectionTitleLevel2(URI_SCHEME);
if (isNotBlank(swagger.getHost())) {
this.markupDocBuilder.textLine(HOST + " : " + swagger.getHost());
}
if (isNotBlank(swagger.getBasePath())) {
this.markupDocBuilder.textLine(BASE_PATH + " : " + swagger.getBasePath());
}
if (isNotEmpty(swagger.getSchemes())) {
List<String> schemes = new ArrayList<>();
for (Scheme scheme : swagger.getSchemes()) {
schemes.add(scheme.toString());
}
this.markupDocBuilder.textLine(SCHEMES + " : " + join(schemes, ", "));
}
}
}
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 + " : " + description);
}else{
tagsList.add(name);
}
}
this.markupDocBuilder.unorderedList(tagsList);
}
}
private void buildConsumesSection(List<String> consumes) {
if (isNotEmpty(consumes)) {
this.markupDocBuilder.sectionTitleLevel2(CONSUMES);
this.markupDocBuilder.unorderedList(consumes);
}
}
private void buildProducesSection(List<String> consumes) {
if (isNotEmpty(consumes)) {
this.markupDocBuilder.sectionTitleLevel2(PRODUCES);
this.markupDocBuilder.unorderedList(consumes);
}
}
/**
* Apply extension context to all OverviewContentExtension
*
* @param context context
*/
private void applyOverviewDocumentExtension(Context context) {
for (OverviewDocumentExtension extension : globalContext.getExtensionRegistry().getExtensions(OverviewDocumentExtension.class)) {
extension.apply(context);
}
}
}

View File

@@ -1,812 +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.robwin.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.robwin.markup.builder.*;
import io.github.robwin.swagger2markup.GroupBy;
import io.github.robwin.swagger2markup.Swagger2MarkupConverter;
import io.github.robwin.swagger2markup.internal.document.MarkupDocument;
import io.github.robwin.swagger2markup.internal.model.PathOperation;
import io.github.robwin.swagger2markup.internal.type.ObjectType;
import io.github.robwin.swagger2markup.internal.type.RefType;
import io.github.robwin.swagger2markup.internal.type.Type;
import io.github.robwin.swagger2markup.internal.utils.*;
import io.github.robwin.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.io.IOUtils;
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.io.IOException;
import java.io.Reader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.*;
import static io.github.robwin.swagger2markup.internal.utils.IOUtils.normalizeName;
import static io.github.robwin.swagger2markup.internal.utils.ListUtils.*;
import static io.github.robwin.swagger2markup.internal.utils.MapUtils.toKeySet;
import static io.github.robwin.swagger2markup.internal.utils.TagUtils.convertTagsListToMap;
import static io.github.robwin.swagger2markup.internal.utils.TagUtils.getTagDescription;
import static io.github.robwin.swagger2markup.spi.PathsDocumentExtension.*;
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";
private static final String DESCRIPTION_FILE_NAME = "description";
public PathsDocumentBuilder(Swagger2MarkupConverter.Context globalContext, java.nio.file.Path outputPath) {
super(globalContext, outputPath);
ResourceBundle labels = ResourceBundle.getBundle("io/github/robwin/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.isOperationDescriptionsEnabled()) {
if (logger.isDebugEnabled()) {
logger.debug("Include hand-written operation descriptions is enabled.");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Include hand-written operation descriptions 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));
}
return new MarkupDocument(markupDocBuilder);
}
private void buildsPathsSection(Map<String, Path> paths) {
Set<PathOperation> pathOperations = toPathOperationsSet(paths);
if (CollectionUtils.isNotEmpty(pathOperations)) {
if (config.getOperationsGroupedBy() == 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.sectionTitleLevel2(WordUtils.capitalize(tagName));
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.getOperationsGroupedBy() == 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 : globalContext.getExtensionRegistry().getExtensions(PathsDocumentExtension.class)) {
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 = this.markupDocBuilder.copy();
buildOperation(operation, pathDocBuilder);
java.nio.file.Path operationFile = outputPath.resolve(resolveOperationDocument(operation));
try {
pathDocBuilder.writeToFileWithoutExtension(operationFile, StandardCharsets.UTF_8);
} catch (IOException e) {
if (logger.isWarnEnabled()) {
logger.warn(String.format("Failed to write operation file: %s", operationFile), e);
}
}
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: {}", operation);
}
}
/**
* Returns the operation name depending on available informations.
* The summary is used to name the operation, or else the operation summary is used.
*
* @param operation operation
* @return operation name
*/
private String operationName(PathOperation operation) {
return operation.getTitle();
}
/**
* 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_BEGIN, docBuilder, operation));
buildDeprecatedSection(operation, docBuilder);
buildOperationTitle(operation, docBuilder);
buildDescriptionSection(operation, docBuilder);
inlineDefinitions(buildParametersSection(operation, docBuilder), operation.getPath() + " " + operation.getMethod(), config.getInlineSchemaDepthLevel(), docBuilder);
inlineDefinitions(buildBodyParameterSection(operation, docBuilder), operation.getPath() + " " + operation.getMethod(), config.getInlineSchemaDepthLevel(), docBuilder);
inlineDefinitions(buildResponsesSection(operation, docBuilder), operation.getPath() + " " + operation.getMethod(), config.getInlineSchemaDepthLevel(), docBuilder);
buildConsumesSection(operation, docBuilder);
buildProducesSection(operation, docBuilder);
buildTagsSection(operation, docBuilder);
buildSecuritySchemeSection(operation, docBuilder);
buildExamplesSection(operation, docBuilder);
applyPathsDocumentExtension(new Context(Position.OPERATION_END, 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);
String operationName = operationName(operation);
buildOperationTitle(docBuilder.copy().crossReference(document, operationName, operationName).toString(), "ref-" + operationName, 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) {
String operationName = operationName(operation);
buildOperationTitle(operationName, null, docBuilder);
if (operationName.equals(operation.getOperation().getSummary())) {
docBuilder.listing(operation.getMethod() + " " + operation.getPath());
}
}
/**
* 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.getOperationsGroupedBy() == 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.getOperationsGroupedBy() == GroupBy.AS_IS) {
docBuilder.sectionTitleLevel3(title);
} else {
docBuilder.sectionTitleLevel4(title);
}
}
/**
* Adds a response section title to the document.
*
* @param title the response title
* @param docBuilder the MarkupDocBuilder to use
*/
private void buildResponseTitle(String title, MarkupDocBuilder docBuilder) {
if (config.getOperationsGroupedBy() == GroupBy.AS_IS) {
docBuilder.sectionTitleLevel4(title);
} else {
docBuilder.sectionTitleLevel5(title);
}
}
/**
* Adds a operation description to the document.
* If hand-written descriptions exist, it tries to load the description from a file.
* If the file cannot be read, the description of the operation is returned.
* Operation folder search order :
* - normalizeOperationFileName(operation.operationId)
* - then, normalizeOperationFileName(operation.method + " " + operation.path)
* - then, normalizeOperationFileName(operation.summary)
*
* @param operation the Swagger Operation
* @param docBuilder the docbuilder do use for output
*/
private void buildDescriptionSection(PathOperation operation, MarkupDocBuilder docBuilder) {
if (config.isOperationDescriptionsEnabled()) {
Optional<String> description = handWrittenOperationDescription(normalizeName(operation.getId()), DESCRIPTION_FILE_NAME);
if (!description.isPresent())
description = handWrittenOperationDescription(normalizeName(operation.getTitle()), DESCRIPTION_FILE_NAME);
if (description.isPresent()) {
operationDescription(description.get(), docBuilder);
} else {
operationDescription(operation.getOperation().getDescription(), docBuilder);
}
} else {
operationDescription(operation.getOperation().getDescription(), docBuilder);
}
}
private void operationDescription(String description, MarkupDocBuilder docBuilder) {
if (isNotBlank(description)) {
buildSectionTitle(DESCRIPTION, docBuilder);
docBuilder.paragraph(description);
}
}
/**
* 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> localDefinitions = new ArrayList<>();
boolean displayParameters = false;
if (CollectionUtils.isNotEmpty(parameters)) {
for (Parameter p : parameters) {
if (filterParameter(p)) {
displayParameters = true;
break;
}
}
}
if (displayParameters) {
List<List<String>> cells = new ArrayList<>();
List<MarkupTableColumn> cols = Arrays.asList(
new MarkupTableColumn(TYPE_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1h"),
new MarkupTableColumn(NAME_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1h"),
new MarkupTableColumn(DESCRIPTION_COLUMN, 6).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^6"),
new MarkupTableColumn(REQUIRED_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1"),
new MarkupTableColumn(SCHEMA_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1"),
new MarkupTableColumn(DEFAULT_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1"));
for (Parameter parameter : parameters) {
if (filterParameter(parameter)) {
Type type = ParameterUtils.getType(parameter, new DefinitionDocumentResolverFromOperation());
if (config.getInlineSchemaDepthLevel() > 0 && type instanceof ObjectType) {
if (MapUtils.isNotEmpty(((ObjectType) type).getProperties())) {
String localTypeName = parameter.getName();
type.setName(localTypeName);
type.setUniqueName(operation.getId() + " " + localTypeName);
localDefinitions.add((ObjectType) type);
type = new RefType(type);
}
}
String parameterType = WordUtils.capitalize(parameter.getIn());
List<String> content = Arrays.asList(
parameterType,
parameter.getName(),
parameterDescription(operation, parameter),
Boolean.toString(parameter.getRequired()),
type.displaySchema(markupDocBuilder),
ParameterUtils.getDefaultValue(parameter));
cells.add(content);
}
}
buildSectionTitle(PARAMETERS, docBuilder);
docBuilder.tableWithColumnSpecs(cols, cells);
}
return localDefinitions;
}
/**
* 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> localDefinitions = 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, new DefinitionDocumentResolverFromOperation());
buildSectionTitle(BODY_PARAMETER, docBuilder);
if (isNotBlank(parameter.getDescription())) {
docBuilder.paragraph(parameter.getDescription());
}
MarkupDocBuilder typeInfos = MarkupDocBuilders.documentBuilder(config.getMarkupLanguage(), config.getLineSeparator());
typeInfos.italicText(REQUIRED_COLUMN).textLine(": " + parameter.getRequired());
typeInfos.italicText(NAME_COLUMN).textLine(": " + parameter.getName());
if (!(type instanceof ObjectType)) {
typeInfos.italicText(TYPE_COLUMN).textLine(": " + type.displaySchema(docBuilder));
docBuilder.paragraph(typeInfos.toString());
} else {
docBuilder.paragraph(typeInfos.toString());
localDefinitions.addAll(buildPropertiesTable((ObjectType) type, operation.getId(), config.getInlineSchemaDepthLevel(), new PropertyDescriptor(type), new DefinitionDocumentResolverFromOperation(), docBuilder));
}
}
}
}
}
return localDefinitions;
}
/**
* Retrieves the description of a parameter, or otherwise an empty String.
* If hand-written descriptions exist, it tries to load the description from a file.
* If the file cannot be read, the description of the parameter is returned.
* Operation folder search order :
* - normalizeOperationFileName(operation.operationId)
* - then, normalizeOperationFileName(operation.method + " " + operation.path)
* - then, normalizeOperationFileName(operation.summary)
*
* @param operation the Swagger Operation
* @param parameter the Swagger Parameter
* @return the description of a parameter.
*/
private String parameterDescription(final PathOperation operation, Parameter parameter) {
if (config.isOperationDescriptionsEnabled()) {
final String parameterName = parameter.getName();
if (isNotBlank(parameterName)) {
Optional<String> description = handWrittenOperationDescription(new File(normalizeName(operation.getId()), parameterName).getPath(), DESCRIPTION_FILE_NAME);
if (!description.isPresent())
description = handWrittenOperationDescription(new File(normalizeName(operation.getTitle()), parameterName).getPath(), DESCRIPTION_FILE_NAME);
if (description.isPresent()) {
return description.get();
} else {
return defaultString(parameter.getDescription());
}
} else {
return defaultString(parameter.getDescription());
}
} else {
return defaultString(parameter.getDescription());
}
}
private void buildConsumesSection(PathOperation operation, MarkupDocBuilder docBuilder) {
List<String> consumes = operation.getOperation().getConsumes();
if (CollectionUtils.isNotEmpty(consumes)) {
buildSectionTitle(CONSUMES, docBuilder);
docBuilder.unorderedList(consumes);
}
}
private void buildProducesSection(PathOperation operation, MarkupDocBuilder docBuilder) {
List<String> produces = operation.getOperation().getProduces();
if (CollectionUtils.isNotEmpty(produces)) {
buildSectionTitle(PRODUCES, docBuilder);
docBuilder.unorderedList(produces);
}
}
private void buildTagsSection(PathOperation operation, MarkupDocBuilder docBuilder) {
if (config.getOperationsGroupedBy() == 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 sectionTile, MarkupDocBuilder docBuilder) {
if (exampleMap.size() > 0) {
buildSectionTitle(operationSectionTitle, docBuilder);
for (Map.Entry<String, Object> entry : exampleMap.entrySet()) {
buildSectionTitle(sectionTile + " " + entry.getKey(), docBuilder);
docBuilder.listing(Json.pretty(entry.getValue()));
}
}
}
/**
* 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();
if (CollectionUtils.isNotEmpty(securitySchemes)) {
buildSectionTitle(SECURITY, docBuilder);
Map<String, SecuritySchemeDefinition> securityDefinitions = globalContext.getSwagger().getSecurityDefinitions();
List<List<String>> cells = new ArrayList<>();
List<MarkupTableColumn> cols = Arrays.asList(
new MarkupTableColumn(TYPE_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1"),
new MarkupTableColumn(NAME_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1h"),
new MarkupTableColumn(SCOPES_COLUMN, 6).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^6"));
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(type, docBuilder.copy().crossReference(securityKey, securityKey).toString(),
Joiner.on(",").join(securityEntry.getValue()));
cells.add(content);
}
}
docBuilder.tableWithColumnSpecs(cols, cells);
}
}
/**
* Reads a hand-written description
*
* @param descriptionFolder the name of the folder where the description file resides
* @param descriptionFileName the name of the description file
* @return the content of the file
*/
private Optional<String> handWrittenOperationDescription(String descriptionFolder, String descriptionFileName) {
for (String fileNameExtension : config.getMarkupLanguage().getFileNameExtensions()) {
URI contentUri = config.getOperationDescriptionsUri().resolve(descriptionFolder).resolve(descriptionFileName + fileNameExtension);
try (Reader reader = io.github.robwin.swagger2markup.internal.utils.IOUtils.uriReader(contentUri)) {
if (logger.isInfoEnabled()) {
logger.info("Operation description content processed {}", contentUri);
}
return Optional.of(IOUtils.toString(reader).trim());
} catch (IOException e) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to read Operation description content {} > {}", contentUri, e.getMessage());
}
}
}
return Optional.absent();
}
private List<ObjectType> buildResponsesSection(PathOperation operation, MarkupDocBuilder docBuilder) {
Map<String, Response> responses = operation.getOperation().getResponses();
List<ObjectType> localDefinitions = new ArrayList<>();
if (MapUtils.isNotEmpty(responses)) {
buildSectionTitle(RESPONSES, docBuilder);
List<MarkupTableColumn> responseCols = Arrays.asList(
new MarkupTableColumn(HTTP_CODE_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1h"),
new MarkupTableColumn(DESCRIPTION_COLUMN, 3).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^3"),
new MarkupTableColumn(SCHEMA_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1"));
List<MarkupTableColumn> responseHeaderCols = Arrays.asList(
new MarkupTableColumn(NAME_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1h"),
new MarkupTableColumn(DESCRIPTION_COLUMN, 3).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^3"),
new MarkupTableColumn(SCHEMA_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1"),
new MarkupTableColumn(DEFAULT_COLUMN, 1).withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1"));
Set<String> responseNames = toKeySet(responses, config.getResponseOrdering());
for (String responseName : responseNames) {
List<List<String>> cells = new ArrayList<>();
List<List<String>> responseHeaderCells = new ArrayList<>();
Response response = responses.get(responseName);
if (response.getSchema() != null) {
Property property = response.getSchema();
Type type = PropertyUtils.getType(property, new DefinitionDocumentResolverFromOperation());
if (config.getInlineSchemaDepthLevel() > 0 && type instanceof ObjectType) {
if (MapUtils.isNotEmpty(((ObjectType) type).getProperties())) {
String localTypeName = RESPONSE + " " + responseName;
type.setName(localTypeName);
type.setUniqueName(operation.getId() + " " + localTypeName);
localDefinitions.add((ObjectType) type);
type = new RefType(type);
}
}
cells.add(Arrays.asList(responseName, response.getDescription(), type.displaySchema(markupDocBuilder)));
} else {
cells.add(Arrays.asList(responseName, response.getDescription(), NO_CONTENT));
}
buildResponseTitle(HTTP_CODE_COLUMN + " " + responseName, docBuilder);
docBuilder.tableWithColumnSpecs(responseCols, cells);
Map<String, Property> headers = response.getHeaders();
if(MapUtils.isNotEmpty(headers)) {
docBuilder.boldTextLine(HEADERS_COLUMN);
for(Map.Entry<String, Property> entry : headers.entrySet()){
Property property = entry.getValue();
Type propertyType = PropertyUtils.getType(property, null);
responseHeaderCells.add(Arrays.asList(entry.getKey(),
response.getDescription(),
propertyType.displaySchema(markupDocBuilder),
PropertyUtils.getDefaultValue(property)));
}
docBuilder.tableWithColumnSpecs(responseHeaderCols, responseHeaderCells);
}
}
}
return localDefinitions;
}
/**
* 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 depth current inline schema depth
* @param docBuilder the docbuilder do use for output
*/
private void inlineDefinitions(List<ObjectType> definitions, String uniquePrefix, int depth, MarkupDocBuilder docBuilder) {
if (CollectionUtils.isNotEmpty(definitions)) {
for (ObjectType definition : definitions) {
addInlineDefinitionTitle(definition.getName(), definition.getUniqueName(), docBuilder);
List<ObjectType> localDefinitions = buildPropertiesTable(definition, uniquePrefix, depth, new PropertyDescriptor(definition), new DefinitionDocumentResolverFromOperation(), docBuilder);
for (ObjectType localDefinition : localDefinitions)
inlineDefinitions(Collections.singletonList(localDefinition), uniquePrefix, depth - 1, 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,145 +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.robwin.swagger2markup.internal.document.builder;
import io.github.robwin.markup.builder.MarkupDocBuilder;
import io.github.robwin.markup.builder.MarkupTableColumn;
import io.github.robwin.swagger2markup.Swagger2MarkupConverter;
import io.github.robwin.swagger2markup.internal.document.MarkupDocument;
import io.github.robwin.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 org.apache.commons.lang3.StringUtils;
import java.nio.file.Path;
import java.util.*;
import static io.github.robwin.swagger2markup.spi.SecurityDocumentExtension.Context;
import static io.github.robwin.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 = "security";
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, Path outputPath) {
super(context, outputPath);
ResourceBundle labels = ResourceBundle.getBundle("io/github/robwin/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));
}
return new MarkupDocument(markupDocBuilder);
}
private void buildSecurityTitle(String title) {
this.markupDocBuilder.sectionTitleWithAnchorLevel1(title, SECURITY_ANCHOR);
}
private void buildSecuritySchemeDefinitionsSection(Map<String, SecuritySchemeDefinition> definitions) {
for (Map.Entry<String, SecuritySchemeDefinition> entry : definitions.entrySet()) {
String definitionName = entry.getKey();
SecuritySchemeDefinition definition = entry.getValue();
buildSecuritySchemeDefinitionTitle(definitionName);
applySecurityDocumentExtension(new Context(Position.DEFINITION_BEGIN, markupDocBuilder, definitionName, definition));
buildDescriptionParagraph(definition.getDescription());
buildSecurityScheme(definition);
applySecurityDocumentExtension(new Context(Position.DEFINITION_BEGIN, markupDocBuilder, definitionName, definition));
}
}
private void buildDescriptionParagraph(String description) {
if(StringUtils.isNotBlank(description)) {
markupDocBuilder.paragraph(description);
}
}
private MarkupDocBuilder buildSecuritySchemeDefinitionTitle(String definitionName) {
return markupDocBuilder.sectionTitleLevel2(definitionName);
}
private void buildSecurityScheme(SecuritySchemeDefinition securityScheme) {
String type = securityScheme.getType();
markupDocBuilder.textLine(TYPE + " : " + type);
if (securityScheme instanceof ApiKeyAuthDefinition) {
markupDocBuilder.textLine(NAME + " : " + ((ApiKeyAuthDefinition) securityScheme).getName());
markupDocBuilder.textLine(IN + " : " + ((ApiKeyAuthDefinition) securityScheme).getIn());
} else if (securityScheme instanceof OAuth2Definition) {
OAuth2Definition oauth2Scheme = (OAuth2Definition) securityScheme;
String flow = oauth2Scheme.getFlow();
markupDocBuilder.textLine(FLOW + " : " + flow);
if (isNotBlank(oauth2Scheme.getAuthorizationUrl())) {
markupDocBuilder.textLine(AUTHORIZATION_URL + " : " + oauth2Scheme.getAuthorizationUrl());
}
if (isNotBlank(oauth2Scheme.getTokenUrl())) {
markupDocBuilder.textLine(TOKEN_URL + " : " + oauth2Scheme.getTokenUrl());
}
List<List<String>> cells = new ArrayList<>();
List<MarkupTableColumn> cols = Arrays.asList(new MarkupTableColumn(NAME_COLUMN, 1),
new MarkupTableColumn(DESCRIPTION_COLUMN, 6));
for (Map.Entry<String, String> scope : oauth2Scheme.getScopes().entrySet()) {
List<String> content = Arrays.asList(scope.getKey(), scope.getValue());
cells.add(content);
}
markupDocBuilder.tableWithColumnSpecs(cols, cells);
}
}
/**
* Apply extension context to all SecurityContentExtension
*
* @param context context
*/
private void applySecurityDocumentExtension(Context context) {
for (SecurityDocumentExtension extension : globalContext.getExtensionRegistry().getExtensions(SecurityDocumentExtension.class)) {
extension.apply(context);
}
}
}

View File

@@ -1,98 +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.robwin.swagger2markup.internal.extensions;
import com.google.common.base.Optional;
import io.github.robwin.swagger2markup.Swagger2MarkupConverter;
import io.github.robwin.swagger2markup.spi.ContentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
class ContentExtension {
private static final Logger logger = LoggerFactory.getLogger(ContentExtension.class);
protected final Swagger2MarkupConverter.Context globalContext;
protected final ContentContext contentContext;
ContentExtension(Swagger2MarkupConverter.Context globalContext, ContentContext contentContext) {
this.globalContext = globalContext;
this.contentContext = contentContext;
}
/**
* Reads contents from a file
*
* @param contentPath content file path
* @return content reader
*/
protected Optional<Reader> readContentPath(Path contentPath) {
if (Files.isReadable(contentPath)) {
if (logger.isInfoEnabled()) {
logger.info("Content file {} processed", contentPath);
}
try {
Reader contentReader = new FileReader(contentPath.toFile());
return Optional.of(contentReader);
} catch (IOException e) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to read content file {} > {}", contentPath, e.getMessage());
}
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Failed to read content file {}", contentPath);
}
}
return Optional.absent();
}
/**
* Reads content from an Uri
*
* @param contentUri content file URI
* @return content reader
*/
protected Optional<Reader> readContentUri(URI contentUri) {
try {
Reader reader = io.github.robwin.swagger2markup.internal.utils.IOUtils.uriReader(contentUri);
if (logger.isInfoEnabled()) {
logger.info("Content URI {} processed", contentUri);
}
return Optional.of(reader);
} catch (IOException e) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to read content URI {} > {}", contentUri, e.getMessage());
}
}
return Optional.absent();
}
}

View File

@@ -1,97 +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.robwin.swagger2markup.internal.extensions;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import io.github.robwin.swagger2markup.Swagger2MarkupConverter;
import io.github.robwin.swagger2markup.spi.ContentContext;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
class DynamicContentExtension extends ContentExtension {
private static final Logger logger = LoggerFactory.getLogger(DynamicContentExtension.class);
DynamicContentExtension(Swagger2MarkupConverter.Context globalContext, ContentContext contentContext) {
super(globalContext, contentContext);
}
/**
* Builds extension sections
*
* @param contentPath the path where the content files reside
* @param prefix extension file prefix
* @param levelOffset import markup level offset
*/
public void extensionsSection(Path contentPath, final String prefix, int levelOffset) {
final Collection<String> filenameExtensions = Collections2.transform(globalContext.getConfig().getMarkupLanguage().getFileNameExtensions(), new Function<String, String>() {
public String apply(String input) {
return StringUtils.stripStart(input, ".");
}
});
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException {
String fileName = entry.getFileName().toString();
return fileName.startsWith(prefix) && FilenameUtils.isExtension(fileName, filenameExtensions);
}
};
try (DirectoryStream<Path> extensionFiles = Files.newDirectoryStream(contentPath, filter)) {
if (extensionFiles != null) {
List<Path> extensions = Lists.newArrayList(extensionFiles);
Collections.sort(extensions, Ordering.natural());
for (Path extension : extensions) {
Optional<Reader> extensionContent = readContentPath(extension);
if (extensionContent.isPresent()) {
try {
contentContext.getMarkupDocBuilder().importMarkup(extensionContent.get(), levelOffset);
} catch (IOException e) {
throw new RuntimeException(String.format("Failed to read extension file %s", extension), e);
} finally {
extensionContent.get().close();
}
}
}
}
} catch (IOException e) {
if (logger.isDebugEnabled())
logger.debug("Failed to read extension files from directory {}", contentPath);
}
}
}

View File

@@ -1,100 +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.robwin.swagger2markup.internal.extensions;
import io.github.robwin.swagger2markup.Swagger2MarkupConverter;
import io.github.robwin.swagger2markup.internal.utils.IOUtils;
import io.github.robwin.swagger2markup.spi.DefinitionsDocumentExtension;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Dynamically search for markup files in {@code contentPath} to append in Definitions, with the format :<br/>
* - {@code document-before-*.<markup.ext>} : import before Definitions document with levelOffset = 0<br/>
* - {@code document-begin-*.<markup.ext>} : import just after Definitions document main title with levelOffset = 1<br/>
* - {@code document-end-*.<markup.ext>} : import at the end of Definitions document with levelOffset = 1<br/>
* - {@code definition-begin-*.<markup.ext>} : import just after each definition title with levelOffset = 2<br/>
* - {@code definition-end-*.<markup.ext>} : import at the end of each definition with levelOffset = 2<br/>
* <p/>
* Markup files are appended in the natural order of their names, for each category.
*/
public final class DynamicDefinitionsDocumentExtension extends DefinitionsDocumentExtension {
private static final Logger logger = LoggerFactory.getLogger(DynamicDefinitionsDocumentExtension.class);
protected Path contentPath;
public DynamicDefinitionsDocumentExtension(Path contentPath) {
super();
Validate.notNull(contentPath);
this.contentPath = contentPath;
}
public DynamicDefinitionsDocumentExtension() {
super();
}
@Override
public void init(Swagger2MarkupConverter.Context globalContext) {
if (contentPath == null) {
if (globalContext.getSwaggerLocation() == null || !globalContext.getSwaggerLocation().getScheme().equals("file")) {
if (logger.isWarnEnabled())
logger.warn("Disable DynamicDefinitionsContentExtension > Can't set default contentPath from swaggerLocation. You have to explicitly configure the content path.");
} else {
contentPath = Paths.get(globalContext.getSwaggerLocation()).getParent();
}
}
}
@Override
public void apply(Context context) {
Validate.notNull(context);
if (contentPath != null) {
DynamicContentExtension dynamicContent = new DynamicContentExtension(globalContext, context);
DynamicDefinitionsDocumentExtension.Position position = context.getPosition();
switch (position) {
case DOCUMENT_BEFORE:
dynamicContent.extensionsSection(contentPath, contentPrefix(position), levelOffset(context));
break;
case DOCUMENT_BEGIN:
dynamicContent.extensionsSection(contentPath, contentPrefix(position), levelOffset(context));
break;
case DOCUMENT_END:
dynamicContent.extensionsSection(contentPath, contentPrefix(position), levelOffset(context));
break;
case DEFINITION_BEGIN:
dynamicContent.extensionsSection(contentPath.resolve(Paths.get(IOUtils.normalizeName(context.getDefinitionName().get()))), contentPrefix(position), levelOffset(context));
break;
case DEFINITION_END:
dynamicContent.extensionsSection(contentPath.resolve(Paths.get(IOUtils.normalizeName(context.getDefinitionName().get()))), contentPrefix(position), levelOffset(context));
break;
default:
throw new RuntimeException(String.format("Unknown position '%s'", position));
}
}
}
public String contentPrefix(Position position) {
return position.name().toLowerCase().replace('_', '-');
}
}

View File

@@ -1,92 +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.robwin.swagger2markup.internal.extensions;
import io.github.robwin.swagger2markup.Swagger2MarkupConverter;
import io.github.robwin.swagger2markup.spi.OverviewDocumentExtension;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Dynamically search for markup files in {@code contentPath} to append to Overview, with the format :<br/>
* - {@code document-before-*.<markup.ext>} : import before Overview document with levelOffset = 0<br/>
* - {@code document-begin-*.<markup.ext>} : import just after Overview document main title with levelOffset = 1<br/>
* - {@code document-end-*.<markup.ext>} : import at the end of Overview document with levelOffset = 1<br/>
* <p/>
* Markup files are appended in the natural order of their names, for each category.
*/
public final class DynamicOverviewDocumentExtension extends OverviewDocumentExtension {
private static final Logger logger = LoggerFactory.getLogger(DynamicOverviewDocumentExtension.class);
protected Path contentPath;
public DynamicOverviewDocumentExtension() {
super();
}
public DynamicOverviewDocumentExtension(Path contentPath) {
super();
Validate.notNull(contentPath);
this.contentPath = contentPath;
}
@Override
public void init(Swagger2MarkupConverter.Context globalContext) {
if (contentPath == null) {
if (globalContext.getSwaggerLocation() == null || !globalContext.getSwaggerLocation().getScheme().equals("file")) {
if (logger.isWarnEnabled())
logger.warn("Disable > DynamicOverviewContentExtension > Can't set default contentPath from swaggerLocation. You have to explicitly configure the content path.");
} else {
contentPath = Paths.get(globalContext.getSwaggerLocation()).getParent();
}
}
}
@Override
public void apply(Context context) {
Validate.notNull(context);
if (contentPath != null) {
DynamicContentExtension dynamicContent = new DynamicContentExtension(globalContext, context);
OverviewDocumentExtension.Position position = context.getPosition();
switch (position) {
case DOCUMENT_BEFORE:
dynamicContent.extensionsSection(contentPath, contentPrefix(position), levelOffset(context));
break;
case DOCUMENT_BEGIN:
dynamicContent.extensionsSection(contentPath, contentPrefix(position), levelOffset(context));
break;
case DOCUMENT_END:
dynamicContent.extensionsSection(contentPath, contentPrefix(position), levelOffset(context));
break;
default:
throw new RuntimeException(String.format("Unknown position '%s'", position));
}
}
}
private String contentPrefix(Position position) {
return position.name().toLowerCase().replace('_', '-');
}
}

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.robwin.swagger2markup.internal.extensions;
import io.github.robwin.swagger2markup.Swagger2MarkupConverter;
import io.github.robwin.swagger2markup.internal.utils.IOUtils;
import io.github.robwin.swagger2markup.spi.PathsDocumentExtension;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Dynamically search for markup files in {@code contentPath} to append to Operations, with the format :<br/>
* - {@code document-before-*.<markup.ext>} : import before Paths document with levelOffset = 0<br/>
* - {@code document-begin-*.<markup.ext>} : import just after Paths document main title with levelOffset = 1<br/>
* - {@code document-end-*.<markup.ext>} : import at the end of Paths document with levelOffset = 1<br/>
* - {@code operation-begin-*.<markup.ext>} : import just after each operation title with levelOffset = 2(GroupBy.AS_IS) | 3(GroupBy.TAGS)<br/>
* - {@code operation-end-*.<markup.ext>} : import at the end of each operation with levelOffset = 2(GroupBy.AS_IS) | 3(GroupBy.TAGS)<br/>
* <p/>
* Markup files are appended in the natural order of their names, for each category.
*/
public final class DynamicPathsDocumentExtension extends PathsDocumentExtension {
private static final Logger logger = LoggerFactory.getLogger(DynamicPathsDocumentExtension.class);
protected Path contentPath;
public DynamicPathsDocumentExtension() {
super();
}
public DynamicPathsDocumentExtension(Path contentPath) {
super();
Validate.notNull(contentPath);
this.contentPath = contentPath;
}
@Override
public void init(Swagger2MarkupConverter.Context globalContext) {
if (contentPath == null) {
if (globalContext.getSwaggerLocation() == null || !globalContext.getSwaggerLocation().getScheme().equals("file")) {
if (logger.isWarnEnabled())
logger.warn("Disable DynamicOperationsContentExtension > Can't set default contentPath from swaggerLocation. You have to explicitly configure the content path.");
} else {
contentPath = Paths.get(globalContext.getSwaggerLocation()).getParent();
}
}
}
@Override
public void apply(Context context) {
Validate.notNull(context);
if (contentPath != null) {
DynamicContentExtension dynamicContent = new DynamicContentExtension(globalContext, context);
PathsDocumentExtension.Position position = context.getPosition();
switch (position) {
case DOCUMENT_BEFORE:
dynamicContent.extensionsSection(contentPath, contentPrefix(position), levelOffset(context));
break;
case DOCUMENT_BEGIN:
dynamicContent.extensionsSection(contentPath, contentPrefix(position), levelOffset(context));
break;
case DOCUMENT_END:
dynamicContent.extensionsSection(contentPath, contentPrefix(position), levelOffset(context));
break;
case OPERATION_BEGIN:
dynamicContent.extensionsSection(contentPath.resolve(IOUtils.normalizeName(context.getOperation().get().getId())), contentPrefix(position), levelOffset(context));
break;
case OPERATION_END:
dynamicContent.extensionsSection(contentPath.resolve(IOUtils.normalizeName(context.getOperation().get().getId())), contentPrefix(position), levelOffset(context));
break;
default:
throw new RuntimeException(String.format("Unknown position '%s'", position));
}
}
}
private String contentPrefix(Position position) {
return position.name().toLowerCase().replace('_', '-');
}
}

View File

@@ -1,100 +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.robwin.swagger2markup.internal.extensions;
import io.github.robwin.swagger2markup.Swagger2MarkupConverter;
import io.github.robwin.swagger2markup.internal.utils.IOUtils;
import io.github.robwin.swagger2markup.spi.SecurityDocumentExtension;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Dynamically search for markup files in {@code contentPath} to append to Overview, with the format :<br/>
* - {@code document-before-*.<markup.ext>} : import before Overview document with levelOffset = 0<br/>
* - {@code document-begin-*.<markup.ext>} : import just after Overview document main title with levelOffset = 1<br/>
* - {@code document-end-*.<markup.ext>} : import at the end of Overview document with levelOffset = 1<br/>
* - {@code definition-begin-*.<markup.ext>} : import just after each definition title with levelOffset = 2<br/>
* - {@code definition-end-*.<markup.ext>} : import at the end of each definition with levelOffset = 2<br/>
* <p/>
* Markup files are appended in the natural order of their names, for each category.
*/
public final class DynamicSecurityDocumentExtension extends SecurityDocumentExtension {
private static final Logger logger = LoggerFactory.getLogger(DynamicSecurityDocumentExtension.class);
protected Path contentPath;
public DynamicSecurityDocumentExtension() {
super();
}
public DynamicSecurityDocumentExtension(Path contentPath) {
super();
Validate.notNull(contentPath);
this.contentPath = contentPath;
}
@Override
public void init(Swagger2MarkupConverter.Context globalContext) {
if (contentPath == null) {
if (globalContext.getSwaggerLocation() == null || !globalContext.getSwaggerLocation().getScheme().equals("file")) {
if (logger.isWarnEnabled())
logger.warn("Disable > DynamicSecurityContentExtension > Can't set default contentPath from swaggerLocation. You have to explicitly configure the content path.");
} else {
contentPath = Paths.get(globalContext.getSwaggerLocation()).getParent();
}
}
}
@Override
public void apply(Context context) {
Validate.notNull(context);
if (contentPath != null) {
DynamicContentExtension dynamicContent = new DynamicContentExtension(globalContext, context);
SecurityDocumentExtension.Position position = context.getPosition();
switch (position) {
case DOCUMENT_BEFORE:
dynamicContent.extensionsSection(contentPath, contentPrefix(position), levelOffset(context));
break;
case DOCUMENT_BEGIN:
dynamicContent.extensionsSection(contentPath, contentPrefix(position), levelOffset(context));
break;
case DOCUMENT_END:
dynamicContent.extensionsSection(contentPath, contentPrefix(position), levelOffset(context));
break;
case DEFINITION_BEGIN:
dynamicContent.extensionsSection(contentPath.resolve(IOUtils.normalizeName(context.getDefinitionName().get())), contentPrefix(position), levelOffset(context));
break;
case DEFINITION_END:
dynamicContent.extensionsSection(contentPath.resolve(IOUtils.normalizeName(context.getDefinitionName().get())), contentPrefix(position), levelOffset(context));
break;
default:
throw new RuntimeException(String.format("Unknown position '%s'", position));
}
}
}
private String contentPrefix(Position position) {
return position.name().toLowerCase().replace('_', '-');
}
}

View File

@@ -1,168 +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.robwin.swagger2markup.internal.extensions;
import com.google.common.base.Optional;
import io.github.robwin.swagger2markup.Swagger2MarkupConverter;
import io.github.robwin.swagger2markup.spi.DefinitionsDocumentExtension;
import io.github.robwin.swagger2markup.internal.utils.IOUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
/**
* Add external schemas to content.<br/>
* Supported formats are :
* <ul>
* <li>XML Schema (.xsd)</li>
* <li>JSON Schema (.json)</li>
* </ul>
*/
public final class SchemaExtension extends DefinitionsDocumentExtension {
private static final Logger logger = LoggerFactory.getLogger(SchemaExtension.class);
private static final List<SchemaMetadata> DEFAULT_SCHEMAS = new ArrayList<SchemaMetadata>() {{
add(new SchemaMetadata("JSON Schema", "json", "json"));
add(new SchemaMetadata("XML Schema", "xsd", "xml"));
}};
protected List<SchemaMetadata> schemas = new ArrayList<>();
protected URI schemaBaseUri;
public SchemaExtension(URI schemaBaseUri) {
super();
Validate.notNull(schemaBaseUri);
this.schemaBaseUri = schemaBaseUri;
}
public SchemaExtension() {
super();
}
public SchemaExtension withDefaultSchemas() {
schemas.addAll(DEFAULT_SCHEMAS);
return this;
}
public SchemaExtension withSchemas(List<SchemaMetadata> schemas) {
schemas.addAll(schemas);
return this;
}
@Override
public void init(Swagger2MarkupConverter.Context globalContext) {
if (schemaBaseUri == null) {
if (globalContext.getSwaggerLocation() == null) {
if (logger.isWarnEnabled())
logger.warn("Disable SchemaExtension > Can't set default schemaBaseUri from swaggerLocation. You have to explicitly configure the schemaBaseUri.");
} else {
schemaBaseUri = IOUtils.uriParent(globalContext.getSwaggerLocation());
}
}
}
@Override
public void apply(Context context) {
Validate.notNull(context);
if (schemaBaseUri != null) {
switch (context.getPosition()) {
case DOCUMENT_BEFORE:
case DOCUMENT_BEGIN:
case DOCUMENT_END:
case DEFINITION_BEGIN:
break;
case DEFINITION_END:
for (SchemaMetadata schema : DEFAULT_SCHEMAS) {
schemaSection(context, schema, levelOffset(context));
}
break;
default:
throw new RuntimeException(String.format("Unknown position '%s'", context.getPosition()));
}
}
}
/**
* Builds snippet URI for the given {@code definitionName} and {@code schema}.<br/>
* Default implementation use {@code <schemaBaseUri>/normalizeName(<definitionName>)/schema.<schema.extension>}.<br/>
* You can override this method to configure your own folder normalization.
*
* @param context current context
* @param definitionName current definition name
* @return subdirectory normalized name
*/
public URI definitionSchemaUri(Context context, String definitionName, SchemaMetadata schema) {
return schemaBaseUri.resolve(IOUtils.normalizeName(definitionName) + "/").resolve("schema" + (schema.extension != null ? "." + schema.extension : ""));
}
private void schemaSection(Context context, SchemaMetadata schema, int levelOffset) {
ContentExtension contentExtension = new ContentExtension(globalContext, context);
URI schemaUri = definitionSchemaUri(context, context.getDefinitionName().get(), schema);
try {
Optional<Reader> extensionContent = contentExtension.readContentUri(schemaUri);
if (extensionContent.isPresent()) {
try {
context.getMarkupDocBuilder().sectionTitleLevel(1 + levelOffset, schema.title);
context.getMarkupDocBuilder().listing(org.apache.commons.io.IOUtils.toString(extensionContent.get()).trim(), schema.language);
} catch (IOException e) {
throw new RuntimeException(String.format("Failed to read schema URI : %s", schemaUri), e);
} finally {
extensionContent.get().close();
}
}
} catch (IOException e) {
if (logger.isDebugEnabled())
logger.debug("Failed to read schema URI {}", schemaUri);
}
}
public static class SchemaMetadata {
/**
* Schema title
*/
public String title;
/**
* Schema file extension, without dot (e.g.: xsd).<br/>
* Set to null if there's no extension
*/
public String extension;
/**
* Schema content language (e.g.: xml)
*/
public String language;
public SchemaMetadata(String title, String extension, String language) {
this.title = title;
this.extension = extension;
this.language = language;
}
}
}

View File

@@ -1,150 +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.robwin.swagger2markup.internal.extensions;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import io.github.robwin.swagger2markup.internal.model.PathOperation;
import io.github.robwin.swagger2markup.Swagger2MarkupConverter;
import io.github.robwin.swagger2markup.spi.PathsDocumentExtension;
import io.github.robwin.swagger2markup.internal.utils.IOUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.Reader;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Append Spring Rest docs generated snippets to Operations content.
*/
public final class SpringRestDocsExtension extends PathsDocumentExtension {
private static final Logger logger = LoggerFactory.getLogger(SpringRestDocsExtension.class);
private static final Map<String, String> DEFAULT_SNIPPETS = new LinkedHashMap<String, String>() {{
put("http-request", "HTTP request");
put("http-response", "HTTP response");
put("curl-request", "Curl request");
}};
protected URI snippetBaseUri;
protected Map<String, String> snippets = new LinkedHashMap<>();
/**
* Instantiate extension
* @param snippetBaseUri base URI where are snippets are stored
*/
public SpringRestDocsExtension(URI snippetBaseUri) {
super();
Validate.notNull(snippetBaseUri);
this.snippetBaseUri = snippetBaseUri;
}
public SpringRestDocsExtension() {
super();
}
@Override
public void init(Swagger2MarkupConverter.Context globalContext) {
if (snippetBaseUri == null) {
if (globalContext.getSwaggerLocation() == null) {
if (logger.isWarnEnabled())
logger.warn("Disable SpringRestDocsExtension > Can't set default snippetBaseUri from swaggerLocation. You have to explicitly configure the snippetBaseUri.");
} else {
snippetBaseUri = IOUtils.uriParent(globalContext.getSwaggerLocation());
}
}
}
/**
* Add SpringRestDocs default snippets to list
* @return this instance
*/
public SpringRestDocsExtension withDefaultSnippets() {
snippets.putAll(DEFAULT_SNIPPETS);
return this;
}
/**
* Add an explicit list of snippets to display.
* @param snippets snippets to add. key is snippet name (without extension, e.g.: 'http-request'), value is a custom section title for the snippet.
* @return this instance
*/
public SpringRestDocsExtension withExplicitSnippets(Map<String, String> snippets) {
this.snippets.putAll(snippets);
return this;
}
/**
* Builds snippet URI for the given {@code operation} and {@code snippetName}.<br/>
* Default implementation use {@code <snippetBaseUri>/<normalizeName(<operation id>)>/<snippetName>.<markup ext>}.<br/>
* You can override this method to configure your own folder normalization.
*
* @param context current context
* @param operation current operation
* @return subdirectory normalized name
*/
public URI operationSnippetUri(Context context, PathOperation operation, String snippetName) {
return snippetBaseUri.resolve(IOUtils.normalizeName(operation.getId()) + "/").resolve(context.getMarkupDocBuilder().addFileExtension(snippetName));
}
@Override
public void apply(Context context) {
Validate.notNull(context);
switch (context.getPosition()) {
case OPERATION_END:
snippets(context);
break;
}
}
public void snippets(Context context) {
for (Map.Entry<String, String> snippets : this.snippets.entrySet()) {
snippetSection(context, snippets.getKey(), snippets.getValue());
}
}
public void snippetSection(Context context, String snippetName, String title) {
ContentExtension content = new ContentExtension(globalContext, context);
URI snippetUri = operationSnippetUri(context, context.getOperation().get(), snippetName);
Optional<Reader> snippetContent = content.readContentUri(snippetUri);
if (snippetContent.isPresent()) {
try {
context.getMarkupDocBuilder().sectionTitleLevel(1 + levelOffset(context), title);
context.getMarkupDocBuilder().importMarkup(snippetContent.get(), levelOffset(context) + 1);
} catch (IOException e) {
throw new RuntimeException(String.format("Failed to process snippet URI : %s", snippetUri), e);
} finally {
try {
snippetContent.get().close();
} catch (IOException e) {
Throwables.propagate(e);
}
}
}
}
}

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.robwin.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,284 +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.robwin.swagger2markup.internal.utils;
import io.github.robwin.markup.builder.MarkupDocBuilder;
import io.github.robwin.swagger2markup.internal.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.util.HashMap;
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
*
* @param operation the Swagger Operation
* @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 HashMap<>();
Map<String, Response> responses = operation.getResponses();
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 examples for request
*
* @param pathOperation the Swagger Operation
* @return an Optional with the example content
*/
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 HashMap<>();
// 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 = PropertyUtils.convertExample(item.getExample(), item.getType());
if (abstractSerializableParameterExample == null) {
abstractSerializableParameterExample = PropertyUtils.generateExample(item, markupDocBuilder);
}
}
if (abstractSerializableParameterExample == null) {
abstractSerializableParameterExample = ParameterUtils.generateExample((AbstractSerializableParameter)parameter, markupDocBuilder);
}
}
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 HashMap<>();
}
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 simpleRef the simple reference string
* @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();
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 map of properties
* @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 HashMap<>();
for (Map.Entry<String, Property> property : properties.entrySet()) {
Object exampleObject = PropertyUtils.convertExample(property.getValue().getExample(), property.getValue().getType());
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 HashMap<>();
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[]{PropertyUtils.convertExample(itemProperty.getExample(), itemProperty.getType())};
} 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
* @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[]{PropertyUtils.convertExample(property.getExample(), property.getType())};
} 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.robwin.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,50 +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.robwin.swagger2markup.internal.utils;
import com.google.common.base.Function;
import io.github.robwin.swagger2markup.internal.type.ArrayType;
import io.github.robwin.swagger2markup.internal.type.ObjectType;
import io.github.robwin.swagger2markup.internal.type.RefType;
import io.github.robwin.swagger2markup.internal.type.Type;
import io.swagger.models.ArrayModel;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.RefModel;
import org.apache.commons.lang3.Validate;
public final class ModelUtils {
/**
* Retrieves the type of a model, or otherwise null
*
* @param model the model
* @return the type of the model, or otherwise null
*/
public static Type getType(Model model, Function<String, String> definitionDocumentResolver) {
Validate.notNull(model, "model must not be null!");
if (model instanceof ModelImpl) {
return new ObjectType(null, model.getProperties());
} else if (model instanceof RefModel) {
String simpleRef = ((RefModel) model).getSimpleRef();
return new RefType(definitionDocumentResolver.apply(simpleRef), simpleRef);
} else if (model instanceof ArrayModel) {
ArrayModel arrayModel = ((ArrayModel) model);
return new ArrayType(null, PropertyUtils.getType(arrayModel.getItems(), definitionDocumentResolver));
}
return null;
}
}

View File

@@ -1,113 +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.robwin.swagger2markup.internal.utils;
import com.google.common.base.Function;
import io.github.robwin.markup.builder.MarkupDocBuilder;
import io.github.robwin.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 static org.apache.commons.lang3.StringUtils.defaultString;
public final class ParameterUtils {
/**
* Retrieves the type of a parameter, or otherwise null
*
* @param parameter the parameter
* @return the type of the parameter, or otherwise null
*/
public static Type getType(Parameter parameter, 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, definitionDocumentResolver);
}else{
type = new BasicType("string");
}
}
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(), serializableParameter.getFormat());
}
if(type.getName().equals("array")){
String collectionFormat = serializableParameter.getCollectionFormat();
type = new ArrayType(null, PropertyUtils.getType(serializableParameter.getItems(), definitionDocumentResolver), collectionFormat);
}
}
else if(parameter instanceof RefParameter){
String simpleRef = ((RefParameter)parameter).getSimpleRef();
type = new RefType(definitionDocumentResolver.apply(simpleRef), simpleRef);
}
return type;
}
/**
* Retrieves the default value of a parameter, or otherwise an empty String
*
* @param parameter the parameter
* @return the default value of the parameter, or otherwise an empty String
*/
public static String getDefaultValue(Parameter parameter){
Validate.notNull(parameter, "parameter must not be null!");
String defaultValue = "";
if(parameter instanceof AbstractSerializableParameter){
AbstractSerializableParameter serializableParameter = (AbstractSerializableParameter)parameter;
defaultValue = serializableParameter.getDefaultValue();
}
return defaultString(defaultValue);
}
/**
* Generate a default example value for parameter.
*
* @param parameter parameter
* @param markupDocBuilder doc builder
* @return a generated example for the parameter
*/
public static Object generateExample(AbstractSerializableParameter parameter, MarkupDocBuilder markupDocBuilder) {
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,195 +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.robwin.swagger2markup.internal.utils;
import com.google.common.base.Function;
import io.github.robwin.markup.builder.MarkupDocBuilder;
import io.github.robwin.swagger2markup.internal.type.*;
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.*;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public final class PropertyUtils {
/**
* Retrieves the type and format of a property.
*
* @param property the property
* @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(null, null); // FIXME : Workaround for https://github.com/swagger-api/swagger-parser/issues/177
else
type = new RefType(definitionDocumentResolver.apply(refProperty.getSimpleRef()), refProperty.getSimpleRef());
} else if (property instanceof ArrayProperty) {
ArrayProperty arrayProperty = (ArrayProperty) property;
Property items = arrayProperty.getItems();
type = new ArrayType(null, getType(items, definitionDocumentResolver));
} else if (property instanceof StringProperty) {
StringProperty stringProperty = (StringProperty) property;
List<String> enums = stringProperty.getEnum();
if (CollectionUtils.isNotEmpty(enums)) {
type = new EnumType(null, enums);
} else {
type = new BasicType(property.getType());
}
} else if (property instanceof ObjectProperty) {
type = new ObjectType(null, ((ObjectProperty) property).getProperties());
} else {
if (isNotBlank(property.getFormat())) {
type = new BasicType(property.getType(), property.getFormat());
} else {
type = new BasicType(property.getType());
}
}
return type;
}
/**
* Retrieves the default value of a property, or otherwise returns an empty String.
*
* @param property the property
* @return the default value of the property, or otherwise an empty String
*/
public static String getDefaultValue(Property property) {
Validate.notNull(property, "property must not be null");
String defaultValue = "";
if (property instanceof BooleanProperty) {
BooleanProperty booleanProperty = (BooleanProperty) property;
defaultValue = Objects.toString(booleanProperty.getDefault(), "");
} else if (property instanceof StringProperty) {
StringProperty stringProperty = (StringProperty) property;
defaultValue = Objects.toString(stringProperty.getDefault(), "");
} else if (property instanceof DoubleProperty) {
DoubleProperty doubleProperty = (DoubleProperty) property;
defaultValue = Objects.toString(doubleProperty.getDefault(), "");
} else if (property instanceof FloatProperty) {
FloatProperty floatProperty = (FloatProperty) property;
defaultValue = Objects.toString(floatProperty.getDefault(), "");
} else if (property instanceof IntegerProperty) {
IntegerProperty integerProperty = (IntegerProperty) property;
defaultValue = Objects.toString(integerProperty.getDefault(), "");
} else if (property instanceof LongProperty) {
LongProperty longProperty = (LongProperty) property;
defaultValue = Objects.toString(longProperty.getDefault(), "");
} else if (property instanceof UUIDProperty) {
UUIDProperty uuidProperty = (UUIDProperty) property;
defaultValue = Objects.toString(uuidProperty.getDefault(), "");
}
return defaultValue;
}
/**
* Return example display string for the given {@code property}.
*
* @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 = convertExample(property.getExample(), property.getType());
} 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().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.robwin.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.robwin.swagger2markup.internal.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,108 +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.robwin.swagger2markup.spi;
import com.google.common.base.Optional;
import io.github.robwin.markup.builder.MarkupDocBuilder;
import io.github.robwin.swagger2markup.GroupBy;
import io.github.robwin.swagger2markup.internal.model.PathOperation;
import org.apache.commons.lang3.Validate;
/**
* A SecurityContentExtension can be used to extend the paths document.
*/
public abstract class PathsDocumentExtension extends AbstractExtension {
public enum Position {
DOCUMENT_BEFORE,
DOCUMENT_BEGIN,
DOCUMENT_END,
OPERATION_BEGIN,
OPERATION_END
}
public static class Context extends ContentContext {
private Position position;
/**
* null if position == DOC_*
*/
private PathOperation operation;
/**
* @param position the current position
* @param docBuilder the MarkupDocBuilder
*/
public Context(Position position, MarkupDocBuilder docBuilder) {
super(docBuilder);
Validate.isTrue(position != Position.OPERATION_BEGIN && position != Position.OPERATION_END, "You must provide an operation for this position");
this.position = position;
}
/**
* @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.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_BEGIN:
case DOCUMENT_END:
levelOffset = 1;
break;
case OPERATION_BEGIN:
case OPERATION_END:
levelOffset = 2;
break;
default:
throw new RuntimeException(String.format("Unknown position '%s'", context.position));
}
if (globalContext.getConfig().getOperationsGroupedBy() == GroupBy.TAGS) {
levelOffset++;
}
return levelOffset;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016 Robert Winkler
* Copyright 2017 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,9 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.robwin.swagger2markup;
package io.github.swagger2markup;
public enum GroupBy {
AS_IS,
TAGS
TAGS,
REGEX
}

View File

@@ -0,0 +1,110 @@
/*
* Copyright 2017 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.ResourceBundle;
public class Labels {
public static final String DEFAULT_COLUMN = "default_column";
public static final String MAXLENGTH_COLUMN = "maxlength_column";
public static final String MINLENGTH_COLUMN = "minlength_column";
public static final String LENGTH_COLUMN = "length_column";
public static final String PATTERN_COLUMN = "pattern_column";
public static final String MINVALUE_COLUMN = "minvalue_column";
public static final String MINVALUE_EXCLUSIVE_COLUMN = "minvalue_exclusive_column";
public static final String MAXVALUE_COLUMN = "maxvalue_column";
public static final String MAXVALUE_EXCLUSIVE_COLUMN = "maxvalue_exclusive_column";
public static final String EXAMPLE_COLUMN = "example_column";
public static final String SCHEMA_COLUMN = "schema_column";
public static final String NAME_COLUMN = "name_column";
public static final String DESCRIPTION_COLUMN = "description_column";
public static final String SCOPES_COLUMN = "scopes_column";
public static final String DESCRIPTION = DESCRIPTION_COLUMN;
public static final String PRODUCES = "produces";
public static final String CONSUMES = "consumes";
public static final String TAGS = "tags";
public static final String NO_CONTENT = "no_content";
public static final String FLAGS_COLUMN = "flags.column";
public static final String FLAGS_REQUIRED = "flags.required";
public static final String FLAGS_OPTIONAL = "flags.optional";
public static final String FLAGS_READ_ONLY = "flags.read_only";
// Overview Document
public static final String CONTACT_INFORMATION = "contact_information";
public static final String CONTACT_NAME = "contact_name";
public static final String CONTACT_EMAIL = "contact_email";
public static final String LICENSE_INFORMATION = "license_information";
public static final String LICENSE = "license";
public static final String LICENSE_URL = "license_url";
public static final String TERMS_OF_SERVICE = "terms_of_service";
public static final String CURRENT_VERSION = "current_version";
public static final String VERSION = "version";
public static final String OVERVIEW = "overview";
public static final String URI_SCHEME = "uri_scheme";
public static final String HOST = "host";
public static final String BASE_PATH = "base_path";
public static final String SCHEMES = "schemes";
//Security Document
public static final String SECURITY = "security";
public static final String TYPE = "security_type";
public static final String NAME = "security_name";
public static final String IN = "security_in";
public static final String FLOW = "security_flow";
public static final String AUTHORIZATION_URL = "security_authorizationUrl";
public static final String TOKEN_URL = "security_tokenUrl";
//Definitions Document
public static final String DEFINITIONS = "definitions";
public static final String POLYMORPHISM_COLUMN = "polymorphism.column";
public static final String POLYMORPHISM_DISCRIMINATOR_COLUMN = "polymorphism.discriminator";
public static final String TYPE_COLUMN = "type_column";
public static final String POLYMORPHISM_NATURE_COMPOSITION = "polymorphism.nature.COMPOSITION";
public static final String POLYMORPHISM_NATURE_INHERITANCE = "polymorphism.nature.INHERITANCE";
//Paths Document
public static final String RESPONSE = "response";
public static final String REQUEST = "request";
public static final String PATHS = "paths";
public static final String RESOURCES = "resources";
public static final String OPERATIONS = "operations";
public static final String PARAMETERS = "parameters";
public static final String BODY_PARAMETER = "body_parameter";
public static final String RESPONSES = "responses";
public static final String HEADERS_COLUMN = "headers_column";
public static final String EXAMPLE_REQUEST = "example_request";
public static final String EXAMPLE_RESPONSE = "example_response";
public static final String HTTP_CODE_COLUMN = "http_code_column";
public static final String DEPRECATED_OPERATION = "operation.deprecated";
public static final String UNKNOWN = "unknown";
private ResourceBundle resourceBundle;
public Labels(Swagger2MarkupConfig config) {
this.resourceBundle = ResourceBundle.getBundle("io/github/swagger2markup/lang/labels", config.getOutputLanguage().toLocale());
}
/**
* Gets a label for the given key from this resource bundle.
*
* @param key the key for the desired label
* @return the label for the given key
*/
public String getLabel(String key) {
return resourceBundle.getString(key);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016 Robert Winkler
* Copyright 2017 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package io.github.robwin.swagger2markup;
package io.github.swagger2markup;
import java.util.Locale;
@@ -22,9 +22,15 @@ import java.util.Locale;
* @author Maksim Myshkin
*/
public enum Language {
EN(new Locale("en")),
EN(Locale.ENGLISH),
RU(new Locale("ru")),
FR(new Locale("fr"));
FR(Locale.FRENCH),
DE(Locale.GERMAN),
TR(new Locale("tr")),
ZH(Locale.CHINESE),
ES(new Locale("es")),
BR(new Locale("pt", "BR")),
JA(Locale.JAPANESE);
private final Locale lang;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016 Robert Winkler
* Copyright 2017 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.robwin.swagger2markup;
package io.github.swagger2markup;
public enum OrderBy {
AS_IS,

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2017 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 PageBreakLocations {
BEFORE_OPERATION,
BEFORE_OPERATION_DESCRIPTION,
BEFORE_OPERATION_PARAMETERS,
BEFORE_OPERATION_RESPONSES,
BEFORE_OPERATION_CONSUMES,
BEFORE_OPERATION_PRODUCES,
BEFORE_OPERATION_EXAMPLE_REQUEST,
BEFORE_OPERATION_EXAMPLE_RESPONSE,
BEFORE_DEFINITION,
AFTER_OPERATION,
AFTER_OPERATION_DESCRIPTION,
AFTER_OPERATION_PARAMETERS,
AFTER_OPERATION_RESPONSES,
AFTER_OPERATION_CONSUMES,
AFTER_OPERATION_PRODUCES,
AFTER_OPERATION_EXAMPLE_REQUEST,
AFTER_OPERATION_EXAMPLE_RESPONSE,
AFTER_DEFINITION
}

View File

@@ -0,0 +1,243 @@
/*
* Copyright 2017 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;
import java.util.List;
import java.util.regex.Pattern;
/**
* 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();
/**
* Prepend the base path to all paths.
*/
boolean isBasePathPrefixEnabled();
/**
* 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 the regex pattern used for header matching
*/
Pattern getHeaderPattern();
/**
* 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 disable the security section for path sections
*/
boolean isPathSecuritySectionEnabled();
/**
* 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();
/**
* Specifies the array element delimiter to use for multi-valued properties.
* @return the element delimiter if any
*/
Character getListDelimiter();
/**
* Optionally allow lists in property values. Uses the {{@link #getListDelimiter()} to
* delimit list values.
* @return whether lists are converted to arrays
*/
boolean isListDelimiterEnabled();
/**
* Returns properties for extensions.
*
* @return the extension properties
*/
Swagger2MarkupProperties getExtensionsProperties();
/**
* Returns the list of page break locations
*
* @return List of PageBreakLocations
*/
List<PageBreakLocations> getPageBreakLocations();
}

View File

@@ -0,0 +1,422 @@
/*
* Copyright 2017 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.DefinitionsDocument;
import io.github.swagger2markup.internal.document.OverviewDocument;
import io.github.swagger2markup.internal.document.PathsDocument;
import io.github.swagger2markup.internal.document.SecurityDocument;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.markup.builder.MarkupDocBuilders;
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 final Context context;
private final OverviewDocument overviewDocument;
private final PathsDocument pathsDocument;
private final DefinitionsDocument definitionsDocument;
private final SecurityDocument securityDocument;
public Swagger2MarkupConverter(Context context) {
this.context = context;
this.overviewDocument = new OverviewDocument(context);
this.pathsDocument = new PathsDocument(context);
this.definitionsDocument = new DefinitionsDocument(context);
this.securityDocument = new SecurityDocument(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);
}
/**
* Returns the global Context
*
* @return the global Context
*/
public Context getContext() {
return context;
}
/**
* 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");
context.setOutputPath(outputDirectory);
applyOverviewDocument()
.writeToFile(outputDirectory.resolve(context.config.getOverviewDocument()), StandardCharsets.UTF_8);
applyPathsDocument()
.writeToFile(outputDirectory.resolve(context.config.getPathsDocument()), StandardCharsets.UTF_8);
applyDefinitionsDocument()
.writeToFile(outputDirectory.resolve(context.config.getDefinitionsDocument()), StandardCharsets.UTF_8);
applySecurityDocument()
.writeToFile(outputDirectory.resolve(context.config.getSecurityDocument()), StandardCharsets.UTF_8);
}
private MarkupDocBuilder applyOverviewDocument() {
return overviewDocument.apply(
context.createMarkupDocBuilder(),
OverviewDocument.parameters(context.getSwagger()));
}
private MarkupDocBuilder applyPathsDocument() {
return pathsDocument.apply(
context.createMarkupDocBuilder(),
PathsDocument.parameters(context.getSwagger().getPaths()));
}
private MarkupDocBuilder applyDefinitionsDocument() {
return definitionsDocument.apply(
context.createMarkupDocBuilder(),
DefinitionsDocument.parameters(context.getSwagger().getDefinitions()));
}
private MarkupDocBuilder applySecurityDocument() {
return securityDocument.apply(
context.createMarkupDocBuilder(),
SecurityDocument.parameters(context.getSwagger().getSecurityDefinitions()));
}
/**
* 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");
applyOverviewDocument().writeToFile(outputFile, StandardCharsets.UTF_8);
applyPathsDocument().writeToFile(outputFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
applyDefinitionsDocument().writeToFile(outputFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
applySecurityDocument().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");
applyOverviewDocument().writeToFileWithoutExtension(outputFile, StandardCharsets.UTF_8);
applyPathsDocument().writeToFileWithoutExtension(outputFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
applyDefinitionsDocument().writeToFileWithoutExtension(outputFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
applySecurityDocument().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(applyOverviewDocument().toString());
sb.append(applyPathsDocument().toString());
sb.append(applyDefinitionsDocument().toString());
sb.append(applySecurityDocument().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, extensionRegistry, swagger, swaggerLocation);
initExtensions(context);
applySwaggerExtensions(context);
return new Swagger2MarkupConverter(context);
}
private void initExtensions(Context context) {
extensionRegistry.getSwaggerModelExtensions().forEach(extension -> extension.setGlobalContext(context));
extensionRegistry.getOverviewDocumentExtensions().forEach(extension -> extension.setGlobalContext(context));
extensionRegistry.getDefinitionsDocumentExtensions().forEach(extension -> extension.setGlobalContext(context));
extensionRegistry.getPathsDocumentExtensions().forEach(extension -> extension.setGlobalContext(context));
extensionRegistry.getSecurityDocumentExtensions().forEach(extension -> extension.setGlobalContext(context));
}
private void applySwaggerExtensions(Context context) {
extensionRegistry.getSwaggerModelExtensions().forEach(extension -> extension.apply(context.getSwagger()));
}
}
public static class Context {
private final Swagger2MarkupConfig config;
private final Swagger swagger;
private final URI swaggerLocation;
private final Swagger2MarkupExtensionRegistry extensionRegistry;
private final Labels labels;
private Path outputPath;
public Context(Swagger2MarkupConfig config,
Swagger2MarkupExtensionRegistry extensionRegistry,
Swagger swagger,
URI swaggerLocation) {
this.config = config;
this.extensionRegistry = extensionRegistry;
this.swagger = swagger;
this.swaggerLocation = swaggerLocation;
this.labels = new Labels(config);
}
public Swagger2MarkupConfig getConfig() {
return config;
}
public Swagger getSwagger() {
return swagger;
}
public URI getSwaggerLocation() {
return swaggerLocation;
}
public Swagger2MarkupExtensionRegistry getExtensionRegistry() {
return extensionRegistry;
}
public Labels getLabels() {
return labels;
}
public MarkupDocBuilder createMarkupDocBuilder() {
return MarkupDocBuilders.documentBuilder(config.getMarkupLanguage(),
config.getLineSeparator()).withAnchorPrefix(config.getAnchorPrefix());
}
public Path getOutputPath() {
return outputPath;
}
public void setOutputPath(Path outputPath) {
this.outputPath = outputPath;
}
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright 2017 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

@@ -0,0 +1,383 @@
/*
* Copyright 2017 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 org.apache.commons.configuration2.ex.ConversionException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Pattern;
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 BASE_PATH_PREFIX_ENABLED = PROPERTIES_PREFIX + ".basePathPrefixEnabled";
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 HEADER_REGEX = PROPERTIES_PREFIX + ".headerRegex";
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 PATH_SECURITY_SECTION_ENABLED = PROPERTIES_PREFIX + ".pathSecuritySectionEnabled";
public static final String ANCHOR_PREFIX = PROPERTIES_PREFIX + ".anchorPrefix";
public static final String LIST_DELIMITER = PROPERTIES_PREFIX + ".listDelimiter";
public static final String LIST_DELIMITER_ENABLED = PROPERTIES_PREFIX + ".listDelimiterEnabled";
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";
public static final String PAGE_BREAK_LOCATIONS = PROPERTIES_PREFIX + ".pageBreakLocations";
/**
* 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}).
*
* @return The int property
* @throws IllegalStateException if the key cannot be
*/
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}).
*
* @return The boolean property
* @throws IllegalStateException if the key cannot be resolved
*/
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
* @return The URI property
* @throws IllegalStateException if the value cannot be mapped to the enum
*/
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}).
*
* @return The URI property
* @throws IllegalStateException if the key cannot be resolved
*/
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
* @return The Path property
* @throws IllegalStateException if the value cannot be mapped to the enum
*/
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 a list of Path property values associated with the given key,
* or {@code defaultValue} if the key cannot be resolved.
*
* @param key the property name to resolve
* @return The list of Path properties
* @throws IllegalStateException if the value cannot be mapped to an array of strings
*/
public List<Path> getPathList(String key) {
List<Path> pathList = new ArrayList<>();
try {
String[] stringList = configuration.getStringArray(key);
for (String pathStr : stringList) {
pathList.add(Paths.get(pathStr));
}
} catch (ConversionException ce) {
throw new IllegalStateException(String.format("requested key [%s] is not convertable to an array", key));
}
return pathList;
}
/**
* Return the Path property value associated with the given key (never {@code null}).
*
* @return The Path property
* @throws IllegalStateException if the key cannot be resolved
*/
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}).
*
* @return The MarkupLanguage property
* @throws IllegalStateException if the key cannot be resolved
*/
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
* @return The GroupBy property
* @throws IllegalStateException if the value cannot be mapped to the enum
*/
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
* @return The OrderBy property
* @throws IllegalStateException if the value cannot be mapped to the enum
*/
public OrderBy getOrderBy(String key) {
return OrderBy.valueOf(configuration.getString(key));
}
/**
* Return the String property value associated with the given key (never {@code null}).
*
* @return The String property
* @throws IllegalStateException if the key cannot be resolved
*/
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));
}
public List<PageBreakLocations> getPageBreakLocations(String key) {
List<PageBreakLocations> result = configuration.getList(PageBreakLocations.class, key);
if(result == null) result = new ArrayList<PageBreakLocations>();
return result;
}
public Optional<Pattern> getHeaderPattern(String key) {
Optional<String> property = getString(key);
if (property.isPresent()) {
return Optional.of(Pattern.compile(property.get()));
} else {
return Optional.empty();
}
}
}

View File

@@ -0,0 +1,787 @@
/*
* Copyright 2017 Robert Winkler
* Modified December 12 2016 by Cas Eliëns
*
* 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.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.convert.DefaultListDelimiterHandler;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import static io.github.swagger2markup.Swagger2MarkupProperties.*;
public class Swagger2MarkupConfigBuilder {
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(PathOperation::getMethod);
static final Ordering<PathOperation> OPERATION_PATH_NATURAL_ORDERING = Ordering
.natural()
.onResultOf(PathOperation::getPath);
static final Ordering<Parameter> PARAMETER_IN_NATURAL_ORDERING = Ordering
.explicit("header", "path", "query", "formData", "body")
.onResultOf(Parameter::getIn);
static final Ordering<Parameter> PARAMETER_NAME_NATURAL_ORDERING = Ordering
.natural()
.onResultOf(Parameter::getName);
private static final String PROPERTIES_DEFAULT = "io/github/swagger2markup/config/default.properties";
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.basePathPrefixEnabled = swagger2MarkupProperties.getRequiredBoolean(BASE_PATH_PREFIX_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.pathSecuritySectionEnabled = swagger2MarkupProperties.getRequiredBoolean(PATH_SECURITY_SECTION_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());
}
config.pageBreakLocations = swagger2MarkupProperties.getPageBreakLocations(PAGE_BREAK_LOCATIONS);
Optional<Pattern> headerPattern = swagger2MarkupProperties.getHeaderPattern(HEADER_REGEX);
config.headerPattern = headerPattern.orElse(null);
config.listDelimiterEnabled = swagger2MarkupProperties.getBoolean(LIST_DELIMITER_ENABLED, false);
config.listDelimiter = swagger2MarkupProperties.getString(LIST_DELIMITER, ",").charAt(0);
if (config.listDelimiterEnabled && configuration instanceof AbstractConfiguration) {
((AbstractConfiguration)configuration).setListDelimiterHandler(new DefaultListDelimiterHandler(config.listDelimiter));
}
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;
}
/**
* Allows properties to contain a list of elements delimited by a specified character.
* @return this builder
*/
public Swagger2MarkupConfigBuilder withListDelimiter() {
config.listDelimiterEnabled = true;
return this;
}
/**
* Specifies the list delimiter which should be used.
*
* @param delimiter the delimiter
* @return this builder
*/
public Swagger2MarkupConfigBuilder withListDelimiter(Character delimiter) {
Validate.notNull(delimiter, "%s must not be null", "delimiter");
config.listDelimiter = delimiter;
config.listDelimiterEnabled = 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 the regex pattern to use for grouping paths.
*
* @param headerRegex regex pattern string containing one capture group
* @return this builder
* @throws PatternSyntaxException when pattern cannot be compiled
*/
public Swagger2MarkupConfigBuilder withHeaderRegex(String headerRegex) {
Validate.notNull(headerRegex, "%s must not be null", headerRegex);
config.headerPattern = Pattern.compile(headerRegex);
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 disable the security section for path sections
*
* @return this builder
*/
public Swagger2MarkupConfigBuilder withoutPathSecuritySection() {
config.pathSecuritySectionEnabled = false;
return this;
}
/**
* Prepend the base path to all paths.
*
* @return this builder
*/
public Swagger2MarkupConfigBuilder withBasePathPrefix() {
config.basePathPrefixEnabled = 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 not be null", "anchorPrefix");
config.anchorPrefix = anchorPrefix;
return this;
}
/**
* Set the page break locations
*
* @param locations List of locations to create new pages
* @return this builder
*/
public Swagger2MarkupConfigBuilder withPageBreaks(List<PageBreakLocations> locations) {
Validate.notNull(locations, "%s must not be null", "locations");
config.pageBreakLocations = locations;
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 basePathPrefixEnabled;
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 boolean pathSecuritySectionEnabled;
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 Character listDelimiter;
private boolean listDelimiterEnabled;
private List<PageBreakLocations> pageBreakLocations;
private Pattern headerPattern;
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 Pattern getHeaderPattern() {
return headerPattern;
}
@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 boolean isPathSecuritySectionEnabled() {
return pathSecuritySectionEnabled;
}
@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 Character getListDelimiter() {
return listDelimiter;
}
@Override
public boolean isListDelimiterEnabled() {
return listDelimiterEnabled;
}
@Override
public Swagger2MarkupProperties getExtensionsProperties() {
return extensionsProperties;
}
@Override
public boolean isBasePathPrefixEnabled() {
return basePathPrefixEnabled;
}
@Override
public List<PageBreakLocations> getPageBreakLocations() {
return pageBreakLocations;
}
}
}

View File

@@ -0,0 +1,128 @@
/*
* Copyright 2017 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

@@ -0,0 +1,205 @@
/*
* Copyright 2017 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.adapter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.github.swagger2markup.Swagger2MarkupConfig;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.internal.resolver.DocumentResolver;
import io.github.swagger2markup.internal.type.*;
import io.github.swagger2markup.internal.utils.InlineSchemaUtils;
import io.github.swagger2markup.internal.utils.ModelUtils;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.model.PathOperation;
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 io.swagger.util.Json;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.text.WordUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.*;
public class ParameterAdapter {
private final Parameter parameter;
private final List<ObjectType> inlineDefinitions = new ArrayList<>();
private final Swagger2MarkupConfig config;
private Type type;
public ParameterAdapter(Swagger2MarkupConverter.Context context,
PathOperation operation,
Parameter parameter,
DocumentResolver definitionDocumentResolver) {
Validate.notNull(parameter, "parameter must not be null");
this.parameter = parameter;
type = getType(context.getSwagger().getDefinitions(), definitionDocumentResolver);
config = context.getConfig();
if (config.isInlineSchemaEnabled()) {
if (config.isFlatBodyEnabled()) {
if (!(type instanceof ObjectType)) {
type = InlineSchemaUtils.createInlineType(type, parameter.getName(), operation.getId() + " " + parameter.getName(), inlineDefinitions);
}
} else {
type = InlineSchemaUtils.createInlineType(type, parameter.getName(), operation.getId() + " " + parameter.getName(), inlineDefinitions);
}
}
}
/**
* 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();
}
}
@JsonIgnore
public String getAccess() {
return parameter.getAccess();
}
public String getName() {
return parameter.getName();
}
public String getUniqueName() {
return type.getUniqueName();
}
public String displaySchema(MarkupDocBuilder docBuilder) {
return type.displaySchema(docBuilder);
}
public String displayDefaultValue(MarkupDocBuilder docBuilder) {
return getDefaultValue().map(value -> literalText(docBuilder, Json.pretty(value))).orElse("");
}
public String displayDescription(MarkupDocBuilder markupDocBuilder) {
return markupDescription(config.getSwaggerMarkupLanguage(), markupDocBuilder, getDescription());
}
public String displayType(MarkupDocBuilder markupDocBuilder) {
return boldText(markupDocBuilder, getIn());
}
public String getDescription() {
return parameter.getDescription();
}
public boolean getRequired() {
return parameter.getRequired();
}
public String getPattern() {
return parameter.getPattern();
}
public Map<String, Object> getVendorExtensions() {
return parameter.getVendorExtensions();
}
public String getIn() {
return WordUtils.capitalize(parameter.getIn());
}
public Type getType() {
return type;
}
public List<ObjectType> getInlineDefinitions() {
return inlineDefinitions;
}
/**
* Retrieves the type of a parameter, or otherwise null
*
* @param definitionDocumentResolver the definition document resolver
* @return the type of the parameter, or otherwise null
*/
private Type getType(Map<String, Model> definitions, DocumentResolver 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", bodyParameter.getName());
}
} else if (parameter instanceof AbstractSerializableParameter) {
AbstractSerializableParameter serializableParameter = (AbstractSerializableParameter) parameter;
@SuppressWarnings("unchecked")
List<String> enums = serializableParameter.getEnum();
if (CollectionUtils.isNotEmpty(enums)) {
type = new EnumType(serializableParameter.getName(), enums);
} else {
type = new BasicType(serializableParameter.getType(), serializableParameter.getName(), serializableParameter.getFormat());
}
if (serializableParameter.getType().equals("array")) {
String collectionFormat = serializableParameter.getCollectionFormat();
type = new ArrayType(serializableParameter.getName(), new PropertyAdapter(serializableParameter.getItems()).getType(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
*
* @return the default value of the parameter
*/
public Optional<Object> getDefaultValue() {
Validate.notNull(parameter, "parameter must not be null!");
if (parameter instanceof AbstractSerializableParameter) {
AbstractSerializableParameter serializableParameter = (AbstractSerializableParameter) parameter;
return Optional.ofNullable(serializableParameter.getDefaultValue());
}
return Optional.empty();
}
}

View File

@@ -0,0 +1,351 @@
/*
* Copyright 2017 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.adapter;
import io.github.swagger2markup.internal.resolver.DocumentResolver;
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.BooleanUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.util.*;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public final class PropertyAdapter {
private final Property property;
private static Logger logger = LoggerFactory.getLogger(PropertyAdapter.class);
public PropertyAdapter(Property property) {
Validate.notNull(property, "property must not be null");
this.property = property;
}
/**
* 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) {
if (logger.isDebugEnabled()) logger.debug("generateExample RefProperty for " + property.getName());
return markupDocBuilder.copy(false).crossReference(((RefProperty) property).getSimpleRef()).toString();
} else {
if (logger.isDebugEnabled()) logger.debug("generateExample for ref not RefProperty");
}
case "array":
if (property instanceof ArrayProperty) {
return generateArrayExample((ArrayProperty) property, markupDocBuilder);
}
default:
return property.getType();
}
}
/**
* Generate example for an ArrayProperty
*
* @param property ArrayProperty to generate example for
* @param markupDocBuilder MarkupDocBuilder containing all associated settings
* @return String example
*/
private static Object generateArrayExample(ArrayProperty property, MarkupDocBuilder markupDocBuilder) {
Property itemProperty = property.getItems();
List<Object> exampleArray = new ArrayList<>();
exampleArray.add(generateExample(itemProperty, markupDocBuilder));
return exampleArray;
}
/**
* 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);
}
}
/**
* Retrieves the type and format of a property.
*
* @param definitionDocumentResolver the definition document resolver
* @return the type of the property
*/
public Type getType(DocumentResolver definitionDocumentResolver) {
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(), new PropertyAdapter(items).getType(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(), new PropertyAdapter(additionalProperties).getType(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 if (isNotBlank(stringProperty.getFormat())) {
type = new BasicType(stringProperty.getType(), stringProperty.getTitle(), stringProperty.getFormat());
} 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
*
* @return the default value of the property
*/
public Optional<Object> getDefaultValue() {
if (property instanceof BooleanProperty) {
BooleanProperty booleanProperty = (BooleanProperty) property;
return Optional.ofNullable(booleanProperty.getDefault());
} else if (property instanceof StringProperty) {
StringProperty stringProperty = (StringProperty) property;
return Optional.ofNullable(stringProperty.getDefault());
} else if (property instanceof DoubleProperty) {
DoubleProperty doubleProperty = (DoubleProperty) property;
return Optional.ofNullable(doubleProperty.getDefault());
} else if (property instanceof FloatProperty) {
FloatProperty floatProperty = (FloatProperty) property;
return Optional.ofNullable(floatProperty.getDefault());
} else if (property instanceof IntegerProperty) {
IntegerProperty integerProperty = (IntegerProperty) property;
return Optional.ofNullable(integerProperty.getDefault());
} else if (property instanceof LongProperty) {
LongProperty longProperty = (LongProperty) property;
return Optional.ofNullable(longProperty.getDefault());
} else if (property instanceof UUIDProperty) {
UUIDProperty uuidProperty = (UUIDProperty) property;
return Optional.ofNullable(uuidProperty.getDefault());
}
return Optional.empty();
}
/**
* Retrieves the minLength of a property
*
* @return the minLength of the property
*/
public Optional<Integer> getMinlength() {
if (property instanceof StringProperty) {
StringProperty stringProperty = (StringProperty) property;
return Optional.ofNullable(stringProperty.getMinLength());
} else if (property instanceof UUIDProperty) {
UUIDProperty uuidProperty = (UUIDProperty) property;
return Optional.ofNullable(uuidProperty.getMinLength());
}
return Optional.empty();
}
/**
* Retrieves the maxLength of a property
*
* @return the maxLength of the property
*/
public Optional<Integer> getMaxlength() {
if (property instanceof StringProperty) {
StringProperty stringProperty = (StringProperty) property;
return Optional.ofNullable(stringProperty.getMaxLength());
} else if (property instanceof UUIDProperty) {
UUIDProperty uuidProperty = (UUIDProperty) property;
return Optional.ofNullable(uuidProperty.getMaxLength());
}
return Optional.empty();
}
/**
* Retrieves the pattern of a property
*
* @return the pattern of the property
*/
public Optional<String> getPattern() {
if (property instanceof StringProperty) {
StringProperty stringProperty = (StringProperty) property;
return Optional.ofNullable(stringProperty.getPattern());
} else if (property instanceof UUIDProperty) {
UUIDProperty uuidProperty = (UUIDProperty) property;
return Optional.ofNullable(uuidProperty.getPattern());
}
return Optional.empty();
}
/**
* Retrieves the minimum value of a property
*
* @return the minimum value of the property
*/
public Optional<BigDecimal> getMin() {
if (property instanceof BaseIntegerProperty) {
BaseIntegerProperty integerProperty = (BaseIntegerProperty) property;
return Optional.ofNullable(integerProperty.getMinimum() != null ? integerProperty.getMinimum() : null);
} else if (property instanceof AbstractNumericProperty) {
AbstractNumericProperty numericProperty = (AbstractNumericProperty) property;
return Optional.ofNullable(numericProperty.getMinimum());
}
return Optional.empty();
}
/**
* Retrieves the exclusiveMinimum value of a property
*
* @return the exclusiveMinimum value of the property
*/
public boolean getExclusiveMin() {
if (property instanceof AbstractNumericProperty) {
AbstractNumericProperty numericProperty = (AbstractNumericProperty) property;
return BooleanUtils.isTrue(numericProperty.getExclusiveMinimum());
}
return false;
}
/**
* Retrieves the minimum value of a property
*
* @return the minimum value of the property
*/
public Optional<BigDecimal> getMax() {
if (property instanceof BaseIntegerProperty) {
BaseIntegerProperty integerProperty = (BaseIntegerProperty) property;
return Optional.ofNullable(integerProperty.getMaximum() != null ? integerProperty.getMaximum() : null);
} else if (property instanceof AbstractNumericProperty) {
AbstractNumericProperty numericProperty = (AbstractNumericProperty) property;
return Optional.ofNullable(numericProperty.getMaximum());
}
return Optional.empty();
}
/**
* Retrieves the exclusiveMaximum value of a property
*
* @return the exclusiveMaximum value of the property
*/
public boolean getExclusiveMax() {
if (property instanceof AbstractNumericProperty) {
AbstractNumericProperty numericProperty = (AbstractNumericProperty) property;
return BooleanUtils.isTrue((numericProperty.getExclusiveMaximum()));
}
return false;
}
/**
* Return example display string for the given {@code property}.
*
* @param generateMissingExamples specifies if missing examples should be generated
* @param markupDocBuilder doc builder
* @return property example display string
*/
public Optional<Object> getExample(boolean generateMissingExamples, MarkupDocBuilder markupDocBuilder) {
if (property.getExample() != null) {
return Optional.ofNullable(property.getExample());
} else if (property instanceof MapProperty) {
Property additionalProperty = ((MapProperty) property).getAdditionalProperties();
if (additionalProperty.getExample() != null) {
return Optional.ofNullable(additionalProperty.getExample());
} else if (generateMissingExamples) {
Map<String, Object> exampleMap = new HashMap<>();
exampleMap.put("string", generateExample(additionalProperty, markupDocBuilder));
return Optional.of(exampleMap);
}
} else if (property instanceof ArrayProperty) {
if (generateMissingExamples) {
Property itemProperty = ((ArrayProperty) property).getItems();
List<Object> exampleArray = new ArrayList<>();
exampleArray.add(generateExample(itemProperty, markupDocBuilder));
return Optional.of(exampleArray);
}
} else if (generateMissingExamples) {
return Optional.of(generateExample(property, markupDocBuilder));
}
return Optional.empty();
}
/**
* Checks if a property is read-only.
*
* @return true if the property is read-only
*/
public boolean getReadOnly() {
return BooleanUtils.isTrue(property.getReadOnly());
}
}

View File

@@ -0,0 +1,127 @@
/*
* Copyright 2017 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.component;
import io.github.swagger2markup.GroupBy;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.internal.adapter.ParameterAdapter;
import io.github.swagger2markup.internal.resolver.DocumentResolver;
import io.github.swagger2markup.internal.type.ObjectType;
import io.github.swagger2markup.internal.type.Type;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.model.PathOperation;
import io.github.swagger2markup.spi.MarkupComponent;
import io.swagger.models.parameters.Parameter;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import java.util.ArrayList;
import java.util.List;
import static io.github.swagger2markup.Labels.*;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.copyMarkupDocBuilder;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.markupDescription;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public class BodyParameterComponent extends MarkupComponent<BodyParameterComponent.Parameters> {
private final DocumentResolver definitionDocumentResolver;
private final PropertiesTableComponent propertiesTableComponent;
public BodyParameterComponent(Swagger2MarkupConverter.Context context,
DocumentResolver definitionDocumentResolver) {
super(context);
this.definitionDocumentResolver = Validate.notNull(definitionDocumentResolver, "DocumentResolver must not be null");
this.propertiesTableComponent = new PropertiesTableComponent(context, definitionDocumentResolver);
}
public static BodyParameterComponent.Parameters parameters(PathOperation operation,
List<ObjectType> inlineDefinitions) {
return new BodyParameterComponent.Parameters(operation, inlineDefinitions);
}
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
PathOperation operation = params.operation;
List<ObjectType> inlineDefinitions = params.inlineDefinitions;
if (config.isFlatBodyEnabled()) {
List<Parameter> parameters = operation.getOperation().getParameters();
if (CollectionUtils.isNotEmpty(parameters)) {
for (Parameter parameter : parameters) {
if (StringUtils.equals(parameter.getIn(), "body")) {
ParameterAdapter parameterAdapter = new ParameterAdapter(context,
operation, parameter, definitionDocumentResolver);
Type type = parameterAdapter.getType();
inlineDefinitions.addAll(parameterAdapter.getInlineDefinitions());
buildSectionTitle(markupDocBuilder, labels.getLabel(BODY_PARAMETER));
String description = parameter.getDescription();
if (isNotBlank(description)) {
markupDocBuilder.paragraph(markupDescription(config.getSwaggerMarkupLanguage(), markupDocBuilder, description));
}
MarkupDocBuilder typeInfos = copyMarkupDocBuilder(markupDocBuilder);
typeInfos.italicText(labels.getLabel(NAME_COLUMN)).textLine(COLON + parameter.getName());
typeInfos.italicText(labels.getLabel(FLAGS_COLUMN)).textLine(COLON + (BooleanUtils.isTrue(parameter.getRequired()) ? labels.getLabel(FLAGS_REQUIRED).toLowerCase() : labels.getLabel(FLAGS_OPTIONAL).toLowerCase()));
if (!(type instanceof ObjectType)) {
typeInfos.italicText(labels.getLabel(TYPE_COLUMN)).textLine(COLON + type.displaySchema(markupDocBuilder));
}
markupDocBuilder.paragraph(typeInfos.toString(), true);
if (type instanceof ObjectType) {
List<ObjectType> localDefinitions = new ArrayList<>();
propertiesTableComponent.apply(markupDocBuilder, PropertiesTableComponent.parameters(
((ObjectType) type).getProperties(),
operation.getId(),
localDefinitions
));
inlineDefinitions.addAll(localDefinitions);
}
}
}
}
}
return markupDocBuilder;
}
private void buildSectionTitle(MarkupDocBuilder markupDocBuilder, String title) {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
markupDocBuilder.sectionTitleLevel3(title);
} else {
markupDocBuilder.sectionTitleLevel4(title);
}
}
public static class Parameters {
private final List<ObjectType> inlineDefinitions;
private PathOperation operation;
public Parameters(PathOperation operation,
List<ObjectType> inlineDefinitions) {
Validate.notNull(operation, "Operation must not be null");
this.operation = operation;
this.inlineDefinitions = inlineDefinitions;
}
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright 2017 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.component;
import io.github.swagger2markup.Labels;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.spi.MarkupComponent;
import org.apache.commons.lang3.Validate;
import java.util.List;
import java.util.stream.Collectors;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.literalText;
public class ConsumesComponent extends MarkupComponent<ConsumesComponent.Parameters> {
public ConsumesComponent(Swagger2MarkupConverter.Context context) {
super(context);
}
public static ConsumesComponent.Parameters parameters(List<String> consumes,
int titleLevel) {
return new ConsumesComponent.Parameters(consumes, titleLevel);
}
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
markupDocBuilder.sectionTitleLevel(params.titleLevel, labels.getLabel(Labels.CONSUMES));
markupDocBuilder.unorderedList(params.consumes.stream()
.map(value -> literalText(markupDocBuilder, value)).collect(Collectors.toList()));
return markupDocBuilder;
}
public static class Parameters {
private final List<String> consumes;
private final int titleLevel;
public Parameters(List<String> consumes,
int titleLevel) {
this.consumes = Validate.notNull(consumes, "Consumes must not be null");
this.titleLevel = titleLevel;
}
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2017 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.component;
import io.github.swagger2markup.Labels;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.spi.MarkupComponent;
import io.swagger.models.Contact;
import org.apache.commons.lang3.Validate;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.copyMarkupDocBuilder;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public class ContactInfoComponent extends MarkupComponent<ContactInfoComponent.Parameters> {
public ContactInfoComponent(Swagger2MarkupConverter.Context context) {
super(context);
}
public static ContactInfoComponent.Parameters parameters(Contact contact,
int titleLevel) {
return new ContactInfoComponent.Parameters(contact, titleLevel);
}
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
Contact contact = params.contact;
if (isNotBlank(contact.getName()) || isNotBlank(contact.getEmail())) {
markupDocBuilder.sectionTitleLevel(params.titleLevel, labels.getLabel(Labels.CONTACT_INFORMATION));
MarkupDocBuilder paragraphBuilder = copyMarkupDocBuilder(markupDocBuilder);
if (isNotBlank(contact.getName())) {
paragraphBuilder.italicText(labels.getLabel(Labels.CONTACT_NAME))
.textLine(COLON + contact.getName());
}
if (isNotBlank(contact.getEmail())) {
paragraphBuilder.italicText(labels.getLabel(Labels.CONTACT_EMAIL))
.textLine(COLON + contact.getEmail());
}
markupDocBuilder.paragraph(paragraphBuilder.toString(), true);
}
return markupDocBuilder;
}
public static class Parameters {
private final Contact contact;
private final int titleLevel;
public Parameters(Contact contact,
int titleLevel) {
this.contact = Validate.notNull(contact, "Contact must not be null");
this.titleLevel = titleLevel;
}
}
}

View File

@@ -0,0 +1,199 @@
/*
* Copyright 2017 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.component;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.internal.resolver.DocumentResolver;
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.github.swagger2markup.spi.MarkupComponent;
import io.swagger.models.Model;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.Validate;
import java.util.*;
import static io.github.swagger2markup.Labels.*;
import static io.github.swagger2markup.internal.utils.InlineSchemaUtils.createInlineType;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.copyMarkupDocBuilder;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.markupDescription;
import static io.github.swagger2markup.spi.DefinitionsDocumentExtension.Position;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public class DefinitionComponent extends MarkupComponent<DefinitionComponent.Parameters> {
/* Discriminator is only displayed for inheriting definitions */
private static final boolean ALWAYS_DISPLAY_DISCRIMINATOR = false;
private final Map<String, Model> definitions;
private final Map<ObjectTypePolymorphism.Nature, String> POLYMORPHISM_NATURE;
private final DocumentResolver definitionsDocumentResolver;
private PropertiesTableComponent propertiesTableComponent;
public DefinitionComponent(Swagger2MarkupConverter.Context context,
DocumentResolver definitionsDocumentResolver) {
super(context);
this.definitions = context.getSwagger().getDefinitions();
this.definitionsDocumentResolver = definitionsDocumentResolver;
POLYMORPHISM_NATURE = new HashMap<ObjectTypePolymorphism.Nature, String>() {{
put(ObjectTypePolymorphism.Nature.COMPOSITION, labels.getLabel(POLYMORPHISM_NATURE_COMPOSITION));
put(ObjectTypePolymorphism.Nature.INHERITANCE, labels.getLabel(POLYMORPHISM_NATURE_INHERITANCE));
}};
propertiesTableComponent = new PropertiesTableComponent(context, definitionsDocumentResolver);
}
public static DefinitionComponent.Parameters parameters(String definitionName,
Model model,
int titleLevel) {
return new DefinitionComponent.Parameters(definitionName, model, titleLevel);
}
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
String definitionName = params.definitionName;
Model model = params.model;
applyDefinitionsDocumentExtension(new DefinitionsDocumentExtension.Context(Position.DEFINITION_BEFORE, markupDocBuilder, definitionName, model));
markupDocBuilder.sectionTitleWithAnchorLevel(params.titleLevel, definitionName, definitionName);
applyDefinitionsDocumentExtension(new DefinitionsDocumentExtension.Context(Position.DEFINITION_BEGIN, markupDocBuilder, definitionName, model));
String description = model.getDescription();
if (isNotBlank(description)) {
markupDocBuilder.paragraph(markupDescription(config.getSwaggerMarkupLanguage(), markupDocBuilder, description));
}
inlineDefinitions(markupDocBuilder, typeSection(markupDocBuilder, definitionName, model), definitionName);
applyDefinitionsDocumentExtension(new DefinitionsDocumentExtension.Context(Position.DEFINITION_END, markupDocBuilder, definitionName, model));
applyDefinitionsDocumentExtension(new DefinitionsDocumentExtension.Context(Position.DEFINITION_AFTER, markupDocBuilder, definitionName, model));
return markupDocBuilder;
}
/**
* 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 markupDocBuilder the docbuilder do use for output
* @param definitions all inline definitions to display
* @param uniquePrefix unique prefix to prepend to inline object names to enforce unicity
*/
private void inlineDefinitions(MarkupDocBuilder markupDocBuilder, List<ObjectType> definitions, String uniquePrefix) {
if (CollectionUtils.isNotEmpty(definitions)) {
for (ObjectType definition : definitions) {
addInlineDefinitionTitle(definition.getName(), definition.getUniqueName(), markupDocBuilder);
List<ObjectType> localDefinitions = new ArrayList<>();
propertiesTableComponent.apply(markupDocBuilder, new PropertiesTableComponent.Parameters(definition.getProperties(), uniquePrefix, localDefinitions));
for (ObjectType localDefinition : localDefinitions)
inlineDefinitions(markupDocBuilder, Collections.singletonList(localDefinition), localDefinition.getUniqueName());
}
}
}
/**
* Builds the type informations of a definition
*
* @param markupDocBuilder the docbuilder do use for output
* @param definitionName name of the definition to display
* @param model model of the definition to display
* @return a list of inlined types.
*/
private List<ObjectType> typeSection(MarkupDocBuilder markupDocBuilder, String definitionName, Model model) {
List<ObjectType> inlineDefinitions = new ArrayList<>();
Type modelType = ModelUtils.resolveRefType(ModelUtils.getType(model, definitions, definitionsDocumentResolver));
if (!(modelType instanceof ObjectType) && config.isInlineSchemaEnabled()) {
modelType = createInlineType(modelType, definitionName, definitionName + " " + "inline", inlineDefinitions);
}
if (modelType instanceof ObjectType) {
ObjectType objectType = (ObjectType) modelType;
MarkupDocBuilder typeInfos = copyMarkupDocBuilder(markupDocBuilder);
switch (objectType.getPolymorphism().getNature()) {
case COMPOSITION:
typeInfos.italicText(labels.getLabel(POLYMORPHISM_COLUMN)).textLine(COLON + POLYMORPHISM_NATURE.get(objectType.getPolymorphism().getNature()));
break;
case INHERITANCE:
typeInfos.italicText(labels.getLabel(POLYMORPHISM_COLUMN)).textLine(COLON + POLYMORPHISM_NATURE.get(objectType.getPolymorphism().getNature()));
typeInfos.italicText(labels.getLabel(POLYMORPHISM_DISCRIMINATOR_COLUMN)).textLine(COLON + objectType.getPolymorphism().getDiscriminator());
break;
case NONE:
if (ALWAYS_DISPLAY_DISCRIMINATOR && isNotBlank(objectType.getPolymorphism().getDiscriminator()))
typeInfos.italicText(labels.getLabel(POLYMORPHISM_DISCRIMINATOR_COLUMN)).textLine(COLON + objectType.getPolymorphism().getDiscriminator());
break;
default:
break;
}
String typeInfosString = typeInfos.toString();
if (isNotBlank(typeInfosString))
markupDocBuilder.paragraph(typeInfosString, true);
propertiesTableComponent.apply(markupDocBuilder,
PropertiesTableComponent.parameters(
((ObjectType) modelType).getProperties(),
definitionName,
inlineDefinitions));
} else if (modelType != null) {
MarkupDocBuilder typeInfos = copyMarkupDocBuilder(markupDocBuilder);
typeInfos.italicText(labels.getLabel(TYPE_COLUMN)).textLine(COLON + modelType.displaySchema(markupDocBuilder));
markupDocBuilder.paragraph(typeInfos.toString());
}
return inlineDefinitions;
}
/**
* Apply extension context to all DefinitionsContentExtension
*
* @param context context
*/
private void applyDefinitionsDocumentExtension(DefinitionsDocumentExtension.Context context) {
extensionRegistry.getDefinitionsDocumentExtensions().forEach(extension -> extension.apply(context));
}
public static class Parameters {
private final String definitionName;
private final Model model;
private final int titleLevel;
public Parameters(String definitionName,
Model model,
int titleLevel) {
this.definitionName = Validate.notBlank(definitionName, "DefinitionName must not be empty");
this.model = Validate.notNull(model, "Model must not be null");
this.titleLevel = titleLevel;
}
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright 2017 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.component;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.spi.MarkupComponent;
import io.swagger.models.Info;
import io.swagger.models.License;
import org.apache.commons.lang3.Validate;
import static io.github.swagger2markup.Labels.*;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.copyMarkupDocBuilder;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public class LicenseInfoComponent extends MarkupComponent<LicenseInfoComponent.Parameters> {
public LicenseInfoComponent(Swagger2MarkupConverter.Context context) {
super(context);
}
public static LicenseInfoComponent.Parameters parameters(Info info,
int titleLevel) {
return new LicenseInfoComponent.Parameters(info, titleLevel);
}
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
Info info = params.info;
License license = info.getLicense();
String termOfService = info.getTermsOfService();
if ((license != null && (isNotBlank(license.getName()) || isNotBlank(license.getUrl()))) || isNotBlank(termOfService)) {
markupDocBuilder.sectionTitleLevel(params.titleLevel, labels.getLabel(LICENSE_INFORMATION));
MarkupDocBuilder paragraph = copyMarkupDocBuilder(markupDocBuilder);
if (license != null) {
if (isNotBlank(license.getName())) {
paragraph.italicText(labels.getLabel(LICENSE)).textLine(COLON + license.getName());
}
if (isNotBlank(license.getUrl())) {
paragraph.italicText(labels.getLabel(LICENSE_URL)).textLine(COLON + license.getUrl());
}
}
paragraph.italicText(labels.getLabel(TERMS_OF_SERVICE)).textLine(COLON + termOfService);
markupDocBuilder.paragraph(paragraph.toString(), true);
}
return markupDocBuilder;
}
public static class Parameters {
private final int titleLevel;
private final Info info;
public Parameters(Info info,
int titleLevel) {
this.info = Validate.notNull(info, "Info must not be null");
this.titleLevel = titleLevel;
}
}
}

View File

@@ -0,0 +1,166 @@
/*
* Copyright 2017 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.component;
import ch.netzwerg.paleo.StringColumn;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.internal.adapter.ParameterAdapter;
import io.github.swagger2markup.internal.resolver.DocumentResolver;
import io.github.swagger2markup.internal.type.ObjectType;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.model.PathOperation;
import io.github.swagger2markup.spi.MarkupComponent;
import io.github.swagger2markup.spi.PathsDocumentExtension;
import io.swagger.models.parameters.Parameter;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import java.util.List;
import java.util.stream.Collectors;
import static ch.netzwerg.paleo.ColumnIds.StringColumnId;
import static io.github.swagger2markup.Labels.*;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.copyMarkupDocBuilder;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public class ParameterTableComponent extends MarkupComponent<ParameterTableComponent.Parameters> {
private final DocumentResolver definitionDocumentResolver;
private final TableComponent tableComponent;
ParameterTableComponent(Swagger2MarkupConverter.Context context,
DocumentResolver definitionDocumentResolver) {
super(context);
this.definitionDocumentResolver = Validate.notNull(definitionDocumentResolver, "DocumentResolver must not be null");
this.tableComponent = new TableComponent(context);
}
public static ParameterTableComponent.Parameters parameters(PathOperation operation,
List<ObjectType> inlineDefinitions,
int titleLevel) {
return new ParameterTableComponent.Parameters(operation, inlineDefinitions, titleLevel);
}
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
PathOperation operation = params.operation;
List<ObjectType> inlineDefinitions = params.inlineDefinitions;
List<Parameter> parameters = operation.getOperation().getParameters();
if (config.getParameterOrdering() != null)
parameters.sort(config.getParameterOrdering());
// Filter parameters to display in parameters section
List<Parameter> filteredParameters = parameters.stream()
.filter(this::filterParameter).collect(Collectors.toList());
MarkupDocBuilder parametersBuilder = copyMarkupDocBuilder(markupDocBuilder);
applyPathsDocumentExtension(new PathsDocumentExtension.Context(PathsDocumentExtension.Position.OPERATION_PARAMETERS_BEGIN, parametersBuilder, operation));
if (CollectionUtils.isNotEmpty(filteredParameters)) {
StringColumn.Builder typeColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(TYPE_COLUMN)))
.putMetaData(TableComponent.WIDTH_RATIO, "2");
StringColumn.Builder nameColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(NAME_COLUMN)))
.putMetaData(TableComponent.WIDTH_RATIO, "3");
StringColumn.Builder descriptionColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(DESCRIPTION_COLUMN)))
.putMetaData(TableComponent.WIDTH_RATIO, "9")
.putMetaData(TableComponent.HEADER_COLUMN, "true");
StringColumn.Builder schemaColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(SCHEMA_COLUMN)))
.putMetaData(TableComponent.WIDTH_RATIO, "4")
.putMetaData(TableComponent.HEADER_COLUMN, "true");
StringColumn.Builder defaultColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(DEFAULT_COLUMN)))
.putMetaData(TableComponent.WIDTH_RATIO, "2")
.putMetaData(TableComponent.HEADER_COLUMN, "true");
for (Parameter parameter : filteredParameters) {
ParameterAdapter parameterAdapter = new ParameterAdapter(context,
operation, parameter, definitionDocumentResolver);
inlineDefinitions.addAll(parameterAdapter.getInlineDefinitions());
typeColumnBuilder.add(parameterAdapter.displayType(markupDocBuilder));
nameColumnBuilder.add(getParameterNameColumnContent(markupDocBuilder, parameterAdapter));
descriptionColumnBuilder.add(parameterAdapter.displayDescription(markupDocBuilder));
schemaColumnBuilder.add(parameterAdapter.displaySchema(markupDocBuilder));
defaultColumnBuilder.add(parameterAdapter.displayDefaultValue(markupDocBuilder));
}
parametersBuilder = tableComponent.apply(parametersBuilder, TableComponent.parameters(
typeColumnBuilder.build(),
nameColumnBuilder.build(),
descriptionColumnBuilder.build(),
schemaColumnBuilder.build(),
defaultColumnBuilder.build()));
}
applyPathsDocumentExtension(new PathsDocumentExtension.Context(PathsDocumentExtension.Position.OPERATION_PARAMETERS_END, parametersBuilder, operation));
String parametersContent = parametersBuilder.toString();
applyPathsDocumentExtension(new PathsDocumentExtension.Context(PathsDocumentExtension.Position.OPERATION_PARAMETERS_BEFORE, markupDocBuilder, operation));
if (isNotBlank(parametersContent)) {
markupDocBuilder.sectionTitleLevel(params.titleLevel, labels.getLabel(PARAMETERS));
markupDocBuilder.text(parametersContent);
}
applyPathsDocumentExtension(new PathsDocumentExtension.Context(PathsDocumentExtension.Position.OPERATION_PARAMETERS_AFTER, markupDocBuilder, operation));
return markupDocBuilder;
}
private String getParameterNameColumnContent(MarkupDocBuilder markupDocBuilder, ParameterAdapter parameter) {
MarkupDocBuilder parameterNameContent = copyMarkupDocBuilder(markupDocBuilder);
parameterNameContent.boldTextLine(parameter.getName(), true);
if (parameter.getRequired())
parameterNameContent.italicText(labels.getLabel(FLAGS_REQUIRED).toLowerCase());
else
parameterNameContent.italicText(labels.getLabel(FLAGS_OPTIONAL).toLowerCase());
return parameterNameContent.toString();
}
/**
* 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"));
}
/**
* Apply extension context to all OperationsContentExtension.
*
* @param context context
*/
private void applyPathsDocumentExtension(PathsDocumentExtension.Context context) {
extensionRegistry.getPathsDocumentExtensions().forEach(extension -> extension.apply(context));
}
public static class Parameters {
private final PathOperation operation;
private final int titleLevel;
private final List<ObjectType> inlineDefinitions;
public Parameters(PathOperation operation,
List<ObjectType> inlineDefinitions,
int titleLevel) {
this.operation = Validate.notNull(operation, "PathOperation must not be null");
this.inlineDefinitions = Validate.notNull(inlineDefinitions, "InlineDefinitions must not be null");
this.titleLevel = titleLevel;
}
}
}

View File

@@ -0,0 +1,477 @@
/*
* Copyright 2017 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.component;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.swagger2markup.GroupBy;
import io.github.swagger2markup.PageBreakLocations;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.internal.resolver.DocumentResolver;
import io.github.swagger2markup.internal.type.ObjectType;
import io.github.swagger2markup.internal.utils.ExamplesUtil;
import io.github.swagger2markup.markup.builder.MarkupAdmonition;
import io.github.swagger2markup.markup.builder.MarkupBlockStyle;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.model.PathOperation;
import io.github.swagger2markup.spi.MarkupComponent;
import io.github.swagger2markup.spi.PathsDocumentExtension;
import io.swagger.models.Model;
import io.swagger.util.Json;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.math.NumberUtils;
import java.util.*;
import static io.github.swagger2markup.Labels.*;
import static io.github.swagger2markup.PageBreakLocations.*;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.copyMarkupDocBuilder;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.markupDescription;
import static io.github.swagger2markup.spi.PathsDocumentExtension.Position;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public class PathOperationComponent extends MarkupComponent<PathOperationComponent.Parameters> {
private final DocumentResolver definitionDocumentResolver;
private final Map<String, Model> definitions;
private final PropertiesTableComponent propertiesTableComponent;
private final ParameterTableComponent parameterTableComponent;
private final ConsumesComponent consumesComponent;
private final ProducesComponent producesComponent;
private final SecuritySchemeComponent securitySchemeComponent;
private final BodyParameterComponent bodyParameterComponent;
private final ResponseComponent responseComponent;
public PathOperationComponent(Swagger2MarkupConverter.Context context,
DocumentResolver definitionDocumentResolver,
DocumentResolver securityDocumentResolver) {
super(context);
this.definitions = context.getSwagger().getDefinitions();
this.definitionDocumentResolver = Validate.notNull(definitionDocumentResolver, "DocumentResolver must not be null");
this.propertiesTableComponent = new PropertiesTableComponent(context, definitionDocumentResolver);
this.parameterTableComponent = new ParameterTableComponent(context, definitionDocumentResolver);
this.consumesComponent = new ConsumesComponent(context);
this.producesComponent = new ProducesComponent(context);
this.securitySchemeComponent = new SecuritySchemeComponent(context, securityDocumentResolver);
this.bodyParameterComponent = new BodyParameterComponent(context, definitionDocumentResolver);
this.responseComponent = new ResponseComponent(context, definitionDocumentResolver);
}
public static PathOperationComponent.Parameters parameters(PathOperation operation) {
return new PathOperationComponent.Parameters(operation);
}
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
PathOperation operation = params.operation;
List<PageBreakLocations> locations = config.getPageBreakLocations();
applyPathsDocumentExtension(new PathsDocumentExtension.Context(Position.OPERATION_BEFORE, markupDocBuilder, operation));
if (locations.contains(BEFORE_OPERATION)) markupDocBuilder.pageBreak();
buildOperationTitle(markupDocBuilder, operation);
applyPathsDocumentExtension(new PathsDocumentExtension.Context(Position.OPERATION_BEGIN, markupDocBuilder, operation));
buildDeprecatedSection(markupDocBuilder, operation);
if (locations.contains(BEFORE_OPERATION_DESCRIPTION)) markupDocBuilder.pageBreak();
buildDescriptionSection(markupDocBuilder, operation);
if (locations.contains(AFTER_OPERATION_DESCRIPTION)) markupDocBuilder.pageBreak();
if (locations.contains(BEFORE_OPERATION_PARAMETERS)) markupDocBuilder.pageBreak();
inlineDefinitions(markupDocBuilder, buildParametersSection(markupDocBuilder, operation), operation.getPath() + " " + operation.getMethod());
if (locations.contains(AFTER_OPERATION_PARAMETERS)) markupDocBuilder.pageBreak();
inlineDefinitions(markupDocBuilder, buildBodyParameterSection(markupDocBuilder, operation), operation.getPath() + " " + operation.getMethod());
if (locations.contains(BEFORE_OPERATION_RESPONSES)) markupDocBuilder.pageBreak();
inlineDefinitions(markupDocBuilder, buildResponsesSection(markupDocBuilder, operation), operation.getPath() + " " + operation.getMethod());
if (locations.contains(AFTER_OPERATION_RESPONSES)) markupDocBuilder.pageBreak();
if (locations.contains(BEFORE_OPERATION_CONSUMES)) markupDocBuilder.pageBreak();
buildConsumesSection(markupDocBuilder, operation);
if (locations.contains(AFTER_OPERATION_CONSUMES)) markupDocBuilder.pageBreak();
if (locations.contains(BEFORE_OPERATION_PRODUCES)) markupDocBuilder.pageBreak();
buildProducesSection(markupDocBuilder, operation);
if (locations.contains(AFTER_OPERATION_PRODUCES)) markupDocBuilder.pageBreak();
buildTagsSection(markupDocBuilder, operation);
buildSecuritySchemeSection(markupDocBuilder, operation);
buildExamplesSection(markupDocBuilder, operation, locations);
applyPathsDocumentExtension(new PathsDocumentExtension.Context(Position.OPERATION_END, markupDocBuilder, operation));
applyPathsDocumentExtension(new PathsDocumentExtension.Context(Position.OPERATION_AFTER, markupDocBuilder, operation));
if (locations.contains(AFTER_OPERATION)) markupDocBuilder.pageBreak();
return markupDocBuilder;
}
/**
* 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
*/
private void buildOperationTitle(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
buildOperationTitle(markupDocBuilder, operation.getTitle(), operation.getId());
if (operation.getTitle().equals(operation.getOperation().getSummary())) {
markupDocBuilder.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)
*/
private void buildOperationTitle(MarkupDocBuilder markupDocBuilder, String title, String anchor) {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
markupDocBuilder.sectionTitleWithAnchorLevel2(title, anchor);
} else {
markupDocBuilder.sectionTitleWithAnchorLevel3(title, anchor);
}
}
/**
* Builds a warning if method is deprecated.
*
* @param operation the Swagger Operation
*/
private void buildDeprecatedSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
if (BooleanUtils.isTrue(operation.getOperation().isDeprecated())) {
markupDocBuilder.block(DEPRECATED_OPERATION, MarkupBlockStyle.EXAMPLE, null, MarkupAdmonition.CAUTION);
}
}
/**
* Adds a operation description to the document.
*
* @param operation the Swagger Operation
*/
private void buildDescriptionSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
MarkupDocBuilder descriptionBuilder = copyMarkupDocBuilder(markupDocBuilder);
applyPathsDocumentExtension(new PathsDocumentExtension.Context(Position.OPERATION_DESCRIPTION_BEGIN, descriptionBuilder, operation));
String description = operation.getOperation().getDescription();
if (isNotBlank(description)) {
descriptionBuilder.paragraph(markupDescription(config.getSwaggerMarkupLanguage(), markupDocBuilder, description));
}
applyPathsDocumentExtension(new PathsDocumentExtension.Context(Position.OPERATION_DESCRIPTION_END, descriptionBuilder, operation));
String descriptionContent = descriptionBuilder.toString();
applyPathsDocumentExtension(new PathsDocumentExtension.Context(Position.OPERATION_DESCRIPTION_BEFORE, markupDocBuilder, operation));
if (isNotBlank(descriptionContent)) {
buildSectionTitle(markupDocBuilder, labels.getLabel(DESCRIPTION));
markupDocBuilder.text(descriptionContent);
}
applyPathsDocumentExtension(new PathsDocumentExtension.Context(Position.OPERATION_DESCRIPTION_AFTER, markupDocBuilder, operation));
}
/**
* Builds the parameters section
*
* @param operation the Swagger Operation
*/
private List<ObjectType> buildParametersSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
List<ObjectType> inlineDefinitions = new ArrayList<>();
parameterTableComponent.apply(markupDocBuilder, ParameterTableComponent.parameters(
operation,
inlineDefinitions,
getSectionTitleLevel()
));
return inlineDefinitions;
}
/**
* Builds the body parameter section
*
* @param operation the Swagger Operation
* @return a list of inlined types.
*/
private List<ObjectType> buildBodyParameterSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
List<ObjectType> inlineDefinitions = new ArrayList<>();
bodyParameterComponent.apply(markupDocBuilder, BodyParameterComponent.parameters(
operation,
inlineDefinitions
));
return inlineDefinitions;
}
private List<ObjectType> buildResponsesSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
List<ObjectType> inlineDefinitions = new ArrayList<>();
responseComponent.apply(markupDocBuilder, ResponseComponent.parameters(
operation,
getSectionTitleLevel(),
inlineDefinitions
));
return inlineDefinitions;
}
/**
* Adds a operation section title to the document.
*
* @param title the section title
*/
private void buildSectionTitle(MarkupDocBuilder markupDocBuilder, String title) {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
markupDocBuilder.sectionTitleLevel3(title);
} else {
markupDocBuilder.sectionTitleLevel4(title);
}
}
/**
* 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
*/
private void addInlineDefinitionTitle(MarkupDocBuilder markupDocBuilder, String title, String anchor) {
markupDocBuilder.anchor(anchor);
markupDocBuilder.newLine();
markupDocBuilder.boldTextLine(title);
}
/**
* Builds inline schema definitions
*
* @param markupDocBuilder the docbuilder do use for output
* @param definitions all inline definitions to display
* @param uniquePrefix unique prefix to prepend to inline object names to enforce unicity
*/
private void inlineDefinitions(MarkupDocBuilder markupDocBuilder, List<ObjectType> definitions, String uniquePrefix) {
if (CollectionUtils.isNotEmpty(definitions)) {
for (ObjectType definition : definitions) {
addInlineDefinitionTitle(markupDocBuilder, definition.getName(), definition.getUniqueName());
List<ObjectType> localDefinitions = new ArrayList<>();
propertiesTableComponent.apply(markupDocBuilder, PropertiesTableComponent.parameters(
definition.getProperties(),
uniquePrefix,
localDefinitions
));
for (ObjectType localDefinition : localDefinitions)
inlineDefinitions(markupDocBuilder, Collections.singletonList(localDefinition), localDefinition.getUniqueName());
}
}
}
private void buildConsumesSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
List<String> consumes = operation.getOperation().getConsumes();
if (CollectionUtils.isNotEmpty(consumes)) {
consumesComponent.apply(markupDocBuilder, ConsumesComponent.parameters(consumes,
getSectionTitleLevel()));
}
}
private void buildProducesSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
List<String> produces = operation.getOperation().getProduces();
if (CollectionUtils.isNotEmpty(produces)) {
producesComponent.apply(markupDocBuilder, ProducesComponent.parameters(produces,
getSectionTitleLevel()));
}
}
private void buildTagsSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
List<String> tags = operation.getOperation().getTags();
if (CollectionUtils.isNotEmpty(tags)) {
buildSectionTitle(markupDocBuilder, labels.getLabel(TAGS));
if (config.getTagOrdering() != null) {
tags.sort(config.getTagOrdering());
}
markupDocBuilder.unorderedList(tags);
}
}
}
/**
* Builds the security section of a Swagger Operation.
*
* @param operation the Swagger Operation
*/
private void buildSecuritySchemeSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
if (config.isPathSecuritySectionEnabled()) {
securitySchemeComponent.apply(markupDocBuilder, SecuritySchemeComponent.parameters(
operation,
getSectionTitleLevel()
));
}
}
/**
* Retrieves the title level for sections
*/
private int getSectionTitleLevel() {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
return 3;
} else {
return 4;
}
}
/**
* Builds the example section of a Swagger Operation.
*
* @param operation the Swagger Operation
*/
private void buildExamplesSection(MarkupDocBuilder markupDocBuilder, PathOperation operation, List<PageBreakLocations> locations) {
Map<String, Object> generatedRequestExampleMap = ExamplesUtil.generateRequestExampleMap(config.isGeneratedExamplesEnabled(), operation, definitions, definitionDocumentResolver, markupDocBuilder);
Map<String, Object> generatedResponseExampleMap = ExamplesUtil.generateResponseExampleMap(config.isGeneratedExamplesEnabled(), operation, definitions, definitionDocumentResolver, markupDocBuilder);
boolean beforeExampleRequestBreak = locations.contains(BEFORE_OPERATION_EXAMPLE_REQUEST);
boolean afterExampleRequestBreak = locations.contains(AFTER_OPERATION_EXAMPLE_REQUEST);
boolean beforeExampleResponseBreak = locations.contains(BEFORE_OPERATION_EXAMPLE_RESPONSE);
boolean afterExampleResponseBreak = locations.contains(AFTER_OPERATION_EXAMPLE_RESPONSE);
exampleMap(markupDocBuilder, generatedRequestExampleMap, labels.getLabel(EXAMPLE_REQUEST), labels.getLabel(REQUEST), beforeExampleRequestBreak, afterExampleRequestBreak);
exampleMap(markupDocBuilder, generatedResponseExampleMap, labels.getLabel(EXAMPLE_RESPONSE), labels.getLabel(RESPONSE), beforeExampleResponseBreak, afterExampleResponseBreak);
}
private void exampleMap(MarkupDocBuilder markupDocBuilder, Map<String, Object> exampleMap, String operationSectionTitle, String sectionTitle, boolean beforeBreak, boolean afterBreak) {
if (exampleMap.size() > 0) {
if (beforeBreak) markupDocBuilder.pageBreak();
buildSectionTitle(markupDocBuilder, operationSectionTitle);
for (Map.Entry<String, Object> entry : exampleMap.entrySet()) {
// Example title, like "Response 200" or "Request Body"
buildExampleTitle(markupDocBuilder, sectionTitle + " " + entry.getKey());
if (NumberUtils.isNumber(entry.getKey())) {
// Section header is an HTTP status code (numeric)
JsonNode rootNode = parseExample(entry.getValue());
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
if (!fieldsIterator.hasNext()) {
// rootNode contains a single example, no need to further iterate.
String example = Json.pretty(rootNode);
// String example = Json.pretty(stripExampleQuotes(rootNode.toString()));
// example = Json.pretty(example);
markupDocBuilder.listingBlock(example, "json");
}
while (fieldsIterator.hasNext()) {
Map.Entry<String, JsonNode> field = fieldsIterator.next();
if (field.getKey().equals("application/json")) {
String example = Json.pretty(field.getValue());
example = stripExampleQuotes(StringEscapeUtils.unescapeJson(example));
markupDocBuilder.listingBlock(example, "json");
} else if (field.getKey().equals("application/xml")) {
String example = stripExampleQuotes(field.getValue().toString());
example = StringEscapeUtils.unescapeJava(example);
//TODO: pretty print XML
markupDocBuilder.listingBlock(example, "xml");
} else {
String example = Json.pretty(entry.getValue());
markupDocBuilder.listingBlock(example, "json");
break; // No need to print the same example multiple times
}
}
} else if (entry.getKey().equals("path")) {
// Path shouldn't have quotes around it
markupDocBuilder.listingBlock(entry.getValue().toString());
} else {
markupDocBuilder.listingBlock(Json.pretty(entry.getValue()), "json");
}
}
if (afterBreak) markupDocBuilder.pageBreak();
}
}
/**
* Strip leading and trailing quotes from a string
*
* @param raw String containing leading or trailing quotes
* @return parsed String
*/
private String stripExampleQuotes(String raw) {
return raw
.replaceAll("^\"+", "") // Strip leading quotes
.replaceAll("\"+$", ""); // Strip trailing quotes
}
/**
* Parse a JSON array
*
* @param raw Object containing a JSON string
* @return JsonNode[contentType, example]
* @throws RuntimeException when the given JSON string cannot be parsed
*/
private JsonNode parseExample(Object raw) throws RuntimeException {
try {
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
return mapper.readTree(Json.pretty(raw));
} catch (Exception ex) {
throw new RuntimeException("Failed to read example", ex);
}
}
/**
* Adds a example title to the document.
*
* @param title the section title
*/
private void buildExampleTitle(MarkupDocBuilder markupDocBuilder, String title) {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
markupDocBuilder.sectionTitleLevel4(title);
} else {
markupDocBuilder.sectionTitleLevel5(title);
}
}
/**
* Apply extension context to all OperationsContentExtension.
*
* @param context context
*/
private void applyPathsDocumentExtension(PathsDocumentExtension.Context context) {
extensionRegistry.getPathsDocumentExtensions().forEach(extension -> extension.apply(context));
}
public static class Parameters {
private final PathOperation operation;
public Parameters(PathOperation operation) {
this.operation = Validate.notNull(operation, "PathOperation must not be null");
}
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright 2017 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.component;
import io.github.swagger2markup.Labels;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.spi.MarkupComponent;
import org.apache.commons.lang3.Validate;
import java.util.List;
import java.util.stream.Collectors;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.literalText;
public class ProducesComponent extends MarkupComponent<ProducesComponent.Parameters> {
public ProducesComponent(Swagger2MarkupConverter.Context context) {
super(context);
}
public static ProducesComponent.Parameters parameters(List<String> consumes,
int titleLevel) {
return new ProducesComponent.Parameters(consumes, titleLevel);
}
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
markupDocBuilder.sectionTitleLevel(params.titleLevel, labels.getLabel(Labels.PRODUCES));
markupDocBuilder.unorderedList(params.produces.stream()
.map(value -> literalText(markupDocBuilder, value)).collect(Collectors.toList()));
return markupDocBuilder;
}
public static class Parameters {
private final List<String> produces;
private final int titleLevel;
public Parameters(List<String> produces, int titleLevel) {
this.produces = Validate.notNull(produces, "Produces must not be null");
this.titleLevel = titleLevel;
}
}
}

View File

@@ -0,0 +1,220 @@
/*
* Copyright 2017 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.component;
import ch.netzwerg.paleo.ColumnIds;
import ch.netzwerg.paleo.StringColumn;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.internal.adapter.PropertyAdapter;
import io.github.swagger2markup.internal.resolver.DocumentResolver;
import io.github.swagger2markup.internal.type.ObjectType;
import io.github.swagger2markup.internal.type.Type;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.spi.MarkupComponent;
import io.swagger.models.properties.Property;
import io.swagger.util.Json;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.Validate;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static io.github.swagger2markup.Labels.*;
import static io.github.swagger2markup.internal.utils.InlineSchemaUtils.createInlineType;
import static io.github.swagger2markup.internal.utils.MapUtils.toSortedMap;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.copyMarkupDocBuilder;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.markupDescription;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public class PropertiesTableComponent extends MarkupComponent<PropertiesTableComponent.Parameters> {
private final DocumentResolver definitionDocumentResolver;
private final TableComponent tableComponent;
/**
* Build a generic property table
*
* @param definitionDocumentResolver definition document resolver to apply to property type cross-reference
*/
PropertiesTableComponent(Swagger2MarkupConverter.Context context,
DocumentResolver definitionDocumentResolver) {
super(context);
this.definitionDocumentResolver = definitionDocumentResolver;
this.tableComponent = new TableComponent(context);
}
public static PropertiesTableComponent.Parameters parameters(Map<String, Property> properties,
String parameterName,
List<ObjectType> inlineDefinitions) {
return new PropertiesTableComponent.Parameters(properties, parameterName, inlineDefinitions);
}
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
//TODO: This method is too complex, split it up in smaller methods to increase readability
StringColumn.Builder nameColumnBuilder = StringColumn.builder(ColumnIds.StringColumnId.of(labels.getLabel(NAME_COLUMN)))
.putMetaData(TableComponent.WIDTH_RATIO, "3");
StringColumn.Builder descriptionColumnBuilder = StringColumn.builder(ColumnIds.StringColumnId.of(labels.getLabel(DESCRIPTION_COLUMN)))
.putMetaData(TableComponent.WIDTH_RATIO, "11")
.putMetaData(TableComponent.HEADER_COLUMN, "true");
StringColumn.Builder schemaColumnBuilder = StringColumn.builder(ColumnIds.StringColumnId.of(labels.getLabel(SCHEMA_COLUMN)))
.putMetaData(TableComponent.WIDTH_RATIO, "4")
.putMetaData(TableComponent.HEADER_COLUMN, "true");
Map<String, Property> properties = params.properties;
if (MapUtils.isNotEmpty(properties)) {
Map<String, Property> sortedProperties = toSortedMap(properties, config.getPropertyOrdering());
sortedProperties.forEach((String propertyName, Property property) -> {
PropertyAdapter propertyAdapter = new PropertyAdapter(property);
Type propertyType = propertyAdapter.getType(definitionDocumentResolver);
if (config.isInlineSchemaEnabled()) {
propertyType = createInlineType(propertyType, propertyName, params.parameterName + " " + propertyName, params.inlineDefinitions);
}
Optional<Object> optionalExample = propertyAdapter.getExample(config.isGeneratedExamplesEnabled(), markupDocBuilder);
Optional<Object> optionalDefaultValue = propertyAdapter.getDefaultValue();
Optional<Integer> optionalMaxLength = propertyAdapter.getMaxlength();
Optional<Integer> optionalMinLength = propertyAdapter.getMinlength();
Optional<String> optionalPattern = propertyAdapter.getPattern();
Optional<BigDecimal> optionalMinValue = propertyAdapter.getMin();
boolean exclusiveMin = propertyAdapter.getExclusiveMin();
Optional<BigDecimal> optionalMaxValue = propertyAdapter.getMax();
boolean exclusiveMax = propertyAdapter.getExclusiveMax();
MarkupDocBuilder propertyNameContent = copyMarkupDocBuilder(markupDocBuilder);
propertyNameContent.boldTextLine(propertyName, true);
if (property.getRequired())
propertyNameContent.italicText(labels.getLabel(FLAGS_REQUIRED).toLowerCase());
else
propertyNameContent.italicText(labels.getLabel(FLAGS_OPTIONAL).toLowerCase());
if (propertyAdapter.getReadOnly()) {
propertyNameContent.newLine(true);
propertyNameContent.italicText(labels.getLabel(FLAGS_READ_ONLY).toLowerCase());
}
MarkupDocBuilder descriptionContent = copyMarkupDocBuilder(markupDocBuilder);
String description = markupDescription(config.getSwaggerMarkupLanguage(), markupDocBuilder, property.getDescription());
if (isNotBlank(description))
descriptionContent.text(description);
if (optionalDefaultValue.isPresent()) {
if (isNotBlank(descriptionContent.toString())) {
descriptionContent.newLine(true);
}
descriptionContent.boldText(labels.getLabel(DEFAULT_COLUMN)).text(COLON).literalText(Json.pretty(optionalDefaultValue.get()));
}
if (optionalMinLength.isPresent() && optionalMaxLength.isPresent()) {
// combination of minlength/maxlength
Integer minLength = optionalMinLength.get();
Integer maxLength = optionalMaxLength.get();
if (isNotBlank(descriptionContent.toString())) {
descriptionContent.newLine(true);
}
String lengthRange = minLength + " - " + maxLength;
if (minLength.equals(maxLength)) {
lengthRange = minLength.toString();
}
descriptionContent.boldText(labels.getLabel(LENGTH_COLUMN)).text(COLON).literalText(lengthRange);
} else {
if (optionalMinLength.isPresent()) {
if (isNotBlank(descriptionContent.toString())) {
descriptionContent.newLine(true);
}
descriptionContent.boldText(labels.getLabel(MINLENGTH_COLUMN)).text(COLON).literalText(optionalMinLength.get().toString());
}
if (optionalMaxLength.isPresent()) {
if (isNotBlank(descriptionContent.toString())) {
descriptionContent.newLine(true);
}
descriptionContent.boldText(labels.getLabel(MAXLENGTH_COLUMN)).text(COLON).literalText(optionalMaxLength.get().toString());
}
}
if (optionalPattern.isPresent()) {
if (isNotBlank(descriptionContent.toString())) {
descriptionContent.newLine(true);
}
descriptionContent.boldText(labels.getLabel(PATTERN_COLUMN)).text(COLON).literalText(Json.pretty(optionalPattern.get()));
}
DecimalFormat numberFormatter = new DecimalFormat("#.##",
DecimalFormatSymbols.getInstance(config.getOutputLanguage().toLocale()));
if (optionalMinValue.isPresent()) {
if (isNotBlank(descriptionContent.toString())) {
descriptionContent.newLine(true);
}
String minValueColumn = exclusiveMin ? labels.getLabel(MINVALUE_EXCLUSIVE_COLUMN) : labels.getLabel(MINVALUE_COLUMN);
descriptionContent.boldText(minValueColumn).text(COLON).literalText(numberFormatter.format(optionalMinValue.get()));
}
if (optionalMaxValue.isPresent()) {
if (isNotBlank(descriptionContent.toString())) {
descriptionContent.newLine(true);
}
String maxValueColumn = exclusiveMax ? labels.getLabel(MAXVALUE_EXCLUSIVE_COLUMN) : labels.getLabel(MAXVALUE_COLUMN);
descriptionContent.boldText(maxValueColumn).text(COLON).literalText(numberFormatter.format(optionalMaxValue.get()));
}
if (optionalExample.isPresent()) {
if (isNotBlank(description) || optionalDefaultValue.isPresent()) {
descriptionContent.newLine(true);
}
descriptionContent.boldText(labels.getLabel(EXAMPLE_COLUMN)).text(COLON).literalText(Json.pretty(optionalExample.get()));
}
nameColumnBuilder.add(propertyNameContent.toString());
descriptionColumnBuilder.add(descriptionContent.toString());
schemaColumnBuilder.add(propertyType.displaySchema(markupDocBuilder));
});
}
return tableComponent.apply(markupDocBuilder, TableComponent.parameters(
nameColumnBuilder.build(),
descriptionColumnBuilder.build(),
schemaColumnBuilder.build()));
}
public static class Parameters {
private final Map<String, Property> properties;
private final String parameterName;
private final List<ObjectType> inlineDefinitions;
public Parameters(Map<String, Property> properties,
String parameterName,
List<ObjectType> inlineDefinitions) {
this.properties = Validate.notNull(properties, "Properties must not be null");
this.parameterName = Validate.notBlank(parameterName, "ParameterName must not be blank");
this.inlineDefinitions = Validate.notNull(inlineDefinitions, "InlineDefinitions must not be null");
}
}
}

View File

@@ -0,0 +1,173 @@
/*
* Copyright 2017 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.component;
import ch.netzwerg.paleo.StringColumn;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.internal.adapter.PropertyAdapter;
import io.github.swagger2markup.internal.resolver.DocumentResolver;
import io.github.swagger2markup.internal.type.ObjectType;
import io.github.swagger2markup.internal.type.Type;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.model.PathOperation;
import io.github.swagger2markup.spi.MarkupComponent;
import io.github.swagger2markup.spi.PathsDocumentExtension;
import io.swagger.models.Response;
import io.swagger.models.properties.Property;
import io.swagger.util.Json;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.Validate;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static ch.netzwerg.paleo.ColumnIds.StringColumnId;
import static io.github.swagger2markup.Labels.*;
import static io.github.swagger2markup.internal.utils.InlineSchemaUtils.createInlineType;
import static io.github.swagger2markup.internal.utils.MapUtils.toSortedMap;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.*;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public class ResponseComponent extends MarkupComponent<ResponseComponent.Parameters> {
private final TableComponent tableComponent;
private final DocumentResolver definitionDocumentResolver;
ResponseComponent(Swagger2MarkupConverter.Context context,
DocumentResolver definitionDocumentResolver) {
super(context);
this.definitionDocumentResolver = Validate.notNull(definitionDocumentResolver, "DocumentResolver must not be null");
this.tableComponent = new TableComponent(context);
}
public static ResponseComponent.Parameters parameters(PathOperation operation,
int titleLevel,
List<ObjectType> inlineDefinitions) {
return new ResponseComponent.Parameters(operation, titleLevel, inlineDefinitions);
}
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
PathOperation operation = params.operation;
Map<String, Response> responses = operation.getOperation().getResponses();
MarkupDocBuilder responsesBuilder = copyMarkupDocBuilder(markupDocBuilder);
applyPathsDocumentExtension(new PathsDocumentExtension.Context(PathsDocumentExtension.Position.OPERATION_RESPONSES_BEGIN, responsesBuilder, operation));
if (MapUtils.isNotEmpty(responses)) {
StringColumn.Builder httpCodeColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(HTTP_CODE_COLUMN)))
.putMetaData(TableComponent.WIDTH_RATIO, "2");
StringColumn.Builder descriptionColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(DESCRIPTION_COLUMN)))
.putMetaData(TableComponent.WIDTH_RATIO, "14")
.putMetaData(TableComponent.HEADER_COLUMN, "true");
StringColumn.Builder schemaColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(SCHEMA_COLUMN)))
.putMetaData(TableComponent.WIDTH_RATIO, "4")
.putMetaData(TableComponent.HEADER_COLUMN, "true");
Map<String, Response> sortedResponses = toSortedMap(responses, config.getResponseOrdering());
sortedResponses.forEach((String responseName, Response response) -> {
String schemaContent = labels.getLabel(NO_CONTENT);
if (response.getSchema() != null) {
Property property = response.getSchema();
Type type = new PropertyAdapter(property).getType(definitionDocumentResolver);
if (config.isInlineSchemaEnabled()) {
type = createInlineType(type, labels.getLabel(RESPONSE) + " " + responseName, operation.getId() + " " + labels.getLabel(RESPONSE) + " " + responseName, params.inlineDefinitions);
}
schemaContent = type.displaySchema(markupDocBuilder);
}
MarkupDocBuilder descriptionBuilder = copyMarkupDocBuilder(markupDocBuilder);
descriptionBuilder.text(markupDescription(config.getSwaggerMarkupLanguage(), markupDocBuilder, response.getDescription()));
Map<String, Property> headers = response.getHeaders();
if (MapUtils.isNotEmpty(headers)) {
descriptionBuilder.newLine(true).boldText(labels.getLabel(HEADERS_COLUMN)).text(COLON);
for (Map.Entry<String, Property> header : headers.entrySet()) {
descriptionBuilder.newLine(true);
Property headerProperty = header.getValue();
PropertyAdapter headerPropertyAdapter = new PropertyAdapter(headerProperty);
Type propertyType = headerPropertyAdapter.getType(definitionDocumentResolver);
String headerDescription = markupDescription(config.getSwaggerMarkupLanguage(), markupDocBuilder, headerProperty.getDescription());
Optional<Object> optionalDefaultValue = headerPropertyAdapter.getDefaultValue();
descriptionBuilder
.literalText(header.getKey())
.text(String.format(" (%s)", propertyType.displaySchema(markupDocBuilder)));
if (isNotBlank(headerDescription) || optionalDefaultValue.isPresent()) {
descriptionBuilder.text(COLON);
if (isNotBlank(headerDescription) && !headerDescription.endsWith("."))
headerDescription += ".";
descriptionBuilder.text(headerDescription);
optionalDefaultValue.ifPresent(o -> descriptionBuilder.text(" ")
.boldText(labels.getLabel(DEFAULT_COLUMN))
.text(COLON).literalText(Json.pretty(o)));
}
}
}
httpCodeColumnBuilder.add(boldText(markupDocBuilder, responseName));
descriptionColumnBuilder.add(descriptionBuilder.toString());
schemaColumnBuilder.add(schemaContent);
});
responsesBuilder = tableComponent.apply(responsesBuilder, TableComponent.parameters(httpCodeColumnBuilder.build(),
descriptionColumnBuilder.build(),
schemaColumnBuilder.build()));
}
applyPathsDocumentExtension(new PathsDocumentExtension.Context(PathsDocumentExtension.Position.OPERATION_RESPONSES_END, responsesBuilder, operation));
String responsesContent = responsesBuilder.toString();
applyPathsDocumentExtension(new PathsDocumentExtension.Context(PathsDocumentExtension.Position.OPERATION_RESPONSES_BEFORE, markupDocBuilder, operation));
if (isNotBlank(responsesContent)) {
markupDocBuilder.sectionTitleLevel(params.titleLevel, labels.getLabel(RESPONSES));
markupDocBuilder.text(responsesContent);
}
applyPathsDocumentExtension(new PathsDocumentExtension.Context(PathsDocumentExtension.Position.OPERATION_RESPONSES_AFTER, markupDocBuilder, operation));
return markupDocBuilder;
}
/**
* Apply extension context to all OperationsContentExtension.
*
* @param context context
*/
private void applyPathsDocumentExtension(PathsDocumentExtension.Context context) {
extensionRegistry.getPathsDocumentExtensions().forEach(extension -> extension.apply(context));
}
public static class Parameters {
private final PathOperation operation;
private final int titleLevel;
private final List<ObjectType> inlineDefinitions;
public Parameters(PathOperation operation,
int titleLevel,
List<ObjectType> inlineDefinitions) {
this.operation = Validate.notNull(operation, "PathOperation must not be null");
this.titleLevel = titleLevel;
this.inlineDefinitions = Validate.notNull(inlineDefinitions, "InlineDefinitions must not be null");
}
}
}

View File

@@ -0,0 +1,123 @@
/*
* Copyright 2017 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.component;
import ch.netzwerg.paleo.StringColumn;
import com.google.common.base.Joiner;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.internal.resolver.DocumentResolver;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.model.PathOperation;
import io.github.swagger2markup.spi.MarkupComponent;
import io.github.swagger2markup.spi.PathsDocumentExtension;
import io.swagger.models.auth.SecuritySchemeDefinition;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.Validate;
import java.util.List;
import java.util.Map;
import static ch.netzwerg.paleo.ColumnIds.StringColumnId;
import static io.github.swagger2markup.Labels.*;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.*;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public class SecuritySchemeComponent extends MarkupComponent<SecuritySchemeComponent.Parameters> {
private final Map<String, SecuritySchemeDefinition> securityDefinitions;
private final DocumentResolver securityDocumentResolver;
private final TableComponent tableComponent;
public SecuritySchemeComponent(Swagger2MarkupConverter.Context context,
DocumentResolver securityDocumentResolver) {
super(context);
this.securityDefinitions = context.getSwagger().getSecurityDefinitions();
this.securityDocumentResolver = Validate.notNull(securityDocumentResolver, "SecurityDocumentResolver must not be null");
this.tableComponent = new TableComponent(context);
}
public static SecuritySchemeComponent.Parameters parameters(PathOperation operation,
int titleLevel) {
return new SecuritySchemeComponent.Parameters(operation, titleLevel);
}
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
PathOperation operation = params.operation;
MarkupDocBuilder securityBuilder = copyMarkupDocBuilder(markupDocBuilder);
List<Map<String, List<String>>> securitySchemes = operation.getOperation().getSecurity();
applyPathsDocumentExtension(new PathsDocumentExtension.Context(PathsDocumentExtension.Position.OPERATION_SECURITY_BEGIN, securityBuilder, operation));
if (CollectionUtils.isNotEmpty(securitySchemes)) {
StringColumn.Builder typeColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(TYPE_COLUMN)))
.putMetaData(TableComponent.WIDTH_RATIO, "3");
StringColumn.Builder nameColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(NAME_COLUMN)))
.putMetaData(TableComponent.WIDTH_RATIO, "4");
StringColumn.Builder scopeColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(SCOPES_COLUMN)))
.putMetaData(TableComponent.WIDTH_RATIO, "13")
.putMetaData(TableComponent.HEADER_COLUMN, "true");
for (Map<String, List<String>> securityScheme : securitySchemes) {
for (Map.Entry<String, List<String>> securityEntry : securityScheme.entrySet()) {
String securityKey = securityEntry.getKey();
String type = labels.getLabel(UNKNOWN);
if (securityDefinitions != null && securityDefinitions.containsKey(securityKey)) {
type = securityDefinitions.get(securityKey).getType();
}
typeColumnBuilder.add(boldText(markupDocBuilder, type));
nameColumnBuilder.add(boldText(markupDocBuilder, crossReference(markupDocBuilder, securityDocumentResolver.apply(securityKey), securityKey, securityKey)));
scopeColumnBuilder.add(Joiner.on(",").join(securityEntry.getValue()));
}
}
securityBuilder = tableComponent.apply(securityBuilder, TableComponent.parameters(typeColumnBuilder.build(),
nameColumnBuilder.build(),
scopeColumnBuilder.build()));
}
applyPathsDocumentExtension(new PathsDocumentExtension.Context(PathsDocumentExtension.Position.OPERATION_SECURITY_END, securityBuilder, operation));
String securityContent = securityBuilder.toString();
applyPathsDocumentExtension(new PathsDocumentExtension.Context(PathsDocumentExtension.Position.OPERATION_SECURITY_BEFORE, markupDocBuilder, operation));
if (isNotBlank(securityContent)) {
markupDocBuilder.sectionTitleLevel(params.titleLevel, labels.getLabel(SECURITY));
markupDocBuilder.text(securityContent);
}
applyPathsDocumentExtension(new PathsDocumentExtension.Context(PathsDocumentExtension.Position.OPERATION_SECURITY_AFTER, markupDocBuilder, operation));
return markupDocBuilder;
}
/**
* Apply extension context to all OperationsContentExtension.
*
* @param context context
*/
private void applyPathsDocumentExtension(PathsDocumentExtension.Context context) {
extensionRegistry.getPathsDocumentExtensions().forEach(extension -> extension.apply(context));
}
public static class Parameters {
private final PathOperation operation;
private final int titleLevel;
public Parameters(PathOperation operation,
int titleLevel) {
this.operation = Validate.notNull(operation, "PathOperation must not be null");
this.titleLevel = titleLevel;
}
}
}

View File

@@ -0,0 +1,135 @@
/*
* Copyright 2017 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.component;
import ch.netzwerg.paleo.StringColumn;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.spi.MarkupComponent;
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.lang3.Validate;
import java.util.Map;
import static ch.netzwerg.paleo.ColumnIds.StringColumnId;
import static io.github.swagger2markup.Labels.*;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.copyMarkupDocBuilder;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.markupDescription;
import static io.github.swagger2markup.spi.SecurityDocumentExtension.Position;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public class SecuritySchemeDefinitionComponent extends MarkupComponent<SecuritySchemeDefinitionComponent.Parameters> {
private final TableComponent tableComponent;
public SecuritySchemeDefinitionComponent(Swagger2MarkupConverter.Context context) {
super(context);
this.tableComponent = new TableComponent(context);
}
public static SecuritySchemeDefinitionComponent.Parameters parameters(String securitySchemeDefinitionName,
SecuritySchemeDefinition securitySchemeDefinition,
int titleLevel) {
return new SecuritySchemeDefinitionComponent.Parameters(securitySchemeDefinitionName, securitySchemeDefinition, titleLevel);
}
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
String securitySchemeDefinitionName = params.securitySchemeDefinitionName;
SecuritySchemeDefinition securitySchemeDefinition = params.securitySchemeDefinition;
applySecurityDocumentExtension(new SecurityDocumentExtension.Context(Position.SECURITY_SCHEME_BEFORE, markupDocBuilder, securitySchemeDefinitionName, securitySchemeDefinition));
markupDocBuilder.sectionTitleWithAnchorLevel(params.titleLevel, securitySchemeDefinitionName);
applySecurityDocumentExtension(new SecurityDocumentExtension.Context(Position.SECURITY_SCHEME_BEGIN, markupDocBuilder, securitySchemeDefinitionName, securitySchemeDefinition));
String description = securitySchemeDefinition.getDescription();
if (isNotBlank(description)) {
markupDocBuilder.paragraph(markupDescription(config.getSwaggerMarkupLanguage(), markupDocBuilder, description));
}
buildSecurityScheme(markupDocBuilder, securitySchemeDefinition);
applySecurityDocumentExtension(new SecurityDocumentExtension.Context(Position.SECURITY_SCHEME_END, markupDocBuilder, securitySchemeDefinitionName, securitySchemeDefinition));
applySecurityDocumentExtension(new SecurityDocumentExtension.Context(Position.SECURITY_SCHEME_AFTER, markupDocBuilder, securitySchemeDefinitionName, securitySchemeDefinition));
return markupDocBuilder;
}
private MarkupDocBuilder buildSecurityScheme(MarkupDocBuilder markupDocBuilder, SecuritySchemeDefinition securityScheme) {
String type = securityScheme.getType();
MarkupDocBuilder paragraphBuilder = copyMarkupDocBuilder(markupDocBuilder);
paragraphBuilder.italicText(labels.getLabel(TYPE)).textLine(COLON + type);
if (securityScheme instanceof ApiKeyAuthDefinition) {
paragraphBuilder.italicText(labels.getLabel(NAME)).textLine(COLON + ((ApiKeyAuthDefinition) securityScheme).getName());
paragraphBuilder.italicText(labels.getLabel(IN)).textLine(COLON + ((ApiKeyAuthDefinition) securityScheme).getIn());
return markupDocBuilder.paragraph(paragraphBuilder.toString(), true);
} else if (securityScheme instanceof OAuth2Definition) {
OAuth2Definition oauth2Scheme = (OAuth2Definition) securityScheme;
String flow = oauth2Scheme.getFlow();
paragraphBuilder.italicText(labels.getLabel(FLOW)).textLine(COLON + flow);
if (isNotBlank(oauth2Scheme.getAuthorizationUrl())) {
paragraphBuilder.italicText(labels.getLabel(AUTHORIZATION_URL)).textLine(COLON + oauth2Scheme.getAuthorizationUrl());
}
if (isNotBlank(oauth2Scheme.getTokenUrl())) {
paragraphBuilder.italicText(labels.getLabel(TOKEN_URL)).textLine(COLON + oauth2Scheme.getTokenUrl());
}
StringColumn.Builder nameColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(NAME_COLUMN)))
.putMetaData(TableComponent.WIDTH_RATIO, "3")
.putMetaData(TableComponent.HEADER_COLUMN, "true");
StringColumn.Builder descriptionColumnBuilder = StringColumn.builder(StringColumnId.of(labels.getLabel(DESCRIPTION_COLUMN)))
.putMetaData(TableComponent.WIDTH_RATIO, "17")
.putMetaData(TableComponent.HEADER_COLUMN, "true");
if (oauth2Scheme.getScopes() != null) {
for (Map.Entry<String, String> scope : oauth2Scheme.getScopes().entrySet()) {
nameColumnBuilder.add(scope.getKey());
descriptionColumnBuilder.add(scope.getValue());
}
}
markupDocBuilder.paragraph(paragraphBuilder.toString(), true);
return tableComponent.apply(markupDocBuilder, TableComponent.parameters(nameColumnBuilder.build(),
descriptionColumnBuilder.build()));
} else {
return markupDocBuilder.paragraph(paragraphBuilder.toString(), true);
}
}
/**
* Apply extension context to all SecurityContentExtension
*
* @param context context
*/
private void applySecurityDocumentExtension(SecurityDocumentExtension.Context context) {
extensionRegistry.getSecurityDocumentExtensions().forEach(extension -> extension.apply(context));
}
public static class Parameters {
private final String securitySchemeDefinitionName;
private final SecuritySchemeDefinition securitySchemeDefinition;
private final int titleLevel;
public Parameters(String securitySchemeDefinitionName,
SecuritySchemeDefinition securitySchemeDefinition,
int titleLevel) {
this.securitySchemeDefinitionName = Validate.notBlank(securitySchemeDefinitionName, "SecuritySchemeDefinitionName must not be empty");
this.securitySchemeDefinition = Validate.notNull(securitySchemeDefinition, "SecuritySchemeDefinition must not be null");
this.titleLevel = titleLevel;
}
}
}

View File

@@ -0,0 +1,76 @@
/*
* Copyright 2017 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.component;
import ch.netzwerg.paleo.DataFrame;
import ch.netzwerg.paleo.StringColumn;
import io.github.swagger2markup.Swagger2MarkupConverter;
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.MarkupComponent;
import javaslang.collection.Array;
import javaslang.collection.IndexedSeq;
import javaslang.collection.List;
import org.apache.commons.lang3.StringUtils;
public class TableComponent extends MarkupComponent<TableComponent.Parameters> {
public static final String WIDTH_RATIO = "widthRatio";
public static final String HEADER_COLUMN = "headerColumn";
public TableComponent(Swagger2MarkupConverter.Context context) {
super(context);
}
public static TableComponent.Parameters parameters(StringColumn... columns) {
return new TableComponent.Parameters(columns);
}
public static boolean isNotBlank(StringColumn column) {
return !column.getValues().filter(StringUtils::isNotBlank).isEmpty();
}
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
DataFrame dataFrame = params.dataFrame;
java.util.List<MarkupTableColumn> columnSpecs = dataFrame.getColumns().map(column -> {
Integer widthRatio = Integer.valueOf(column.getMetaData().get(WIDTH_RATIO).getOrElse("0"));
return new MarkupTableColumn(column.getId().getName())
.withWidthRatio(widthRatio)
.withHeaderColumn(Boolean.parseBoolean(column.getMetaData().get(HEADER_COLUMN).getOrElse("false")))
.withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^" + widthRatio);
}
).toJavaList();
IndexedSeq<IndexedSeq<String>> columnValues = dataFrame.getColumns()
.map(column -> ((StringColumn) column).getValues());
java.util.List<java.util.List<String>> cells = Array.range(0, dataFrame.getRowCount())
.map(rowNumber -> columnValues.map(values -> values.get(rowNumber)).toJavaList()).toJavaList();
return markupDocBuilder.tableWithColumnSpecs(columnSpecs, cells);
}
public static class Parameters {
private final DataFrame dataFrame;
public Parameters(StringColumn... columns) {
this.dataFrame = DataFrame.ofAll(List.of(columns).filter(TableComponent::isNotBlank));
}
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright 2017 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.component;
import io.github.swagger2markup.Labels;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.spi.MarkupComponent;
import io.swagger.models.Tag;
import org.apache.commons.lang3.Validate;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public class TagsComponent extends MarkupComponent<TagsComponent.Parameters> {
public TagsComponent(Swagger2MarkupConverter.Context context) {
super(context);
}
public static TagsComponent.Parameters parameters(List<Tag> tags,
int titleLevel) {
return new TagsComponent.Parameters(tags, titleLevel);
}
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
markupDocBuilder.sectionTitleLevel(params.titleLevel, labels.getLabel(Labels.TAGS));
List<String> tagsList = params.tags.stream()
.map(this::mapToString).collect(Collectors.toList());
if (config.getTagOrdering() != null)
Collections.sort(tagsList, config.getTagOrdering());
markupDocBuilder.unorderedList(tagsList);
return markupDocBuilder;
}
private String mapToString(Tag tag) {
String name = tag.getName();
String description = tag.getDescription();
if (isNotBlank(description)) {
return name + COLON + description;
} else {
return name;
}
}
public static class Parameters {
private final List<Tag> tags;
private final int titleLevel;
public Parameters(List<Tag> tags,
int titleLevel) {
this.tags = Validate.notNull(tags, "Tags must not be null");
this.titleLevel = titleLevel;
}
}
}

View File

@@ -0,0 +1,83 @@
/*
* Copyright 2017 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.component;
import io.github.swagger2markup.Labels;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.spi.MarkupComponent;
import io.swagger.models.Swagger;
import org.apache.commons.lang3.Validate;
import java.util.List;
import java.util.stream.Collectors;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.copyMarkupDocBuilder;
import static org.apache.commons.collections4.CollectionUtils.isNotEmpty;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.lang3.StringUtils.join;
public class UriSchemeComponent extends MarkupComponent<UriSchemeComponent.Parameters> {
public UriSchemeComponent(Swagger2MarkupConverter.Context context) {
super(context);
}
public static UriSchemeComponent.Parameters parameters(Swagger swagger, int titleLevel) {
return new UriSchemeComponent.Parameters(swagger, titleLevel);
}
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
Swagger swagger = params.swagger;
if (isNotBlank(swagger.getHost()) || isNotBlank(swagger.getBasePath()) || isNotEmpty(swagger.getSchemes())) {
markupDocBuilder.sectionTitleLevel(params.titleLevel, labels.getLabel(Labels.URI_SCHEME));
MarkupDocBuilder paragraphBuilder = copyMarkupDocBuilder(markupDocBuilder);
if (isNotBlank(swagger.getHost())) {
paragraphBuilder.italicText(labels.getLabel(Labels.HOST))
.textLine(COLON + swagger.getHost());
}
if (isNotBlank(swagger.getBasePath())) {
paragraphBuilder.italicText(labels.getLabel(Labels.BASE_PATH))
.textLine(COLON + swagger.getBasePath());
}
if (isNotEmpty(swagger.getSchemes())) {
List<String> schemes = swagger.getSchemes().stream()
.map(Enum::toString)
.collect(Collectors.toList());
paragraphBuilder.italicText(labels.getLabel(Labels.SCHEMES))
.textLine(COLON + join(schemes, ", "));
}
markupDocBuilder.paragraph(paragraphBuilder.toString(), true);
}
return markupDocBuilder;
}
public static class Parameters {
private final int titleLevel;
private final Swagger swagger;
public Parameters(Swagger swagger, int titleLevel) {
this.swagger = Validate.notNull(swagger);
this.titleLevel = titleLevel;
}
}
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright 2017 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.component;
import io.github.swagger2markup.Labels;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.spi.MarkupComponent;
import io.swagger.models.Info;
import org.apache.commons.lang3.Validate;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.copyMarkupDocBuilder;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public class VersionInfoComponent extends MarkupComponent<VersionInfoComponent.Parameters> {
public VersionInfoComponent(Swagger2MarkupConverter.Context context) {
super(context);
}
public static VersionInfoComponent.Parameters parameters(Info info,
int titleLevel) {
return new VersionInfoComponent.Parameters(info, titleLevel);
}
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
String version = params.info.getVersion();
if (isNotBlank(version)) {
markupDocBuilder.sectionTitleLevel(params.titleLevel, labels.getLabel(Labels.CURRENT_VERSION));
MarkupDocBuilder paragraphBuilder = copyMarkupDocBuilder(markupDocBuilder);
paragraphBuilder.italicText(labels.getLabel(Labels.VERSION)).textLine(COLON + version);
markupDocBuilder.paragraph(paragraphBuilder.toString(), true);
}
return markupDocBuilder;
}
public static class Parameters {
private final int titleLevel;
private final Info info;
public Parameters(
Info info,
int titleLevel) {
this.info = Validate.notNull(info, "Info must not be null");
this.titleLevel = titleLevel;
}
}
}

View File

@@ -0,0 +1,194 @@
/*
* Copyright 2017 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.Labels;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.internal.component.DefinitionComponent;
import io.github.swagger2markup.internal.resolver.DefinitionDocumentNameResolver;
import io.github.swagger2markup.internal.resolver.DefinitionDocumentResolverDefault;
import io.github.swagger2markup.internal.resolver.DefinitionDocumentResolverFromDefinition;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.spi.MarkupComponent;
import io.swagger.models.Model;
import org.apache.commons.collections4.MapUtils;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static io.github.swagger2markup.internal.utils.MapUtils.toSortedMap;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.copyMarkupDocBuilder;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.crossReference;
import static io.github.swagger2markup.spi.DefinitionsDocumentExtension.Context;
import static io.github.swagger2markup.spi.DefinitionsDocumentExtension.Position;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
/**
* @author Robert Winkler
*/
public class DefinitionsDocument extends MarkupComponent<DefinitionsDocument.Parameters> {
private static final String DEFINITIONS_ANCHOR = "definitions";
private static final List<String> IGNORED_DEFINITIONS = Collections.singletonList("Void");
private final DefinitionComponent definitionComponent;
private final DefinitionDocumentResolverDefault definitionDocumentResolverDefault;
private final DefinitionDocumentNameResolver definitionDocumentNameResolver;
public DefinitionsDocument(Swagger2MarkupConverter.Context context) {
super(context);
if (config.isSeparatedDefinitionsEnabled()) {
if (logger.isDebugEnabled()) {
logger.debug("Create separated definition files is enabled.");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Create separated definition files is disabled.");
}
}
this.definitionDocumentNameResolver = new DefinitionDocumentNameResolver(context);
this.definitionComponent = new DefinitionComponent(context, new DefinitionDocumentResolverFromDefinition(context));
this.definitionDocumentResolverDefault = new DefinitionDocumentResolverDefault(context);
}
public static DefinitionsDocument.Parameters parameters(Map<String, Model> definitions) {
return new DefinitionsDocument.Parameters(definitions);
}
/**
* Builds the definitions MarkupDocument.
*
* @return the definitions MarkupDocument
*/
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, DefinitionsDocument.Parameters params) {
Map<String, Model> definitions = params.definitions;
if (MapUtils.isNotEmpty(definitions)) {
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder));
buildDefinitionsTitle(markupDocBuilder, labels.getLabel(Labels.DEFINITIONS));
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder));
buildDefinitionsSection(markupDocBuilder, definitions);
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder));
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder));
}
return markupDocBuilder;
}
private void buildDefinitionsTitle(MarkupDocBuilder markupDocBuilder, String title) {
markupDocBuilder.sectionTitleWithAnchorLevel1(title, DEFINITIONS_ANCHOR);
}
private void buildDefinitionsSection(MarkupDocBuilder markupDocBuilder, Map<String, Model> definitions) {
Map<String, Model> sortedMap = toSortedMap(definitions, config.getDefinitionOrdering());
sortedMap.forEach((String definitionName, Model model) -> {
if (isNotBlank(definitionName)
&& checkThatDefinitionIsNotInIgnoreList(definitionName)) {
buildDefinition(markupDocBuilder, definitionName, model);
}
});
}
/**
* Apply extension context to all DefinitionsContentExtension
*
* @param context context
*/
private void applyDefinitionsDocumentExtension(Context context) {
extensionRegistry.getDefinitionsDocumentExtensions().forEach(extension -> extension.apply(context));
}
/**
* Generate definition files depending on the generation mode
*
* @param definitionName definition name to process
* @param model definition model to process
*/
private void buildDefinition(MarkupDocBuilder markupDocBuilder, String definitionName, Model model) {
if (logger.isDebugEnabled()) {
logger.debug("Definition processed : '{}'", definitionName);
}
if (config.isSeparatedDefinitionsEnabled()) {
MarkupDocBuilder defDocBuilder = copyMarkupDocBuilder(markupDocBuilder);
applyDefinitionComponent(defDocBuilder, definitionName, model);
Path definitionFile = context.getOutputPath().resolve(definitionDocumentNameResolver.apply(definitionName));
defDocBuilder.writeToFileWithoutExtension(definitionFile, StandardCharsets.UTF_8);
if (logger.isDebugEnabled()) {
logger.debug("Separate definition file produced : '{}'", definitionFile);
}
definitionRef(markupDocBuilder, definitionName);
} else {
applyDefinitionComponent(markupDocBuilder, definitionName, model);
}
}
/**
* 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 markupDocBuilder the markupDocBuilder do use for output
* @param definitionName the name of the definition
* @param model the Swagger Model of the definition
*/
private void applyDefinitionComponent(MarkupDocBuilder markupDocBuilder, String definitionName, Model model) {
definitionComponent.apply(markupDocBuilder, DefinitionComponent.parameters(
definitionName,
model,
2));
}
/**
* Builds a cross-reference to a separated definition file.
*
* @param definitionName definition name to target
*/
private void definitionRef(MarkupDocBuilder markupDocBuilder, String definitionName) {
buildDefinitionTitle(markupDocBuilder, crossReference(markupDocBuilder, definitionDocumentResolverDefault.apply(definitionName), definitionName, definitionName), "ref-" + definitionName);
}
/**
* Builds definition title
*
* @param markupDocBuilder the markupDocBuilder do use for output
* @param title definition title
* @param anchor optional anchor (null => auto-generate from title)
*/
private void buildDefinitionTitle(MarkupDocBuilder markupDocBuilder, String title, String anchor) {
markupDocBuilder.sectionTitleWithAnchorLevel2(title, anchor);
}
public static class Parameters {
private final Map<String, Model> definitions;
public Parameters(Map<String, Model> definitions) {
this.definitions = definitions;
}
}
}

View File

@@ -0,0 +1,161 @@
/*
* Copyright 2017 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.Labels;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.internal.component.*;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.spi.MarkupComponent;
import io.swagger.models.Contact;
import io.swagger.models.Info;
import io.swagger.models.Swagger;
import io.swagger.models.Tag;
import org.apache.commons.lang3.Validate;
import java.util.List;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.markupDescription;
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.isNotBlank;
public class OverviewDocument extends MarkupComponent<OverviewDocument.Parameters> {
public static final int SECTION_TITLE_LEVEL = 2;
private static final String OVERVIEW_ANCHOR = "overview";
private final VersionInfoComponent versionInfoComponent;
private final ContactInfoComponent contactInfoComponent;
private final LicenseInfoComponent licenseInfoComponent;
private final UriSchemeComponent uriSchemeComponent;
private final TagsComponent tagsComponent;
private final ProducesComponent producesComponent;
private final ConsumesComponent consumesComponent;
public OverviewDocument(Swagger2MarkupConverter.Context context) {
super(context);
versionInfoComponent = new VersionInfoComponent(context);
contactInfoComponent = new ContactInfoComponent(context);
licenseInfoComponent = new LicenseInfoComponent(context);
uriSchemeComponent = new UriSchemeComponent(context);
tagsComponent = new TagsComponent(context);
producesComponent = new ProducesComponent(context);
consumesComponent = new ConsumesComponent(context);
}
public static OverviewDocument.Parameters parameters(Swagger swagger) {
return new OverviewDocument.Parameters(swagger);
}
/**
* Builds the overview MarkupDocument.
*
* @return the overview MarkupDocument
*/
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, OverviewDocument.Parameters params) {
Swagger swagger = params.swagger;
Info info = swagger.getInfo();
buildDocumentTitle(markupDocBuilder, info.getTitle());
applyOverviewDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder));
buildOverviewTitle(markupDocBuilder, labels.getLabel(Labels.OVERVIEW));
applyOverviewDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder));
buildDescriptionParagraph(markupDocBuilder, info.getDescription());
buildVersionInfoSection(markupDocBuilder, info);
buildContactInfoSection(markupDocBuilder, info.getContact());
buildLicenseInfoSection(markupDocBuilder, info);
buildUriSchemeSection(markupDocBuilder, swagger);
buildTagsSection(markupDocBuilder, swagger.getTags());
buildConsumesSection(markupDocBuilder, swagger.getConsumes());
buildProducesSection(markupDocBuilder, swagger.getProduces());
applyOverviewDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder));
applyOverviewDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder));
return markupDocBuilder;
}
private void buildDocumentTitle(MarkupDocBuilder markupDocBuilder, String title) {
markupDocBuilder.documentTitle(title);
}
private void buildOverviewTitle(MarkupDocBuilder markupDocBuilder, String title) {
markupDocBuilder.sectionTitleWithAnchorLevel1(title, OVERVIEW_ANCHOR);
}
void buildDescriptionParagraph(MarkupDocBuilder markupDocBuilder, String description) {
if (isNotBlank(description)) {
markupDocBuilder.paragraph(markupDescription(config.getSwaggerMarkupLanguage(), markupDocBuilder, description));
}
}
private void buildVersionInfoSection(MarkupDocBuilder markupDocBuilder, Info info) {
if (info != null) {
versionInfoComponent.apply(markupDocBuilder, VersionInfoComponent.parameters(info, SECTION_TITLE_LEVEL));
}
}
private void buildContactInfoSection(MarkupDocBuilder markupDocBuilder, Contact contact) {
if (contact != null) {
contactInfoComponent.apply(markupDocBuilder, ContactInfoComponent.parameters(contact, SECTION_TITLE_LEVEL));
}
}
private void buildLicenseInfoSection(MarkupDocBuilder markupDocBuilder, Info info) {
if (info != null) {
licenseInfoComponent.apply(markupDocBuilder, LicenseInfoComponent.parameters(info, SECTION_TITLE_LEVEL));
}
}
private void buildUriSchemeSection(MarkupDocBuilder markupDocBuilder, Swagger swagger) {
uriSchemeComponent.apply(markupDocBuilder, UriSchemeComponent.parameters(swagger, SECTION_TITLE_LEVEL));
}
private void buildTagsSection(MarkupDocBuilder markupDocBuilder, List<Tag> tags) {
if (isNotEmpty(tags)) {
tagsComponent.apply(markupDocBuilder, TagsComponent.parameters(tags, SECTION_TITLE_LEVEL));
}
}
private void buildConsumesSection(MarkupDocBuilder markupDocBuilder, List<String> consumes) {
if (isNotEmpty(consumes)) {
consumesComponent.apply(markupDocBuilder, ConsumesComponent.parameters(consumes, SECTION_TITLE_LEVEL));
}
}
private void buildProducesSection(MarkupDocBuilder markupDocBuilder, List<String> produces) {
if (isNotEmpty(produces)) {
producesComponent.apply(markupDocBuilder, ProducesComponent.parameters(produces, SECTION_TITLE_LEVEL));
}
}
/**
* Apply extension context to all OverviewContentExtension
*
* @param context context
*/
private void applyOverviewDocumentExtension(Context context) {
extensionRegistry.getOverviewDocumentExtensions().forEach(extension -> extension.apply(context));
}
public static class Parameters {
private final Swagger swagger;
public Parameters(Swagger swagger) {
this.swagger = Validate.notNull(swagger, "Swagger must not be null");
}
}
}

View File

@@ -0,0 +1,258 @@
/*
* Copyright 2017 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 com.google.common.collect.Multimap;
import io.github.swagger2markup.GroupBy;
import io.github.swagger2markup.Labels;
import io.github.swagger2markup.Swagger2MarkupConfig;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.internal.component.PathOperationComponent;
import io.github.swagger2markup.internal.resolver.DefinitionDocumentResolverFromOperation;
import io.github.swagger2markup.internal.resolver.OperationDocumentNameResolver;
import io.github.swagger2markup.internal.resolver.OperationDocumentResolverDefault;
import io.github.swagger2markup.internal.resolver.SecurityDocumentResolver;
import io.github.swagger2markup.internal.utils.PathUtils;
import io.github.swagger2markup.internal.utils.RegexUtils;
import io.github.swagger2markup.internal.utils.TagUtils;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.model.PathOperation;
import io.github.swagger2markup.spi.MarkupComponent;
import io.swagger.models.Path;
import io.swagger.models.Tag;
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 org.apache.commons.lang3.text.WordUtils;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.copyMarkupDocBuilder;
import static io.github.swagger2markup.internal.utils.MarkupDocBuilderUtils.crossReference;
import static io.github.swagger2markup.spi.PathsDocumentExtension.Context;
import static io.github.swagger2markup.spi.PathsDocumentExtension.Position;
import static io.github.swagger2markup.utils.IOUtils.normalizeName;
/**
* @author Robert Winkler
*/
public class PathsDocument extends MarkupComponent<PathsDocument.Parameters> {
private static final String PATHS_ANCHOR = "paths";
private final PathOperationComponent pathOperationComponent;
private final OperationDocumentNameResolver operationDocumentNameResolver;
private final OperationDocumentResolverDefault operationDocumentResolverDefault;
public PathsDocument(Swagger2MarkupConverter.Context context) {
super(context);
this.pathOperationComponent = new PathOperationComponent(context,
new DefinitionDocumentResolverFromOperation(context),
new SecurityDocumentResolver(context));
this.operationDocumentNameResolver = new OperationDocumentNameResolver(context);
this.operationDocumentResolverDefault = new OperationDocumentResolverDefault(context);
if (logger.isDebugEnabled()) {
if (config.isGeneratedExamplesEnabled()) {
logger.debug("Generate examples is enabled.");
} else {
logger.debug("Generate examples is disabled.");
}
if (config.isSeparatedOperationsEnabled()) {
logger.debug("Create separated operation files is enabled.");
} else {
logger.debug("Create separated operation files is disabled.");
}
}
}
public static PathsDocument.Parameters parameters(Map<String, Path> paths) {
return new PathsDocument.Parameters(paths);
}
/**
* Builds the paths MarkupDocument.
*
* @return the paths MarkupDocument
*/
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, PathsDocument.Parameters params) {
Map<String, Path> paths = params.paths;
if (MapUtils.isNotEmpty(paths)) {
applyPathsDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder));
buildPathsTitle(markupDocBuilder);
applyPathsDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder));
buildsPathsSection(markupDocBuilder, paths);
applyPathsDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder));
applyPathsDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder));
}
return markupDocBuilder;
}
/**
* Builds the paths section. Groups the paths either as-is, by tags or using regex.
*
* @param paths the Swagger paths
*/
private void buildsPathsSection(MarkupDocBuilder markupDocBuilder, Map<String, Path> paths) {
List<PathOperation> pathOperations = PathUtils.toPathOperationsList(paths, getBasePath(), config.getOperationOrdering());
if (CollectionUtils.isNotEmpty(pathOperations)) {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
pathOperations.forEach(operation -> buildOperation(markupDocBuilder, operation, config));
} else if (config.getPathsGroupedBy() == GroupBy.TAGS) {
Validate.notEmpty(context.getSwagger().getTags(), "Tags must not be empty, when operations are grouped by tags");
// Group operations by tag
Multimap<String, PathOperation> operationsGroupedByTag = TagUtils.groupOperationsByTag(pathOperations, config.getOperationOrdering());
Map<String, Tag> tagsMap = TagUtils.toSortedMap(context.getSwagger().getTags(), config.getTagOrdering());
tagsMap.forEach((String tagName, Tag tag) -> {
markupDocBuilder.sectionTitleWithAnchorLevel2(WordUtils.capitalize(tagName), tagName + "_resource");
String description = tag.getDescription();
if (StringUtils.isNotBlank(description)) {
markupDocBuilder.paragraph(description);
}
operationsGroupedByTag.get(tagName).forEach(operation -> buildOperation(markupDocBuilder, operation, config));
});
} else if (config.getPathsGroupedBy() == GroupBy.REGEX) {
Validate.notNull(config.getHeaderPattern(), "Header regex pattern must not be empty when operations are grouped using regex");
Pattern headerPattern = config.getHeaderPattern();
Multimap<String, PathOperation> operationsGroupedByRegex = RegexUtils.groupOperationsByRegex(pathOperations, headerPattern);
Set<String> keys = operationsGroupedByRegex.keySet();
String[] sortedHeaders = RegexUtils.toSortedArray(keys);
for (String header : sortedHeaders) {
markupDocBuilder.sectionTitleWithAnchorLevel2(WordUtils.capitalize(header), header + "_resource");
operationsGroupedByRegex.get(header).forEach(operation -> buildOperation(markupDocBuilder, operation, config));
}
}
}
}
/**
* Builds the path title depending on the operationsGroupedBy configuration setting.
*/
private void buildPathsTitle(MarkupDocBuilder markupDocBuilder) {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
buildPathsTitle(markupDocBuilder, labels.getLabel(Labels.PATHS));
} else if (config.getPathsGroupedBy() == GroupBy.REGEX) {
buildPathsTitle(markupDocBuilder, labels.getLabel(Labels.OPERATIONS));
} else {
buildPathsTitle(markupDocBuilder, labels.getLabel(Labels.RESOURCES));
}
}
/**
* Returns the basePath which should be prepended to the relative path
*
* @return either the relative or the full path
*/
private String getBasePath() {
if (config.isBasePathPrefixEnabled()) {
return StringUtils.defaultString(context.getSwagger().getBasePath());
}
return "";
}
private void buildPathsTitle(MarkupDocBuilder markupDocBuilder, String title) {
markupDocBuilder.sectionTitleWithAnchorLevel1(title, PATHS_ANCHOR);
}
/**
* Apply extension context to all OperationsContentExtension.
*
* @param context context
*/
private void applyPathsDocumentExtension(Context context) {
extensionRegistry.getPathsDocumentExtensions().forEach(extension -> extension.apply(context));
}
/**
* Builds a path operation depending on generation mode.
*
* @param operation operation
*/
private void buildOperation(MarkupDocBuilder markupDocBuilder, PathOperation operation, Swagger2MarkupConfig config) {
if (config.isSeparatedOperationsEnabled()) {
MarkupDocBuilder pathDocBuilder = copyMarkupDocBuilder(markupDocBuilder);
applyPathOperationComponent(pathDocBuilder, operation);
java.nio.file.Path operationFile = context.getOutputPath().resolve(operationDocumentNameResolver.apply(operation));
pathDocBuilder.writeToFileWithoutExtension(operationFile, StandardCharsets.UTF_8);
if (logger.isDebugEnabled()) {
logger.debug("Separate operation file produced : '{}'", operationFile);
}
buildOperationRef(markupDocBuilder, operation);
} else {
applyPathOperationComponent(markupDocBuilder, operation);
}
if (logger.isDebugEnabled()) {
logger.debug("Operation processed : '{}' (normalized id = '{}')", operation, normalizeName(operation.getId()));
}
}
/**
* Builds a path operation.
*
* @param markupDocBuilder the docbuilder do use for output
* @param operation the Swagger Operation
*/
private void applyPathOperationComponent(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
if (operation != null) {
pathOperationComponent.apply(markupDocBuilder, PathOperationComponent.parameters(operation));
}
}
/**
* Builds a cross-reference to a separated operation file
*
* @param markupDocBuilder the markupDocBuilder do use for output
* @param operation the Swagger Operation
*/
private void buildOperationRef(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
buildOperationTitle(markupDocBuilder, crossReference(markupDocBuilder, operationDocumentResolverDefault.apply(operation), operation.getId(), operation.getTitle()), "ref-" + operation.getId());
}
/**
* Adds a operation title to the document.
*
* @param title the operation title
* @param anchor optional anchor (null => auto-generate from title)
*/
private void buildOperationTitle(MarkupDocBuilder markupDocBuilder, String title, String anchor) {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
markupDocBuilder.sectionTitleWithAnchorLevel2(title, anchor);
} else {
markupDocBuilder.sectionTitleWithAnchorLevel3(title, anchor);
}
}
public static class Parameters {
private final Map<String, Path> paths;
public Parameters(Map<String, Path> paths) {
this.paths = paths;
}
}
}

View File

@@ -0,0 +1,96 @@
/*
* Copyright 2017 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.Swagger2MarkupConverter;
import io.github.swagger2markup.internal.component.SecuritySchemeDefinitionComponent;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.spi.MarkupComponent;
import io.swagger.models.auth.SecuritySchemeDefinition;
import org.apache.commons.collections4.MapUtils;
import java.util.Map;
import static io.github.swagger2markup.Labels.SECURITY;
import static io.github.swagger2markup.internal.utils.MapUtils.toSortedMap;
import static io.github.swagger2markup.spi.SecurityDocumentExtension.Context;
import static io.github.swagger2markup.spi.SecurityDocumentExtension.Position;
/**
* @author Robert Winkler
*/
public class SecurityDocument extends MarkupComponent<SecurityDocument.Parameters> {
private static final String SECURITY_ANCHOR = "securityScheme";
private final SecuritySchemeDefinitionComponent securitySchemeDefinitionComponent;
public SecurityDocument(Swagger2MarkupConverter.Context context) {
super(context);
this.securitySchemeDefinitionComponent = new SecuritySchemeDefinitionComponent(context);
}
public static SecurityDocument.Parameters parameters(Map<String, SecuritySchemeDefinition> securitySchemeDefinitions) {
return new SecurityDocument.Parameters(securitySchemeDefinitions);
}
/**
* Builds the security MarkupDocument.
*
* @return the security MarkupDocument
*/
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, SecurityDocument.Parameters params) {
Map<String, SecuritySchemeDefinition> definitions = params.securitySchemeDefinitions;
if (MapUtils.isNotEmpty(definitions)) {
applySecurityDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder));
buildSecurityTitle(markupDocBuilder, labels.getLabel(SECURITY));
applySecurityDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder));
buildSecuritySchemeDefinitionsSection(markupDocBuilder, definitions);
applySecurityDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder));
applySecurityDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder));
}
return markupDocBuilder;
}
private void buildSecurityTitle(MarkupDocBuilder markupDocBuilder, String title) {
markupDocBuilder.sectionTitleWithAnchorLevel1(title, SECURITY_ANCHOR);
}
private void buildSecuritySchemeDefinitionsSection(MarkupDocBuilder markupDocBuilder, Map<String, SecuritySchemeDefinition> securitySchemes) {
Map<String, SecuritySchemeDefinition> securitySchemeNames = toSortedMap(securitySchemes, null); // TODO : provide a dedicated ordering configuration for security schemes
securitySchemeNames.forEach((String securitySchemeName, SecuritySchemeDefinition securityScheme) ->
securitySchemeDefinitionComponent.apply(markupDocBuilder, SecuritySchemeDefinitionComponent.parameters(
securitySchemeName, securityScheme, 2
)));
}
/**
* Apply extension context to all SecurityContentExtension
*
* @param context context
*/
private void applySecurityDocumentExtension(Context context) {
extensionRegistry.getSecurityDocumentExtensions().forEach(extension -> extension.apply(context));
}
public static class Parameters {
private final Map<String, SecuritySchemeDefinition> securitySchemeDefinitions;
public Parameters(Map<String, SecuritySchemeDefinition> securitySchemeDefinitions) {
this.securitySchemeDefinitions = securitySchemeDefinitions;
}
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2017 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.resolver;
import io.github.swagger2markup.Swagger2MarkupConverter;
import java.io.File;
import static io.github.swagger2markup.utils.IOUtils.normalizeName;
public class DefinitionDocumentNameResolver extends DocumentResolver {
public DefinitionDocumentNameResolver(Swagger2MarkupConverter.Context context) {
super(context);
}
public String apply(String definitionName) {
if (config.isSeparatedDefinitionsEnabled())
return new File(config.getSeparatedDefinitionsFolder(), markupDocBuilder.addFileExtension(normalizeName(definitionName))).getPath();
else
return markupDocBuilder.addFileExtension(config.getDefinitionsDocument());
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2017 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.resolver;
import io.github.swagger2markup.Swagger2MarkupConverter;
import static org.apache.commons.lang3.StringUtils.defaultString;
/**
* Default {@code DocumentResolver} functor
*/
public class DefinitionDocumentResolverDefault extends DocumentResolver {
private final DefinitionDocumentNameResolver definitionDocumentNameResolver;
public DefinitionDocumentResolverDefault(Swagger2MarkupConverter.Context context) {
super(context);
this.definitionDocumentNameResolver = new DefinitionDocumentNameResolver(context);
}
public String apply(String definitionName) {
if (!config.isInterDocumentCrossReferencesEnabled() || context.getOutputPath() == null)
return null;
else
return defaultString(config.getInterDocumentCrossReferencesPrefix()) + definitionDocumentNameResolver.apply(definitionName);
}
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright 2017 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.resolver;
import io.github.swagger2markup.Swagger2MarkupConverter;
import static io.github.swagger2markup.utils.IOUtils.normalizeName;
import static org.apache.commons.lang3.StringUtils.defaultString;
/**
* Overrides definition document resolver functor for inter-document cross-references from definitions files.
* This implementation simplifies the path between two definitions because all definitions are in the same path.
*/
public class DefinitionDocumentResolverFromDefinition extends DefinitionDocumentResolverDefault {
public DefinitionDocumentResolverFromDefinition(Swagger2MarkupConverter.Context context) {
super(context);
}
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

@@ -0,0 +1,27 @@
package io.github.swagger2markup.internal.resolver;
import io.github.swagger2markup.Swagger2MarkupConverter;
import java.io.File;
import static org.apache.commons.lang3.StringUtils.defaultString;
/**
* Overrides definition document resolver functor for inter-document cross-references from operations files.
* This implementation adapt the relative paths to definitions files
*/
public class DefinitionDocumentResolverFromOperation extends DefinitionDocumentResolverDefault {
public DefinitionDocumentResolverFromOperation(Swagger2MarkupConverter.Context context) {
super(context);
}
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

@@ -0,0 +1,38 @@
/*
* Copyright 2017 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.resolver;
import io.github.swagger2markup.Swagger2MarkupConfig;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import javaslang.Function1;
/**
* A functor to return the document part of an inter-document cross-references, depending on the context.
*/
public abstract class DocumentResolver implements Function1<String, String> {
Swagger2MarkupConverter.Context context;
MarkupDocBuilder markupDocBuilder;
Swagger2MarkupConfig config;
public DocumentResolver(Swagger2MarkupConverter.Context context) {
this.context = context;
this.markupDocBuilder = context.createMarkupDocBuilder();
this.config = context.getConfig();
}
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2017 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.resolver;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.model.PathOperation;
import java.io.File;
import static io.github.swagger2markup.utils.IOUtils.normalizeName;
public class OperationDocumentNameResolver extends OperationDocumentResolver {
public OperationDocumentNameResolver(Swagger2MarkupConverter.Context context) {
super(context);
}
public String apply(PathOperation operation) {
if (config.isSeparatedOperationsEnabled())
return new File(config.getSeparatedOperationsFolder(), markupDocBuilder.addFileExtension(normalizeName(operation.getId()))).getPath();
else
return markupDocBuilder.addFileExtension(config.getPathsDocument());
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright 2017 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.resolver;
import io.github.swagger2markup.Swagger2MarkupConfig;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.markup.builder.MarkupDocBuilder;
import io.github.swagger2markup.model.PathOperation;
import javaslang.Function1;
/**
* A functor to return the document part of an inter-document cross-references, depending on the context.
*/
public abstract class OperationDocumentResolver implements Function1<PathOperation, String> {
Swagger2MarkupConverter.Context context;
MarkupDocBuilder markupDocBuilder;
Swagger2MarkupConfig config;
public OperationDocumentResolver(Swagger2MarkupConverter.Context context) {
this.context = context;
this.markupDocBuilder = context.createMarkupDocBuilder();
this.config = context.getConfig();
}
}

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