Compare commits

...

201 Commits

Author SHA1 Message Date
Hugo Mercado
d20d1a854f removed Java 7 as an option on README. 2018-01-23 19:22:29 -05:00
Hugo Mercado
952695086f disabled tests for not supported languages 2018-01-23 18:50:30 -05:00
HugoMario
c8c42703c6 Merge pull request #7481 from swagger-api/prepare-release-3.0.0-rc0
prepare release 3.0.0-rc0
2018-01-23 14:55:21 -05:00
Hugo Mercado
fe1ac46907 prepare release 3.0.0-rc0 2018-01-23 14:53:06 -05:00
Hugo Mercado
bee674a85e updated artifact id and version for new repo (swagger-codegen-generators). 2018-01-23 13:38:39 -05:00
Hugo Mercado
c91d3648c9 removed no supported templates. 2018-01-23 11:42:45 -05:00
Hugo Mercado
c744e30715 Let app load inflector templates from class resources since they have been moved to a different repo. 2018-01-23 06:43:14 -05:00
Hugo Mercado
9574cb2aed added support for system properties on codegen generator module. 2018-01-23 05:14:35 -05:00
Hugo Mercado
5add84acda enabled system properties on CLI. 2018-01-23 04:47:41 -05:00
Hugo Mercado
b0557fce35 avoid creation of user-defined classes for aliases on java codegen languages. 2018-01-23 01:46:54 -05:00
Hugo Mercado
3d2574c304 refactored swagger-generator endpoints. 2018-01-21 23:18:20 -05:00
Hugo Mercado
852fe048c5 disabled test until “swagger-codegen-templates” dependencies be updated. 2018-01-21 23:17:48 -05:00
Hugo Mercado
61c2b6e4aa added clients and servers languages endpoint. 2018-01-20 05:04:37 -05:00
Hugo Mercado
a0d5033a6b included swagger 2.0 dependencies in order to support conversion. 2018-01-17 06:16:23 -05:00
Hugo Mercado
5fa41b561a changed CI pom files to be built with java 8. 2018-01-17 00:28:09 -05:00
Hugo Mercado
5521c04e65 tweaked additional properties and fixed conflicts with previous version. 2018-01-16 23:48:15 -05:00
Hugo Mercado
678ad89ad6 removed override annontation. 2018-01-13 23:34:13 -05:00
Hugo Mercado
d5954b05b4 Merge remote-tracking branch 'origin/master' into 3.0.0
# Conflicts:
#	.travis.yml
#	modules/swagger-codegen-cli/pom.xml
#	modules/swagger-codegen-maven-plugin/pom.xml
#	modules/swagger-codegen/pom.xml
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractAdaCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AdaCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java
#	modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java
#	modules/swagger-generator/pom.xml
#	pom.xml
#	pom.xml.circleci
2018-01-13 23:33:02 -05:00
HugoMario
f3ff2f3e92 Merge pull request #7390 from keithchong/7389-GenerateWithJaxrsSpecFails
[7389] Generate service with -l jaxrs-spec fails
2018-01-12 18:10:09 -05:00
Keith Chong
7a72271169 [7389] Generate service with -l jaxrs-spec fails 2018-01-12 13:03:37 -05:00
Hugo Mercado
c20b61b0e8 added codegen templates dependency on swagger generator module. 2018-01-11 00:40:28 -05:00
Hugo Mercado
4129c2b701 use new inflector codegen class. 2018-01-10 17:10:47 -05:00
Hugo Mercado
773e1e0eaa Disable test due templates used have been moved to a different repo. 2018-01-10 15:22:21 -05:00
Hugo Mercado
eeef337e6e disable test that uses removed templates. 2018-01-10 15:13:57 -05:00
Hugo Mercado
686150e173 removed new templates since they’re going to be handled from new repo. 2018-01-10 14:11:34 -05:00
Hugo Mercado
989fcbdc4c add dependency of codegen templates project and deprecated java client/inflector classes. 2018-01-10 14:10:44 -05:00
Hugo Mercado
0c9eb34e6f updated to java 8 2018-01-09 19:57:26 -05:00
Hugo Mercado
d3e63c23fe added endpoint on swagger generator to load arguments from remote json/yml file. 2018-01-09 19:52:01 -05:00
Hugo Mercado
1506adc20a added option to read arguments from a JSON or YAML file. 2018-01-09 15:49:47 -05:00
Hugo Mercado
9dbc34de7a updated test assert value. 2018-01-05 22:27:02 -05:00
Hugo Mercado
63f9c36798 Added support to generate inflector with oas3. 2018-01-04 18:35:29 -05:00
Hugo Mercado
8e169f7dcd removed unexisting method 2017-12-26 19:15:21 -05:00
Hugo Mercado
d300ebf344 moved templates files and use only one engine (handlebars) 2017-12-26 18:15:18 -05:00
Hugo Mercado
50d2430104 Issue #7186: fixed npe on reusable parameter. 2017-12-26 15:03:25 -05:00
Hugo Mercado
ca88db4610 Updated swagger core and parser to v3 on codegen cli and generator. 2017-12-23 08:13:57 -05:00
Hugo Mercado
f2a8612135 updated swagger parser and core to v3 version on codegen module. 2017-12-23 07:31:09 -05:00
HugoMario
059b2dbcaa Merge pull request #7243 from swagger-api/3.0.0_enhancements
3.0.0 enhancements
2017-12-21 22:43:26 -05:00
Hugo Mercado
a058bdcca8 Removed duplicated plugin definition. 2017-12-21 21:53:48 -05:00
Hugo Mercado
aab81ee395 Revert "disabled samples on shippable ci."
This reverts commit a88efb5e31.
2017-12-21 17:59:57 -05:00
Hugo Mercado
a88efb5e31 disabled samples on shippable ci. 2017-12-21 17:44:38 -05:00
Hugo Mercado
5ad322ca31 Removed ‘conflicted’ commented code. 2017-12-21 14:33:27 -05:00
Hugo Mercado
7bde281c24 updated travis and shippable pom files. 2017-12-21 14:04:59 -05:00
Hugo Mercado
0eedb465d4 Fixed generated model test. 2017-12-21 12:50:55 -05:00
Hugo Mercado
3f23e2a44d updated circleci pom. 2017-12-21 09:33:19 -05:00
Hugo Mercado
0cde324a36 disabled test at method levels 2017-12-21 02:10:51 -05:00
Hugo Mercado
81cc5dd197 Removed more useless prints. 2017-12-21 02:10:13 -05:00
Hugo Mercado
d8e72fd0f1 disabled test on executable project. These need to be updated according to new changes/libraries. 2017-12-21 01:09:01 -05:00
Hugo Mercado
d412406287 Removed useless print. 2017-12-21 00:47:10 -05:00
Hugo Mercado
ae75341291 temporaryly disabled tests no related to java client/server languages. And tweaked some fews. 2017-12-21 00:46:26 -05:00
Hugo Mercado
6740b263eb Disabled tests on GoModelTest class until tweak oas3 issues related to it. 2017-12-20 03:51:18 -05:00
Hugo Mercado
6dcb92dc9b disabled test on CodegenConfiguratorTest class while figure out issues. 2017-12-20 01:17:03 -05:00
Hugo Mercado
06a20f831e Merge branch '3.0.0' into 3.0.0_enhancements
# Conflicts:
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangClientCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SymfonyServerCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java
#	pom.xml
2017-12-16 03:04:26 -05:00
Hugo Mercado
ec70826001 Merge remote-tracking branch 'origin/master' into 3.0.0 2017-12-16 01:47:54 -05:00
Hugo Mercado
802bbc1596 Implement inflector 2.0 for codegen generator server. 2017-12-16 01:41:16 -05:00
Hugo Mercado
86f299a1d2 removed classes related to previous framework and classes with swagger 2.0 references. 2017-12-16 01:18:07 -05:00
Hugo Mercado
45388247c2 use remaining “hasMore” extensions on templates. 2017-12-09 13:25:19 -05:00
Hugo Mercado
1d149ed63d Removed helper for ‘hasAuthMethod’ var. 2017-12-09 10:20:58 -05:00
Hugo Mercado
c0d7e46428 updated codegen security vars on templates where they are used. 2017-12-09 09:04:31 -05:00
Hugo Mercado
fee7a460f1 removed “is, isNot, has, hasNot” vars in codegen security class. 2017-12-09 07:37:17 -05:00
Hugo Mercado
aef933dc2f added getters on codegen response class. 2017-12-09 07:03:07 -05:00
Hugo Mercado
eb19817fdf added getters to codeine operation class. 2017-12-09 06:59:26 -05:00
Hugo Mercado
d49d82b1dc removed “is, isNot, has, hasNot” vars from CodegenResponse object. 2017-12-09 06:56:42 -05:00
Hugo Mercado
d140d6c83b replaced remaining vars on CodegenParameter class with extensions. 2017-12-08 15:19:06 -05:00
Hugo Mercado
7a1fdb9d03 replaced “isHeaderParam” var on templates by vendor extension. 2017-12-08 04:13:59 -05:00
Hugo Mercado
ff01b26003 replaced “isPathParam” var on templates by vendor extension. 2017-12-08 03:54:09 -05:00
Hugo Mercado
6fbc5cd7db replaced “isQueryParam” var on templates by vendor extension. 2017-12-08 03:34:47 -05:00
Hugo Mercado
e76ce202b4 removed if helper from map elements on templates, fixed list elements syntax 2017-12-08 02:16:29 -05:00
Hugo Mercado
5e792217ce Fixed missing space typo on template. 2017-12-08 00:11:31 -05:00
Hugo Mercado
8a5819eef9 Revert "allow extension helpers to work with maps."
This reverts commit 64b6495d6b.
2017-12-08 00:07:22 -05:00
Hugo Mercado
64b6495d6b allow extension helpers to work with maps. 2017-12-08 00:00:12 -05:00
Hugo Mercado
3bb3f0336d removed “is, isNot, has, hasNot” vars from CodegenParameter class, and use vendor extensions instead. 2017-12-06 17:53:02 -05:00
Hugo Mercado
6918ac1acb removed is, has, isNot, hasNot vars from CodegenOperation class and updated templates to work with vendor extensions instead. 2017-12-06 05:14:03 -05:00
Hugo Mercado
e6b5a001e1 removed blank type. 2017-12-05 17:12:53 -05:00
Hugo Mercado
cb5d99a413 updated templates with extensions. 2017-12-05 13:51:47 -05:00
Hugo Mercado
633445cca8 included new helpers. 2017-12-05 12:52:30 -05:00
Hugo Mercado
076cd467d1 refactor extension helpers. 2017-12-05 12:51:46 -05:00
Hugo Mercado
d815550e26 refactored boolean value method for extensions. 2017-12-01 22:27:21 -05:00
Hugo Mercado
c47e5b7604 removed “is, isNot, has, hasNot” vars from CodegenProperty and replace them vendor extensions. 2017-12-01 20:05:36 -05:00
Hugo Mercado
099a4e3ae9 moved constants to codegen constants class. 2017-11-29 15:36:18 -05:00
Hugo Mercado
00d493bc36 removed all ‘has’, ‘is’ remaining vars on codegen model. 2017-11-28 22:33:09 -05:00
Hugo Mercado
76740a5453 replaced ‘hasEnums’ property for a vendor extension. 2017-11-28 22:01:40 -05:00
Hugo Mercado
c7d438aabc updated model and pojo hbs template to use new helpers. 2017-11-28 17:08:48 -05:00
Hugo Mercado
0660442f66 refactor templates helpers registering. 2017-11-28 16:45:53 -05:00
Hugo Mercado
a32894b79c use codegen extension instead a member var for ‘isEnum’ property. 2017-11-28 15:45:12 -05:00
Hugo Mercado
1d48d9b30d Replaced ‘isEnum’ property for a vendor extension. 2017-11-27 18:29:53 -05:00
Hugo Mercado
523de5f3c1 removed “isAlias” property and replaced by a vendor extension. 2017-11-25 03:37:51 -05:00
Hugo Mercado
18da348ebb moved java helper class to different package. 2017-11-24 13:45:55 -05:00
Hugo Mercado
34dc1d4934 created helper for default codegen class. 2017-11-24 01:49:11 -05:00
Hugo Mercado
115cced92a updated test class to oas3. 2017-11-24 00:01:31 -05:00
Hugo Mercado
1389ce080c moved post process model method to an util class and tweaked its references. 2017-11-23 23:41:28 -05:00
Hugo Mercado
c014102516 Merge branch '3.0.0' into 3.0.0_enhancements
# Conflicts:
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java
2017-11-23 03:30:04 -05:00
Hugo Mercado
db0fe4733c Merge branch 'master' into 3.0.0 2017-11-23 03:09:43 -05:00
Hugo Mercado
d7b6d8e2d6 handle spaces on default api template. 2017-11-23 03:05:36 -05:00
Hugo Mercado
df92fc0562 Read the right collection format. 2017-11-23 01:36:08 -05:00
Hugo Mercado
638b9227d8 load the right template. 2017-11-23 01:35:28 -05:00
Hugo Mercado
de95fb2d54 renamed method that retrieves imports in model template. 2017-11-21 22:18:26 -05:00
Hugo Mercado
708d630a57 Added getters for codeine parameter and operation POJO-s. 2017-11-21 22:10:42 -05:00
Hugo Mercado
9721373186 Use the correct template extension. 2017-11-17 11:54:57 -05:00
Hugo Mercado
51591f8b04 fixed conflict references 2017-11-17 03:35:05 -05:00
Hugo Mercado
58ef1c7c2a Merge branch '3.0.0' into 3.0.0_enhancements
# Conflicts:
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ElixirClientCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellHttpClientCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java
#	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SymfonyServerCodegen.java
#	modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java
#	modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CsharpModelEnumTest.java
2017-11-17 02:21:49 -05:00
wing328
a8053e9aec Merge remote-tracking branch 'origin/master' into 3.0.0 2017-11-14 14:30:43 +08:00
Hugo Mercado
d72d085e29 tweaked modelinnerenum and xmlannotations templates. 2017-11-14 01:13:52 -05:00
Hugo Mercado
4cf480a060 fixed spaces issue on pojo template 2017-11-14 00:47:16 -05:00
Hugo Mercado
7ad1127cbf updated model template, fixing spaces issues among properties. 2017-11-13 22:17:22 -05:00
Hugo Mercado
502efdf54e changes getters in order to make them readeable on template. 2017-11-13 22:16:10 -05:00
Hugo Mercado
71405e5d5a wrap helpers in one class. 2017-11-13 06:34:38 -05:00
Hugo Mercado
6694cb2489 added capability to support multiple kind of helpers 2017-11-13 06:01:15 -05:00
wing328
b0472ab0d9 skip google check style 2017-11-12 21:47:40 +08:00
wing328
4afc1d143a add reset_minion: true to shippable yml 2017-11-12 21:27:10 +08:00
Hugo Mercado
32fa0d6428 added helper to handle class definition from helper 2017-11-09 22:59:30 -05:00
Hugo Mercado
e652b73bfb moved java-import helper class. 2017-11-09 22:11:01 -05:00
Hugo Mercado
87ea1145ca added capability to support mustaches and handlebars as templates engines. 2017-11-06 19:42:49 -05:00
Hugo Mercado
4e1670e7b0 tweaked "first" and "last" elements on lists for some handlebars templates. 2017-11-06 19:32:19 -05:00
Hugo Mercado
73eb30dc74 fixed typos 2017-11-06 19:25:18 -05:00
Hugo Mercado
68a653bf29 added option to select template engine (handlebars, mustache) 2017-11-06 19:24:58 -05:00
Hugo Mercado
3dcae0b921 moved templates files to a version folder. 2017-11-06 11:35:53 -05:00
Hugo Mercado
6637f9f26a placed handlebars templates in their own folder. 2017-11-06 11:25:50 -05:00
Hugo Mercado
cc60211c0c revert changes on mustaches templates in order to move new changes on handlebars templates. 2017-11-06 09:52:27 -05:00
Hugo Mercado
3df4207e7c added helper for imports on java model template. 2017-11-03 09:58:18 -05:00
Hugo Mercado
0f8214dd37 Added getters and setters for codeine pojo’s 2017-11-02 18:57:25 -05:00
Hugo Mercado
cd397f5bf5 replaced “-first” by “@first” element in Java/api_doc template to fix error on handlebar. 2017-11-02 18:56:03 -05:00
Hugo Mercado
97ae7a1e67 added handlerbars and twear some of the java mustache templates. 2017-11-01 12:49:45 -05:00
Hugo Mercado
abb2f9d506 removed print. 2017-10-26 19:11:29 -05:00
Hugo Mercado
5c53d4bb0b moar java model tests improvements 2017-10-26 16:30:56 -05:00
Hugo Mercado
67380e475e tweaked java model test class 2017-10-26 01:34:51 -05:00
Hugo Mercado
702007660e added test on schema sample object. 2017-10-25 15:34:29 -05:00
Hugo Mercado
5e665bf949 tweaked java model enum tests. 2017-10-25 15:30:03 -05:00
Hugo Mercado
0c9f72c5a2 tweaked java inheritance tests. 2017-10-25 15:21:18 -05:00
Hugo Mercado
544677fe26 fixed default degenerator tests. 2017-10-23 19:12:49 -05:00
Hugo Mercado
c3553d16f1 removed useless print. 2017-10-22 23:39:10 -05:00
Hugo Mercado
32eeb66219 verify NPE in extensions for schema. 2017-10-22 23:35:59 -05:00
Hugo Mercado
854ad138c4 fixed default path "/" NPE issue 2017-10-22 23:35:22 -05:00
Hugo Mercado
6010ac287a fixed imports on Validate class. 2017-10-22 20:39:27 -05:00
Hugo Mercado
ba62d9c4d0 implement missed method 2017-10-22 20:39:04 -05:00
Hugo Mercado
9bfdca19f3 remove previous version dependency. 2017-10-22 20:38:45 -05:00
Hugo Mercado
864739b52a fixed references on default generator test class. 2017-10-20 04:47:11 -05:00
Hugo Mercado
5c48f8f133 fixed references on type script test classes. 2017-10-20 04:30:58 -05:00
Hugo Mercado
e368d2e77d fixed references on swift test classes. 2017-10-20 04:01:58 -05:00
Hugo Mercado
bcad62ae4e fixed references on static doc/html test classes 2017-10-20 04:00:53 -05:00
Hugo Mercado
78ce1d9b5a fixed references on scala test class. 2017-10-20 03:35:50 -05:00
Hugo Mercado
6f349bd944 fixed reference on ruby test class. 2017-10-20 03:34:59 -05:00
Hugo Mercado
73976e2408 fixed reference on python test class. 2017-10-20 03:15:09 -05:00
Hugo Mercado
4345ab403b fixed references on php model test class. 2017-10-20 03:03:17 -05:00
Hugo Mercado
d13142d344 fixed references on objective c test class. 2017-10-20 02:40:05 -05:00
Hugo Mercado
5fdd39fedd fixed references on languages test classes. 2017-10-20 02:19:46 -05:00
Hugo Mercado
1cbf28b280 fixed references for kotlin test class. 2017-10-20 02:14:06 -05:00
Hugo Mercado
c633ab68c2 fixed reference on jaxrs test classes. 2017-10-20 02:09:27 -05:00
Hugo Mercado
140aa761f3 fixed reference on javascript test classes. 2017-10-20 02:05:33 -05:00
Hugo Mercado
4d1fb8d849 fixed references on java test classes. 2017-10-20 01:07:57 -05:00
Hugo Mercado
80e48dad01 removed unused imports. 2017-10-20 01:07:12 -05:00
Hugo Mercado
91a13baac7 fixed reference on go test class. 2017-10-20 01:05:40 -05:00
Hugo Mercado
2cff3adb44 fixed reference on eiffel test class. 2017-10-20 01:05:25 -05:00
Hugo Mercado
7ad4d9c7be fixed references on csharp test classes. 2017-10-20 01:04:05 -05:00
Hugo Mercado
502f81f24c fixed references on codegen configurator test class. 2017-10-20 01:03:43 -05:00
Hugo Mercado
243fd6bb59 fixed reference on bash test class. 2017-10-20 01:00:00 -05:00
Hugo Mercado
c931e9cfd9 fixed reference on apex model test class. 2017-10-20 00:59:32 -05:00
Hugo Mercado
dab51a6e44 tweaked languages classes to work with oas3. 2017-10-19 21:52:26 -05:00
Hugo Mercado
011ad35988 tweaked languages classes. 2017-10-19 05:15:32 -05:00
Hugo Mercado
9da44bb066 Removed old reference for ada codegen class. 2017-10-18 04:52:13 -05:00
Hugo Mercado
112c1f0130 tweaked abstract languages classes. 2017-10-18 04:36:14 -05:00
Hugo Mercado
aaaddfdc51 Created util class to handle host, basepath, port, etc 2017-10-18 03:12:11 -05:00
Hugo Mercado
a54b9b4f55 fixed oas3 dependency conflicts on DefaultCodegen class. 2017-10-18 00:47:55 -05:00
Hugo Mercado
b6d145b080 switch swagger references to oas3 on default generator class 2017-10-18 00:46:48 -05:00
Hugo Mercado
30e1867836 updated open api references on tests classes. 2017-10-18 00:45:13 -05:00
Hugo Mercado
de87739567 updated example generator. 2017-10-18 00:44:56 -05:00
Hugo Mercado
77fdae7cf1 removed inline model resolver class from project to be handled on open api parser. 2017-10-18 00:44:25 -05:00
Hugo Mercado
ba9286d013 import the right class on auth parser class. 2017-10-18 00:43:44 -05:00
Hugo Mercado
7f995bbac3 updated external doc class on codegen operation pojo. 2017-10-18 00:43:34 -05:00
Hugo Mercado
9191fbcf88 updated external doc class on codegen model pojo. 2017-10-18 00:43:24 -05:00
Hugo Mercado
176e776ae7 replaced swagger parser for open api parser. 2017-10-18 00:43:15 -05:00
Hugo Mercado
20590d9933 removed the unreacheable classes due to OAS3 changes. 2017-10-18 00:43:03 -05:00
Hugo Mercado
d52c5ea4d3 updated condeg config interface to support open api objects. 2017-10-18 00:42:08 -05:00
Hugo Mercado
8a4bfd25fe updated "ClientOptInput" class to work with oas3. 2017-10-18 00:41:31 -05:00
Hugo Mercado
1b8d85988e update parser and core version to work with oas3. 2017-10-18 00:40:47 -05:00
Hugo Mercado
7cd3086fd9 Issue #6041: added setter methods to commands class. 2017-10-18 00:33:24 -05:00
Hugo Mercado
0981e94473 Issue #6041: allow commands with not options such as ‘version’. 2017-10-18 00:33:13 -05:00
Hugo Mercado
0807a8b9ec #6041: implement argparse4j library and updated SwaggerCodegen and Generate classes. 2017-10-18 00:32:56 -05:00
Hugo Mercado
48c5704422 #6041 removed annotations and imports from airline library. 2017-10-18 00:32:27 -05:00
Hugo Mercado
23f491c797 Issue #6041 removed airline dependency from pom file. 2017-10-18 00:31:53 -05:00
Hugo Mercado
026426e50c Revert "Merge pull request #6668 from swagger-api/issue-6041"
This reverts commit 3c399a335c, reversing
changes made to c690ea83d3.
2017-10-15 09:47:20 -05:00
HugoMario
3c399a335c Merge pull request #6668 from swagger-api/issue-6041
Issue 6041
2017-10-12 14:24:16 -05:00
Hugo Mercado
453f5a6a9c Merge branch '3.0.0' into issue-6041 2017-10-12 13:08:40 -05:00
Hugo Mercado
81dc39e6aa Issue #6041: added setter methods to commands class. 2017-10-12 13:07:06 -05:00
Hugo Mercado
dc277f3914 Issue #6041: allow commands with not options such as ‘version’. 2017-10-12 12:35:45 -05:00
wing328
c690ea83d3 restore google_checkstyle.xml 2017-10-12 18:32:38 +08:00
wing328
9368e4cf66 Merge branch '3.0.0' of https://github.com/swagger-api/swagger-codegen into 3.0.0 2017-10-12 18:32:06 +08:00
wing328
fc3d18278c rename google_checkstyle.xml to resolve ci failure 2017-10-12 18:31:37 +08:00
Hugo Mercado
c1f7fed968 #6041: implement argparse4j library and updated SwaggerCodegen and Generate classes. 2017-10-12 03:09:57 -05:00
Hugo Mercado
043e41e485 #6041 removed annotations and imports from airline library. 2017-10-12 02:57:49 -05:00
Hugo Mercado
7afca43f0e Issue #6041 removed airline dependency from pom file. 2017-10-12 02:46:33 -05:00
wing328
1e1c6907d8 Merge remote-tracking branch 'origin/master' into 3.0.0 2017-10-09 23:45:04 +08:00
wing328
2c7eeaa9dc Merge remote-tracking branch 'origin/master' into 3.0.0 2017-10-09 13:59:05 +08:00
wing328
fa6232e6f5 Merge remote-tracking branch 'origin/master' into 3.0.0 2017-09-24 17:38:30 +08:00
WendellDuncan
bb36831efa Propsed fix for the ApiClient runtime crash (#6523) 2017-09-23 15:32:29 +08:00
wing328
bc8b48d136 Merge remote-tracking branch 'origin/master' into 3.0.0 2017-09-21 15:13:12 +08:00
wing328
53732b8522 Merge remote-tracking branch 'origin/master' into 3.0.0 2017-09-05 00:13:31 +08:00
wing328
d806c6d6ae Merge remote-tracking branch 'origin/master' into 3.0.0 2017-08-24 10:26:16 +08:00
wing328
6947362e29 update snapshot push to 3.0.0 2017-07-27 19:45:50 +08:00
wing328
35da68cf7c Merge remote-tracking branch 'origin/master' into 3.0.0 2017-07-27 19:45:33 +08:00
wing328
97ddd81b4d Merge remote-tracking branch 'origin/master' into 3.0.0 2017-07-25 21:10:42 +08:00
wing328
1939e8f5e8 update version to 3.0.0-SNAPSHOT 2017-07-17 00:45:28 +08:00
1989 changed files with 15015 additions and 131270 deletions

View File

@@ -1,7 +1,7 @@
sudo: required
language: java
jdk:
- openjdk7
- oraclejdk8
cache:
directories:

View File

@@ -79,7 +79,7 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20
Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes
-------------------------- | ------------ | -------------------------- | -----
3.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/io/swagger/swagger-codegen-cli/3.0.0-SNAPSHOT/)| TBD | 1.0, 1.1, 1.2, 2.0, 3.0 | Major release with breaking changes
3.0.0 (upcoming major release) [rc0](https://oss.sonatype.org/content/repositories/snapshots/io/swagger/swagger-codegen-cli/3.0.0-rc0/)| TBD | 1.0, 1.1, 1.2, 2.0, 3.0 | Major release with breaking changes
2.4.0 (current master, upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/io/swagger/swagger-codegen-cli/2.4.0-SNAPSHOT/)| TBD | 1.0, 1.1, 1.2, 2.0 | Minor release with breaking changes
[2.3.0](https://github.com/swagger-api/swagger-codegen/releases/tag/v2.3.0) (**current stable**) | 2017-12-21 | 1.0, 1.1, 1.2, 2.0 | [tag v2.3.0](https://github.com/swagger-api/swagger-codegen/tree/v2.3.0)
[2.2.3](https://github.com/swagger-api/swagger-codegen/releases/tag/v2.2.3) | 2017-07-15 | 1.0, 1.1, 1.2, 2.0 | [tag v2.2.3](https://github.com/swagger-api/swagger-codegen/tree/v2.2.3)
@@ -91,15 +91,15 @@ Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes
### Prerequisites
If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 7 runtime at a minimum):
If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 8 runtime at a minimum):
```sh
wget http://central.maven.org/maven2/io/swagger/swagger-codegen-cli/2.3.0/swagger-codegen-cli-2.3.0.jar -O swagger-codegen-cli.jar
wget http://central.maven.org/maven2/io/swagger/swagger-codegen-cli/3.0.0-rc0/swagger-codegen-cli-3.0.0-rc0.jar -O swagger-codegen-cli.jar
java -jar swagger-codegen-cli.jar help
```
For Windows users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g. `Invoke-WebRequest -OutFile swagger-codegen-cli.jar http://central.maven.org/maven2/io/swagger/swagger-codegen-cli/2.3.0/swagger-codegen-cli-2.3.0.jar`
For Windows users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g. `Invoke-WebRequest -OutFile swagger-codegen-cli.jar http://central.maven.org/maven2/io/swagger/swagger-codegen-cli/3.0.0-rc0/swagger-codegen-cli-3.0.0-rc0.jar`
On a mac, it's even easier with `brew`:
```sh
@@ -108,12 +108,12 @@ brew install swagger-codegen
To build from source, you need the following installed and available in your $PATH:
* [Java 7 or 8](http://java.oracle.com)
* [Java 8](http://java.oracle.com)
* [Apache maven 3.3.3 or greater](http://maven.apache.org/)
#### OS X Users
Don't forget to install Java 7 or 8. You probably have 1.6.
Don't forget to install Java 8. You probably have 1.6 or 1.7.
Export JAVA_HOME in order to use the supported Java version:
```sh

View File

@@ -26,6 +26,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaInflector -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l inflector -o samples/server/petstore/java-inflector -DhideGenerationTimestamp=true"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l inflector -o samples/server/petstore/java-inflector -DhideGenerationTimestamp=true"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-project</artifactId>
<version>2.3.1</version>
<version>3.0.0-rc0</version>
<relativePath>../..</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -79,12 +79,39 @@
<artifactId>swagger-codegen</artifactId>
<version>${project.version}</version>
</dependency>
<!--https://github.com/airlift/airline-->
<dependency>
<groupId>io.airlift</groupId>
<artifactId>airline</artifactId>
<version>0.7</version>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-generators</artifactId>
<version>${swagger-codegen-generators-version}</version>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-core</artifactId>
<version>${swagger-core-version}</version>
</dependency>
<dependency>
<groupId>io.swagger.parser.v3</groupId>
<artifactId>swagger-parser-v3</artifactId>
<version>${swagger-parser-version}</version>
</dependency>
<dependency>
<groupId>net.sourceforge.argparse4j</groupId>
<artifactId>argparse4j</artifactId>
<version>0.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>com.googlecode.lambdaj</groupId>
<artifactId>lambdaj</artifactId>
@@ -98,15 +125,19 @@
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<!-- <version>${testng-version}</version> -->
<!-- <version>${testng-version}</version> -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<!-- <version>${jmockit-version}</version> -->
<!-- <version>${jmockit-version}</version> -->
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<swagger-codegen-generators-version>1.0.0-rc0</swagger-codegen-generators-version>
</properties>
</project>

View File

@@ -0,0 +1,234 @@
package io.swagger.codegen;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import com.google.common.io.Resources;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.apache.commons.io.Charsets;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class CLIHelper {
static String loadResourceOAS3File() {
URL url = Resources.getResource("oas3.yaml");
try {
return Resources.toString(url, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
static boolean containsOptionExtensions(Map<String, Object> extensions) {
if(extensions == null) {
return false;
}
final Object option = extensions.get("x-option");
if(option != null && StringUtils.isNotBlank(option.toString())) {
return true;
}
return false;
}
static String getCommand(String schemaName, Schema schema) {
if(schema.getExtensions() != null && !schema.getExtensions().isEmpty() && schema.getExtensions().get("x-command") != null) {
return schema.getExtensions().get("x-command").toString();
} else {
return schemaName.toLowerCase();
}
}
static String[] getArguments(Map<String, Object> extensions) {
if(extensions.get("x-short-version") != null && StringUtils.isNotBlank(extensions.get("x-short-version").toString())) {
return new String[] {extensions.get("x-short-version").toString(), extensions.get("x-option").toString()};
}
return new String[] {extensions.get("x-option").toString()};
}
static String detectCommand(String[] args) {
if(args == null || args.length == 0) {
return null;
}
String command = args[0];
if(StringUtils.isBlank(command) || command.startsWith("-")) {
return null;
}
return command;
}
static Class getClass(Schema property) {
if(property instanceof BooleanSchema) {
return Boolean.class;
}
return String.class;
}
static Object getDefault(Schema property) {
if(property instanceof BooleanSchema) {
return Boolean.TRUE;
}
return null;
}
public static Map<String, Object> createOptionValueMap(Schema schema, Map<String, Object> inputArgs) {
if(inputArgs == null || inputArgs.isEmpty()) {
return null;
}
final Map<String, Schema> properties = schema.getProperties();
if(properties == null || properties.isEmpty()) {
return null;
}
final Map<String, Object> optionValueMap = new HashMap<>();
for(String propertyName : properties.keySet()) {
final Schema property = properties.get(propertyName);
final Map<String, Object> extensions = property.getExtensions();
if(extensions == null || extensions.isEmpty()) {
continue;
}
Object value = null;
if(extensions.get("x-option") != null) {
String option = fixOptionName(extensions.get("x-option").toString());
value = inputArgs.get(option);
} else {
continue;
}
if(value == null) {
continue;
}
if(property instanceof BooleanSchema) {
optionValueMap.put(propertyName, Boolean.valueOf(value.toString()));
}
else if(property instanceof IntegerSchema) {
if(SchemaTypeUtil.INTEGER64_FORMAT.equals(property.getFormat())) {
optionValueMap.put(propertyName, Long.valueOf(value.toString()));
} else {
optionValueMap.put(propertyName, Integer.valueOf(value.toString()));
}
}
else if(property instanceof NumberSchema) {
if(SchemaTypeUtil.FLOAT_FORMAT.equals(property.getFormat())) {
optionValueMap.put(propertyName, Float.valueOf(value.toString()));
} else {
optionValueMap.put(propertyName, Double.valueOf(value.toString()));
}
}
else if(property instanceof ArraySchema) {
String inputElements = value.toString()
.replace("[", StringUtils.EMPTY)
.replace("]", StringUtils.EMPTY)
.replace(" ", StringUtils.EMPTY);
final List<String> values = new ArrayList<>(Arrays.asList(inputElements.split(",")));
optionValueMap.put(propertyName, values);
}
else {
optionValueMap.put(propertyName, value);
}
}
return optionValueMap;
}
public static Map<String, Object> createOptionValueMap(JsonNode node) {
final Map<String, Object> optionValueMap = new HashMap<>();
Iterator<String> fieldNames = node.fieldNames();
while (fieldNames.hasNext()) {
String argument = fieldNames.next();
JsonNode valueNode = node.findValue(argument);
if (valueNode.isBoolean()) {
optionValueMap.put(argument, valueNode.booleanValue());
}
else if (valueNode.isShort() || valueNode.isInt()) {
optionValueMap.put(argument, valueNode.intValue());
}
else if (valueNode.isLong()) {
optionValueMap.put(argument, valueNode.longValue());
}
else if (valueNode.isFloat()) {
optionValueMap.put(argument, valueNode.floatValue());
}
else if (valueNode.isDouble()) {
optionValueMap.put(argument, valueNode.doubleValue());
}
else if (valueNode.isArray()) {
String inputElements = valueNode.toString()
.replace("[", StringUtils.EMPTY)
.replace("]", StringUtils.EMPTY)
.replace("\"", StringUtils.EMPTY)
.replace(" ", StringUtils.EMPTY);
final List<String> values = new ArrayList<>(Arrays.asList(inputElements.split(",")));
optionValueMap.put(argument, values);
} else {
optionValueMap.put(argument, valueNode.toString()
.replace("\"", StringUtils.EMPTY));
}
}
return optionValueMap;
}
private static String fixOptionName(String option) {
option = option.substring(countDashes(option));
return option.replace("-", "_");
}
private static int countDashes(String option) {
for(int i = 0; i < option.length(); i++) {
if(option.charAt(i) != '-') {
return i;
}
}
return 0;
}
public static boolean isValidJson(String content) {
if (StringUtils.isBlank(content)) {
return false;
}
try {
new ObjectMapper().readTree(content);
return true;
} catch (IOException ex) {
return false;
}
}
public static boolean isValidYaml(String content) {
if (StringUtils.isBlank(content)) {
return false;
}
try {
new YAMLMapper().readTree(content);
return true;
} catch (IOException ex) {
return false;
}
}
public static boolean isValidURL(String urlStr) {
if (StringUtils.isBlank(urlStr)) {
return false;
}
try {
URI uri = new URI(urlStr);
return uri.getScheme().toLowerCase().startsWith("http");
}
catch (Exception e) {
return false;
}
}
}

View File

@@ -1,13 +1,25 @@
package io.swagger.codegen;
import io.airlift.airline.Cli;
import io.airlift.airline.Help;
import io.swagger.codegen.cmd.ConfigHelp;
import io.swagger.codegen.cmd.Generate;
import io.swagger.codegen.cmd.Langs;
import io.swagger.codegen.cmd.Meta;
import io.swagger.codegen.cmd.Validate;
import io.swagger.codegen.cmd.Version;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.parser.OpenAPIV3Parser;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.Argument;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Subparser;
import net.sourceforge.argparse4j.inf.Subparsers;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* User: lanwen Date: 24.03.15 Time: 17:56
@@ -19,19 +31,93 @@ import io.swagger.codegen.cmd.Version;
public class SwaggerCodegen {
public static void main(String[] args) {
String version = Version.readVersionFromResources();
@SuppressWarnings("unchecked")
Cli.CliBuilder<Runnable> builder =
Cli.<Runnable>builder("swagger-codegen-cli")
.withDescription(
String.format(
"Swagger code generator CLI (version %s). More info on swagger.io",
version))
.withDefaultCommand(Langs.class)
.withCommands(Generate.class, Meta.class, Langs.class, Help.class,
ConfigHelp.class, Validate.class, Version.class);
private static Logger LOGGER = LoggerFactory.getLogger(SwaggerCodegen.class);
builder.build().parse(args).run();
public static void main(String[] args) {
final String oas3 = CLIHelper.loadResourceOAS3File();
if(StringUtils.isBlank(oas3)) {
LOGGER.error("Could not load resource file.");
return;
}
final OpenAPI openAPI = new OpenAPIV3Parser().readContents(oas3, null, null).getOpenAPI();
final Map<String, Schema> schemaMap = openAPI.getComponents().getSchemas();
final Set<String> schemaNames = schemaMap.keySet();
final ArgumentParser codegenParser = ArgumentParsers.newFor("swagger-codegen").build();
final Subparsers subparsers = codegenParser.addSubparsers()
.title("commands")
.help("additional help")
.metavar("Command");
final Map<String, Schema> commandMap = new HashMap<>();
for(String schemaName : schemaNames) {
final Schema schema = schemaMap.get(schemaName);
final String command = CLIHelper.getCommand(schemaName, schema);
final Map<String, Schema> schemaProperties = schema.getProperties();
final Subparser parser = subparsers.addParser(command).help(command);
commandMap.put(command, schema);
if(schemaProperties == null || schemaProperties.isEmpty()) {
LOGGER.debug(String.format("there are not options for command '%s'", command));
continue;
}
for (String propertyName : schemaProperties.keySet()) {
final Schema property = schemaProperties.get(propertyName);
final Map<String, Object> extensions = property.getExtensions();
if(!CLIHelper.containsOptionExtensions(extensions)) {
LOGGER.warn(String.format("there are not option extensions for property '%s?", propertyName));
continue;
}
String[] arguments = CLIHelper.getArguments(extensions);
final Argument argument = parser.addArgument(arguments)
.type(CLIHelper.getClass(property))
.help(property.getDescription())
.metavar(StringUtils.EMPTY);
if(property instanceof BooleanSchema) {
argument.nargs("?").setConst(true);
} else if(property instanceof ArraySchema) {
argument.nargs("*");
}
}
}
final Map<String, Object> inputArgs = new HashMap<>();
try {
codegenParser.parseArgs(args, inputArgs);
} catch (ArgumentParserException e) {
codegenParser.handleError(e);
return;
}
final String userInputCommand = CLIHelper.detectCommand(args);
if(userInputCommand == null) {
LOGGER.error("No command found.");
return;
}
final Schema commandSchema = commandMap.get(userInputCommand);
if(commandSchema == null) {
LOGGER.error(String.format("There are not schema related to command '%s'", userInputCommand));
return;
}
final Map<String, Object> extensions = commandSchema.getExtensions();
if(extensions == null || extensions.isEmpty() || extensions.get("x-class-name") == null) {
LOGGER.error("Extensions are required to run command. i.e: 'x-class-name'");
return;
}
final String className = extensions.get("x-class-name").toString();
try {
final Class clazz = Class.forName(className);
final Object commandObject = clazz.newInstance();
final Map<String, Object> optionValueMap = CLIHelper.createOptionValueMap(commandSchema, inputArgs);
BeanUtils.populate(commandObject, optionValueMap);
if(commandObject instanceof Runnable) {
new Thread(((Runnable) commandObject)).start();
}
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException | InvocationTargetException ex) {
LOGGER.error(String.format("Could not load class '%s' for command '%s'", className, userInputCommand), ex);
}
}
}

View File

@@ -1,18 +1,16 @@
package io.swagger.codegen.cmd;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConfigLoader;
@Command(name = "config-help", description = "Config help for chosen lang")
public class ConfigHelp implements Runnable {
@Option(name = {"-l", "--lang"}, title = "language", required = true,
description = "language to get config help for")
private String lang;
public void setLang(String lang) {
this.lang = lang;
}
@Override
public void run() {
System.out.println();

View File

@@ -1,180 +1,207 @@
package io.swagger.codegen.cmd;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.codegen.CLIHelper;
import io.swagger.codegen.ClientOptInput;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.config.CodegenConfigurator;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.core.util.Yaml;
import io.swagger.v3.parser.util.RemoteUrl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.*;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static io.swagger.codegen.CLIHelper.isValidJson;
import static io.swagger.codegen.CLIHelper.isValidURL;
import static io.swagger.codegen.CLIHelper.isValidYaml;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyAdditionalPropertiesKvpList;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyImportMappingsKvpList;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyInstantiationTypesKvpList;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyLanguageSpecificPrimitivesCsvList;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyReservedWordsMappingsKvpList;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applySystemPropertiesKvpList;
import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyTypeMappingsKvpList;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
/**
* User: lanwen Date: 24.03.15 Time: 20:22
*/
@Command(name = "generate", description = "Generate code with chosen lang")
public class Generate implements Runnable {
public static final Logger LOG = LoggerFactory.getLogger(Generate.class);
@Option(name = {"-v", "--verbose"}, description = "verbose mode")
private Boolean verbose;
protected Boolean verbose;
protected String lang;
protected String output = "";
protected String spec;
protected String templateDir;
protected String auth;
protected List<String> systemProperties = new ArrayList<>();
protected String configFile;
protected Boolean skipOverwrite;
protected String apiPackage;
protected String modelPackage;
protected String modelNamePrefix;
protected String modelNameSuffix;
protected List<String> instantiationTypes = new ArrayList<>();
protected List<String> typeMappings = new ArrayList<>();
protected List<String> additionalProperties = new ArrayList<>();
protected List<String> languageSpecificPrimitives = new ArrayList<>();
protected List<String> importMappings = new ArrayList<>();
protected String invokerPackage;
protected String groupId;
protected String artifactId;
protected String artifactVersion;
protected String library;
protected String gitUserId;
protected String gitRepoId;
protected String releaseNote;
protected String httpUserAgent;
protected List<String> reservedWordsMappings = new ArrayList<>();
protected String ignoreFileOverride;
protected Boolean removeOperationIdPrefix;
private String url;
@Option(name = {"-l", "--lang"}, title = "language", required = true,
description = "client language to generate (maybe class name in classpath, required)")
private String lang;
public void setVerbose(Boolean verbose) {
this.verbose = verbose;
}
@Option(name = {"-o", "--output"}, title = "output directory",
description = "where to write the generated files (current dir by default)")
private String output = "";
public void setLang(String lang) {
this.lang = lang;
}
@Option(name = {"-i", "--input-spec"}, title = "spec file", required = true,
description = "location of the swagger spec, as URL or file (required)")
private String spec;
public void setOutput(String output) {
this.output = output;
}
@Option(name = {"-t", "--template-dir"}, title = "template directory",
description = "folder containing the template files")
private String templateDir;
public void setSpec(String spec) {
this.spec = spec;
}
@Option(
name = {"-a", "--auth"},
title = "authorization",
description = "adds authorization headers when fetching the swagger definitions remotely. "
+ "Pass in a URL-encoded string of name:header with a comma separating multiple values")
private String auth;
public void setTemplateDir(String templateDir) {
this.templateDir = templateDir;
}
@Option(
name = {"-D"},
title = "system properties",
description = "sets specified system properties in "
+ "the format of name=value,name=value (or multiple options, each with name=value)")
private List<String> systemProperties = new ArrayList<>();
public void setAuth(String auth) {
this.auth = auth;
}
@Option(
name = {"-c", "--config"},
title = "configuration file",
description = "Path to json configuration file. "
+ "File content should be in a json format {\"optionKey\":\"optionValue\", \"optionKey1\":\"optionValue1\"...} "
+ "Supported options can be different for each language. Run config-help -l {lang} command for language specific config options.")
private String configFile;
public void setSystemProperties(List<String> systemProperties) {
this.systemProperties = systemProperties;
}
@Option(name = {"-s", "--skip-overwrite"}, title = "skip overwrite",
description = "specifies if the existing files should be "
+ "overwritten during the generation.")
private Boolean skipOverwrite;
public void setConfigFile(String configFile) {
this.configFile = configFile;
}
@Option(name = {"--api-package"}, title = "api package",
description = CodegenConstants.API_PACKAGE_DESC)
private String apiPackage;
public void setSkipOverwrite(Boolean skipOverwrite) {
this.skipOverwrite = skipOverwrite;
}
@Option(name = {"--model-package"}, title = "model package",
description = CodegenConstants.MODEL_PACKAGE_DESC)
private String modelPackage;
public void setApiPackage(String apiPackage) {
this.apiPackage = apiPackage;
}
@Option(name = {"--model-name-prefix"}, title = "model name prefix",
description = CodegenConstants.MODEL_NAME_PREFIX_DESC)
private String modelNamePrefix;
public void setModelPackage(String modelPackage) {
this.modelPackage = modelPackage;
}
@Option(name = {"--model-name-suffix"}, title = "model name suffix",
description = CodegenConstants.MODEL_NAME_SUFFIX_DESC)
private String modelNameSuffix;
public void setModelNamePrefix(String modelNamePrefix) {
this.modelNamePrefix = modelNamePrefix;
}
@Option(
name = {"--instantiation-types"},
title = "instantiation types",
description = "sets instantiation type mappings in the format of type=instantiatedType,type=instantiatedType."
+ "For example (in Java): array=ArrayList,map=HashMap. In other words array types will get instantiated as ArrayList in generated code."
+ " You can also have multiple occurrences of this option.")
private List<String> instantiationTypes = new ArrayList<>();
public void setModelNameSuffix(String modelNameSuffix) {
this.modelNameSuffix = modelNameSuffix;
}
@Option(
name = {"--type-mappings"},
title = "type mappings",
description = "sets mappings between swagger spec types and generated code types "
+ "in the format of swaggerType=generatedType,swaggerType=generatedType. For example: array=List,map=Map,string=String."
+ " You can also have multiple occurrences of this option.")
private List<String> typeMappings = new ArrayList<>();
public void setInstantiationTypes(List<String> instantiationTypes) {
this.instantiationTypes = instantiationTypes;
}
@Option(
name = {"--additional-properties"},
title = "additional properties",
description = "sets additional properties that can be referenced by the mustache templates in the format of name=value,name=value."
+ " You can also have multiple occurrences of this option.")
private List<String> additionalProperties = new ArrayList<>();
public void setTypeMappings(List<String> typeMappings) {
this.typeMappings = typeMappings;
}
@Option(
name = {"--language-specific-primitives"},
title = "language specific primitives",
description = "specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: String,boolean,Boolean,Double."
+ " You can also have multiple occurrences of this option.")
private List<String> languageSpecificPrimitives = new ArrayList<>();
public void setAdditionalProperties(List<String> additionalProperties) {
this.additionalProperties = additionalProperties;
}
@Option(
name = {"--import-mappings"},
title = "import mappings",
description = "specifies mappings between a given class and the import that should be used for that class in the format of type=import,type=import."
+ " You can also have multiple occurrences of this option.")
private List<String> importMappings = new ArrayList<>();
public void setLanguageSpecificPrimitives(List<String> languageSpecificPrimitives) {
this.languageSpecificPrimitives = languageSpecificPrimitives;
}
@Option(name = {"--invoker-package"}, title = "invoker package",
description = CodegenConstants.INVOKER_PACKAGE_DESC)
private String invokerPackage;
public void setImportMappings(List<String> importMappings) {
this.importMappings = importMappings;
}
@Option(name = {"--group-id"}, title = "group id", description = CodegenConstants.GROUP_ID_DESC)
private String groupId;
public void setInvokerPackage(String invokerPackage) {
this.invokerPackage = invokerPackage;
}
@Option(name = {"--artifact-id"}, title = "artifact id",
description = CodegenConstants.ARTIFACT_ID_DESC)
private String artifactId;
public void setGroupId(String groupId) {
this.groupId = groupId;
}
@Option(name = {"--artifact-version"}, title = "artifact version",
description = CodegenConstants.ARTIFACT_VERSION_DESC)
private String artifactVersion;
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
@Option(name = {"--library"}, title = "library", description = CodegenConstants.LIBRARY_DESC)
private String library;
public void setArtifactVersion(String artifactVersion) {
this.artifactVersion = artifactVersion;
}
@Option(name = {"--git-user-id"}, title = "git user id",
description = CodegenConstants.GIT_USER_ID_DESC)
private String gitUserId;
public void setLibrary(String library) {
this.library = library;
}
@Option(name = {"--git-repo-id"}, title = "git repo id",
description = CodegenConstants.GIT_REPO_ID_DESC)
private String gitRepoId;
public void setGitUserId(String gitUserId) {
this.gitUserId = gitUserId;
}
@Option(name = {"--release-note"}, title = "release note",
description = CodegenConstants.RELEASE_NOTE_DESC)
private String releaseNote;
public void setGitRepoId(String gitRepoId) {
this.gitRepoId = gitRepoId;
}
@Option(name = {"--http-user-agent"}, title = "http user agent",
description = CodegenConstants.HTTP_USER_AGENT_DESC)
private String httpUserAgent;
public void setReleaseNote(String releaseNote) {
this.releaseNote = releaseNote;
}
@Option(
name = {"--reserved-words-mappings"},
title = "reserved word mappings",
description = "specifies how a reserved name should be escaped to. Otherwise, the default _<name> is used. For example id=identifier."
+ " You can also have multiple occurrences of this option.")
private List<String> reservedWordsMappings = new ArrayList<>();
public void setHttpUserAgent(String httpUserAgent) {
this.httpUserAgent = httpUserAgent;
}
@Option(name = {"--ignore-file-override"}, title = "ignore file override location",
description = CodegenConstants.IGNORE_FILE_OVERRIDE_DESC)
private String ignoreFileOverride;
public void setReservedWordsMappings(List<String> reservedWordsMappings) {
this.reservedWordsMappings = reservedWordsMappings;
}
@Option(name = {"--remove-operation-id-prefix"}, title = "remove prefix of the operationId",
description = CodegenConstants.REMOVE_OPERATION_ID_PREFIX_DESC)
private Boolean removeOperationIdPrefix;
public void setIgnoreFileOverride(String ignoreFileOverride) {
this.ignoreFileOverride = ignoreFileOverride;
}
public void setRemoveOperationIdPrefix(Boolean removeOperationIdPrefix) {
this.removeOperationIdPrefix = removeOperationIdPrefix;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public void run() {
loadArguments();
// attempt to read from config file
CodegenConfigurator configurator = CodegenConfigurator.fromFile(configFile);
@@ -284,4 +311,62 @@ public class Generate implements Runnable {
new DefaultGenerator().opts(clientOptInput).generate();
}
private void loadArguments() {
if (StringUtils.isBlank(this.url)) {
return;
}
final String content;
File file = new File(this.url);
if (file.exists() && file.isFile()) {
try {
content = FileUtils.readFileToString(file);
} catch (IOException e) {
LOG.error("Unable to read file: " + this.url, e);
return;
}
} else if (isValidURL(this.url)) {
try {
content = RemoteUrl.urlToString(this.url, null);
} catch (Exception e) {
LOG.error("Unable to read url: " + this.url, e);
return;
}
} else {
return;
}
if (StringUtils.isBlank(content)) {
return;
}
JsonNode node = null;
if (isValidJson(content)) {
try {
node = Json.mapper().readTree(content.getBytes());
} catch (IOException e) {
LOG.error("Unable to deserialize json from: " + this.url, e);
node = null;
}
} else if (isValidYaml(content)) {
try {
node = Yaml.mapper().readTree(content.getBytes());
} catch (IOException e) {
LOG.error("Unable to deserialize yaml from: " + this.url, e);
node = null;
}
}
if (node == null) {
return;
}
final Map<String, Object> optionValueMap = CLIHelper.createOptionValueMap(node);
try {
BeanUtils.populate(this, optionValueMap);
} catch (Exception e) {
LOG.error("Error setting values to object.", e);
}
}
}

View File

@@ -1,7 +1,6 @@
package io.swagger.codegen.cmd;
import ch.lambdaj.collection.LambdaIterable;
import io.airlift.airline.Command;
import io.swagger.codegen.CodegenConfig;
import static ch.lambdaj.Lambda.on;
@@ -11,7 +10,6 @@ import static java.util.ServiceLoader.load;
/**
* User: lanwen Date: 24.03.15 Time: 20:25
*/
@Command(name = "langs", description = "Shows available langs")
public class Langs implements Runnable {
@Override
public void run() {

View File

@@ -5,8 +5,6 @@ import com.google.common.base.CaseFormat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.SupportingFile;
import org.apache.commons.io.FileUtils;
@@ -25,10 +23,6 @@ import static com.google.common.base.Joiner.on;
/**
* User: lanwen Date: 24.03.15 Time: 20:22
*/
@Command(name = "meta", description = "MetaGenerator. Generator for creating a new template set "
+ "and configuration for Codegen. The output will be based on the language you "
+ "specify, and includes default templates to include.")
public class Meta implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(Meta.class);
@@ -36,18 +30,22 @@ public class Meta implements Runnable {
private static final String TEMPLATE_DIR_CLASSPATH = "codegen";
private static final String MUSTACHE_EXTENSION = ".mustache";
@Option(name = {"-o", "--output"}, title = "output directory",
description = "where to write the generated files (current dir by default)")
private String outputFolder = "";
@Option(name = {"-n", "--name"}, title = "name",
description = "the human-readable name of the generator")
private String name = "default";
@Option(name = {"-p", "--package"}, title = "package",
description = "the package to put the main class into (defaults to io.swagger.codegen)")
private String targetPackage = "io.swagger.codegen";
public void setOutputFolder(String outputFolder) {
this.outputFolder = outputFolder;
}
public void setName(String name) {
this.name = name;
}
public void setTargetPackage(String targetPackage) {
this.targetPackage = targetPackage;
}
@Override
public void run() {
final File targetDir = new File(outputFolder);

View File

@@ -1,29 +1,25 @@
package io.swagger.codegen.cmd;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.swagger.parser.SwaggerParser;
import io.swagger.parser.util.SwaggerDeserializationResult;
import io.swagger.v3.parser.OpenAPIV3Parser;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Command(name = "validate", description = "Validate specification")
public class Validate implements Runnable {
@Option(name = {"-i", "--input-spec"}, title = "spec file", required = true,
description = "location of the swagger spec, as URL or file (required)")
private String spec;
public void setSpec(String spec) {
this.spec = spec;
}
@Override
public void run() {
System.out.println("Validating spec file (" + spec + ")");
SwaggerParser parser = new SwaggerParser();
SwaggerDeserializationResult result = parser.readWithInfo(spec, null, true);
List<String> messageList = result.getMessages();
OpenAPIV3Parser parser = new OpenAPIV3Parser();;
List<String> messageList = parser.readWithInfo(spec, null).getMessages();
Set<String> messages = new HashSet<String>(messageList);
for (String message : messages) {

View File

@@ -1,14 +1,12 @@
package io.swagger.codegen.cmd;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import io.airlift.airline.Command;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Command(name = "version", description = "Show version information")
public class Version implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(Meta.class);

View File

@@ -0,0 +1,229 @@
openapi: 3.0.0
info:
description: "Commands options for swagger codegen"
version: "1.0.0"
title: Swagger codegen command options
contact:
email: you@your-company.com
license:
name: Apache 2.0
url: 'http://www.apache.org/licenses/LICENSE-2.0.html'
paths: {}
components:
schemas:
Generate:
x-command-description: "Generate code with chosen lang"
x-class-name: "io.swagger.codegen.cmd.Generate"
properties:
verbose:
type: "boolean"
description: "verbose mode"
x-option: "--verbose"
x-short-version: "-v"
lang:
type: "string"
title: "language"
description: "client language to generate (maybe class name in classpath, required)"
x-option: "--lang"
x-short-version: "-l"
output:
type: "string"
title: "output directory"
description: "where to write the generated files (current dir by default)"
x-option: "--output"
x-short-version: "-o"
spec:
type: "string"
title: "spec file"
description: "location of the swagger spec, as URL or file (required)"
x-option: "--input-spec"
x-short-version: "-i"
templateDir:
type: "string"
title: "template directory"
description: "folder containing the template files"
x-option: "--template-dir"
x-short-version: "-t"
auth:
type: "string"
title: "authorization"
description: "adds authorization headers when fetching the swagger definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values"
x-option: "--auth"
x-short-version: "-a"
configFile:
type: "string"
title: "configuration file"
description: Path to json configuration file. File content should be in a json format {"optionKey":"optionValue", "optionKey1":"optionValue1"...} Supported options can be different for each language. Run config-help -l {lang} command for language specific config options.
x-option: "--config"
x-short-version: "-c"
systemProperties:
type: "array"
items:
type: string
title: "System Properties"
description: "sets specified system properties in the format of name=value,name=value (or multiple options, each with name=value)"
x-option: "-D"
skipOverwrite:
type: "string"
title: "skip overwrite"
description: "specifies if the existing files should be overwritten during the generation."
x-option: "--skip-overwrite"
x-short-version: "-s"
apiPackage:
type: "string"
title: "api package"
description: "package for generated api classes"
x-option: "--api-package"
modelPackage:
type: "string"
title: "model package"
description: "package for generated models"
x-option: "--model-package"
modelNamePrefix:
type: "string"
title: "model name prefix"
description: "Prefix that will be prepended to all model names. Default is the empty string."
x-option: "--model-name-prefix"
modelNameSuffix:
type: "string"
title: "model name suffix"
description: "PrefixSuffix that will be appended to all model names. Default is the empty string."
x-option: "--model-name-suffix"
instantiationTypes:
type: "array"
items:
type: string
title: "instantiation types"
description: "sets instantiation type mappings in the format of type=instantiatedType,type=instantiatedType. For example (in Java): array=ArrayList,map=HashMap. In other words array types will get instantiated as ArrayList in generated code. You can also have multiple occurrences of this option."
x-option: "--instantiation-types"
typeMappings:
type: "array"
items:
type: string
title: "type mappings"
description: "sets mappings between swagger spec types and generated code types in the format of swaggerType=generatedType,swaggerType=generatedType. For example: array=List,map=Map,string=String. You can also have multiple occurrences of this option."
x-option: "--type-mappings"
additionalProperties:
type: "array"
items:
type: string
title: "additional properties"
description: "sets additional properties that can be referenced by the mustache templates in the format of name=value,name=value. You can also have multiple occurrences of this option."
x-option: "--additional-properties"
importMappings:
type: "array"
items:
type: string
title: "import mappings"
description: "specifies mappings between a given class and the import that should be used for that class in the format of type=import,type=import. You can also have multiple occurrences of this option."
x-option: "--import-mappings"
invokerPackage:
type: "string"
title: "invoker package"
description: "root package for generated code"
x-option: "--invoker-package"
groupId:
type: "string"
title: "group id"
description: "groupId in generated pom.xml"
x-option: "--group-id"
artifactId:
type: "string"
title: "artifact id"
description: "artifactId in generated pom.xml"
x-option: "--artifact-id"
artifactVersion:
type: "string"
title: "artifact version"
description: "artifact version generated in pom.xml"
x-option: "--artifact-version"
library:
type: "string"
title: "library"
description: "library template (sub-template)"
x-option: "--library"
gitUserId:
type: "string"
title: "git user id"
description: "Git user ID, e.g. swagger-api."
x-option: "--git-user-id"
gitRepoId:
type: "string"
title: "git repo id"
description: "Git repo ID, e.g. swagger-codegen."
x-option: "--git-repo-id"
releaseNote:
type: "string"
title: "release note"
description: "Release note, default to 'Minor update'."
x-option: "--release-note"
httpUserAgent:
type: "string"
title: "http user agent"
description: "HTTP user agent, e.g. codegen_csharp_api_client, default to 'Swagger-Codegen/{packageVersion}}/{language}'"
x-option: "--http-user-agent"
reservedWordsMappings:
type: "array"
items:
type: string
title: "reserved words mappings"
description: "pecifies how a reserved name should be escaped to. Otherwise, the default _<name> is used. For example id=identifier. You can also have multiple occurrences of this option."
x-option: "--reserved-words-mappings"
ignoreFileOverride:
type: "string"
title: "ignore file override location"
description: "Specifies an override location for the .swagger-codegen-ignore file. Most useful on initial generation."
x-option: "--ignore-file-override"
removeOperationIdPrefix:
type: "string"
title: "remove prefix of the operationId"
description: "Remove prefix of operationId, e.g. config_getId => getId"
x-option: "--remove-operation-id-prefix"
url:
type: "string"
title: "URL for arguments"
description: "load arguments from a local file or remote URL. Arguments found will replace any one placed on command."
x-option: "--url"
x-short-version: "-u"
ConfigHelp:
x-command: "config-help"
x-command-description: "Config help for chosen lang"
x-class-name: "io.swagger.codegen.cmd.ConfigHelp"
properties:
lang:
type: "string"
title: "language"
description: "language to get config help for"
x-option: "--lang"
x-short-version: "-l"
x-require: true
Meta:
x-command-description: "MetaGenerator. Generator for creating a new template set and configuration for Codegen. The output will be based on the language you specify, and includes default templates to include."
x-class-name: "io.swagger.codegen.cmd.Meta"
properties:
outputFolder:
type: "string"
title: "output directory"
description: "where to write the generated files (current dir by default)"
x-option: "--output"
x-short-version: "-o"
name:
type: "string"
title: "name"
description: "the human-readable name of the generator"
x-option: "--name"
x-short-version: "-n"
x-default-value: "default"
targetPackage:
type: "string"
title: "package"
description: "the package to put the main class into (defaults to io.swagger.codegen)"
x-option: "--package"
x-short-version: "-p"
Langs:
x-command-description: "Shows available langs"
x-class-name: "io.swagger.codegen.cmd.Langs"
Version:
x-command-description: "Show version information"
x-class-name: "io.swagger.codegen.cmd.Version"

View File

@@ -1,17 +1,27 @@
package io.swagger.codegen.cmd;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.codegen.CLIHelper;
import io.swagger.codegen.ClientOptInput;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.SwaggerCodegen;
import io.swagger.codegen.config.CodegenConfigurator;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.core.util.Yaml;
import mockit.Expectations;
import mockit.FullVerifications;
import mockit.Injectable;
import mockit.Mocked;
import mockit.Verifications;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@SuppressWarnings("unused")
public class GenerateTest {
@@ -24,7 +34,7 @@ public class GenerateTest {
@Mocked
DefaultGenerator generator;
@Test
@Test(enabled=false)
public void testVerbose() throws Exception {
setupAndRunGenericTest("-v");
@@ -45,7 +55,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testRequiredArgs_ShortArgs() throws Exception {
setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", false, null);
new FullVerifications() {
@@ -54,7 +64,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testRequiredArgs_LongArgs() throws Exception {
setupAndRunTest("--input-spec", "swagger.yaml", "--lang", "java", "--output",
"src/main/java", false, null);
@@ -64,7 +74,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testTemplateDir() throws Exception {
final String templateDir = "src/main/resources/customTemplates";
@@ -88,7 +98,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testAuth() throws Exception {
final String auth = "hello:world";
@@ -121,7 +131,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testSystemProperties() throws Exception {
setupAndRunGenericTest("-D", "hello=world,foo=bar");
@@ -200,7 +210,7 @@ public class GenerateTest {
}
@Test
@Test(enabled=false)
public void testConfig() throws Exception {
setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", true,
@@ -220,7 +230,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testSkipOverwrite() throws Exception {
setupAndRunGenericTest("-s");
@@ -240,7 +250,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testApiPackage() throws Exception {
final String value = "io.foo.bar.api";
setupAndRunGenericTest("--api-package", value);
@@ -253,7 +263,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testModelPackage() throws Exception {
final String value = "io.foo.bar.api";
setupAndRunGenericTest("--model-package", value);
@@ -266,7 +276,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testInstantiationTypes() throws Exception {
setupAndRunGenericTest("--instantiation-types", "hello=world,key=,foo=bar,key2");
@@ -301,7 +311,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testTypeMappings() throws Exception {
setupAndRunGenericTest("--type-mappings", "hello=world,key=,foo=bar,key2");
@@ -335,7 +345,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testAdditionalProperties() throws Exception {
setupAndRunGenericTest("--additional-properties", "hello=world,key=,foo=bar,key2");
@@ -369,7 +379,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testLanguageSpecificPrimitives() throws Exception {
setupAndRunGenericTest("--language-specific-primitives", "foo,,bar",
"--language-specific-primitives", "hello,world");
@@ -388,7 +398,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testImportMappings() throws Exception {
setupAndRunGenericTest("--import-mappings", "hello=world,key=,foo=bar,key2");
@@ -422,7 +432,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testInvokerPackage() throws Exception {
final String value = "io.foo.bar.api";
setupAndRunGenericTest("--invoker-package", value);
@@ -435,7 +445,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testGroupId() throws Exception {
final String value = "io.foo.bar.api";
setupAndRunGenericTest("--group-id", value);
@@ -448,7 +458,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testArtifactId() throws Exception {
final String value = "awesome-api";
setupAndRunGenericTest("--artifact-id", value);
@@ -461,7 +471,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testArtifactVersion() throws Exception {
final String value = "1.2.3";
setupAndRunGenericTest("--artifact-version", value);
@@ -474,7 +484,7 @@ public class GenerateTest {
};
}
@Test
@Test(enabled=false)
public void testLibrary() throws Exception {
final String value = "library1";
setupAndRunGenericTest("--library", value);
@@ -552,6 +562,85 @@ public class GenerateTest {
};
}
@Test
public void testExternalArguments() throws Exception {
String content = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("args.json"));
JsonNode node = Json.mapper().readTree(content.getBytes());
Map<String, Object> valueMap = CLIHelper.createOptionValueMap(node);
Assert.assertNotNull(valueMap);
Assert.assertTrue(valueMap.containsKey("lang"));
Assert.assertTrue(valueMap.containsKey("library"));
Assert.assertTrue(valueMap.containsKey("additionalProperties"));
Assert.assertTrue(valueMap.containsKey("spec"));
Assert.assertTrue(valueMap.containsKey("output"));
Assert.assertEquals(valueMap.get("lang"), "java");
Assert.assertEquals(valueMap.get("library"), "jersey2");
Assert.assertNotNull(valueMap.get("additionalProperties"));
Assert.assertTrue(valueMap.get("additionalProperties") instanceof ArrayList);
List<String> properties = (List<String>) valueMap.get("additionalProperties");
Assert.assertEquals(properties.size(), 2);
Assert.assertEquals(properties.get(0), "serializableModel=true");
Assert.assertEquals(properties.get(1), "withXml=true");
content = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("args.yaml"));
node = Yaml.mapper().readTree(content.getBytes());
valueMap = CLIHelper.createOptionValueMap(node);
Assert.assertNotNull(valueMap);
Assert.assertTrue(valueMap.containsKey("lang"));
Assert.assertTrue(valueMap.containsKey("library"));
Assert.assertTrue(valueMap.containsKey("additionalProperties"));
Assert.assertTrue(valueMap.containsKey("spec"));
Assert.assertTrue(valueMap.containsKey("output"));
Assert.assertEquals(valueMap.get("lang"), "java");
Assert.assertEquals(valueMap.get("library"), "jersey2");
Assert.assertNotNull(valueMap.get("additionalProperties"));
Assert.assertTrue(valueMap.get("additionalProperties") instanceof ArrayList);
properties = (List<String>) valueMap.get("additionalProperties");
Assert.assertEquals(properties.size(), 2);
Assert.assertEquals(properties.get(0), "serializableModel=true");
Assert.assertEquals(properties.get(1), "withXml=true");
}
@Test
public void testExternalArgumentsFromFile() throws Exception {
String location = "src/test/resources/args.json";
Generate generate = new Generate();
generate.setUrl(location);
generate.run();
Assert.assertEquals(generate.lang, "java");
Assert.assertEquals(generate.library, "jersey2");
Assert.assertEquals(generate.additionalProperties.size(), 2);
Assert.assertEquals(generate.additionalProperties.get(0), "serializableModel=true");
Assert.assertEquals(generate.additionalProperties.get(1), "withXml=true");
location = "src/test/resources/args.yaml";
generate = new Generate();
generate.setUrl(location);
generate.run();
Assert.assertEquals(generate.lang, "java");
Assert.assertEquals(generate.library, "jersey2");
Assert.assertEquals(generate.additionalProperties.size(), 2);
Assert.assertEquals(generate.additionalProperties.get(0), "serializableModel=true");
Assert.assertEquals(generate.additionalProperties.get(1), "withXml=true");
}
private void setupAndRunGenericTest(String... additionalParameters) {
setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", false, null,
additionalParameters);

View File

@@ -0,0 +1,7 @@
{
"lang":"java",
"library":"jersey2",
"additionalProperties":["serializableModel=true","withXml=true"],
"spec":"/some/place/locally",
"output":"/some/place/locally"
}

View File

@@ -0,0 +1,7 @@
lang: java
library: jersey2
additionalProperties:
- "serializableModel=true"
- "withXml=true"
spec: "/some/place/locally"
output: "/some/place/locally"

View File

@@ -6,7 +6,7 @@
<parent>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-project</artifactId>
<version>2.3.1</version>
<version>3.0.0-rc0</version>
<relativePath>../..</relativePath>
</parent>
<artifactId>swagger-codegen-maven-plugin</artifactId>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-project</artifactId>
<version>2.3.1</version>
<version>3.0.0-rc0</version>
<relativePath>../..</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -74,8 +74,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
@@ -200,19 +200,38 @@
<dependencies>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-parser</artifactId>
<version>${swagger-parser-version}</version>
<scope>compile</scope>
<artifactId>swagger-models</artifactId>
<version>1.5.17</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-compat-spec-parser</artifactId>
<artifactId>swagger-core</artifactId>
<version>1.5.17</version>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-models</artifactId>
<version>${swagger-core-version}</version>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-core</artifactId>
<version>${swagger-core-version}</version>
</dependency>
<dependency>
<groupId>io.swagger.parser.v3</groupId>
<artifactId>swagger-parser-core</artifactId>
<version>${swagger-parser-version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>swagger-core</artifactId>
<version>${swagger-core-version}</version>
<groupId>io.swagger.parser.v3</groupId>
<artifactId>swagger-parser-v3</artifactId>
<version>${swagger-parser-version}</version>
</dependency>
<dependency>
<groupId>io.swagger.parser.v3</groupId>
<artifactId>swagger-parser</artifactId>
<version>${swagger-parser-version}</version>
</dependency>
<dependency>
<groupId>com.samskivert</groupId>
@@ -249,6 +268,11 @@
<artifactId>commons-cli</artifactId>
<version>${commons-cli-version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
@@ -267,6 +291,12 @@
<!-- <version>${jmockit-version}</version> -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
<dependency>
<groupId>com.googlecode.java-diff-utils</groupId>
<artifactId>diffutils</artifactId>
@@ -284,6 +314,11 @@
<version>2.8.47</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.jknack</groupId>
<artifactId>handlebars</artifactId>
<version>4.0.6</version>
</dependency>
</dependencies>
<repositories>

View File

@@ -1,10 +1,7 @@
package io.swagger.codegen;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.StringProperty;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -17,7 +14,7 @@ public class CliOption {
private Map<String, String> enumValues;
public CliOption(String opt, String description) {
this(opt, description, StringProperty.TYPE);
this(opt, description, SchemaTypeUtil.STRING_TYPE);
}
public CliOption(String opt, String description, String type) {
@@ -26,7 +23,6 @@ public class CliOption {
this.type = type;
}
@ApiModelProperty(name = "optionName")
public String getOpt() {
return opt;
}
@@ -39,7 +35,6 @@ public class CliOption {
this.description = description;
}
@ApiModelProperty(value = "Data type is based on the types supported by the JSON-Schema")
public String getType() {
return type;
}
@@ -80,11 +75,11 @@ public class CliOption {
}
public static CliOption newBoolean(String opt, String description) {
return new CliOption(opt, description, BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString());
return new CliOption(opt, description, SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString());
}
public static CliOption newString(String opt, String description) {
return new CliOption(opt, description, StringProperty.TYPE);
return new CliOption(opt, description, SchemaTypeUtil.STRING_TYPE);
}
@JsonIgnore

View File

@@ -1,20 +1,19 @@
package io.swagger.codegen;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.codegen.auth.AuthParser;
import io.swagger.models.Swagger;
import io.swagger.models.auth.AuthorizationValue;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.core.models.AuthorizationValue;
import java.util.List;
public class ClientOptInput {
private CodegenConfig config;
private ClientOpts opts;
private Swagger swagger;
private OpenAPI openAPI;
private List<AuthorizationValue> auths;
public ClientOptInput swagger(Swagger swagger) {
this.setSwagger(swagger);
public ClientOptInput openAPI(OpenAPI openAPI) {
this.setOpenAPI(openAPI);
return this;
}
@@ -65,12 +64,11 @@ public class ClientOptInput {
this.opts = opts;
}
@ApiModelProperty(dataType = "Object")
public Swagger getSwagger() {
return swagger;
public OpenAPI getOpenAPI() {
return openAPI;
}
public void setSwagger(Swagger swagger) {
this.swagger = swagger;
public void setOpenAPI(OpenAPI openAPI) {
this.openAPI = openAPI;
}
}

View File

@@ -6,6 +6,8 @@ import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.OpenAPIV3Parser;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
@@ -16,8 +18,6 @@ import org.slf4j.LoggerFactory;
import config.Config;
import config.ConfigParser;
import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;
/**
* @deprecated use instead {@link io.swagger.codegen.DefaultGenerator}
@@ -51,7 +51,7 @@ public class Codegen extends DefaultGenerator {
ClientOptInput clientOptInput = new ClientOptInput();
ClientOpts clientOpts = new ClientOpts();
Swagger swagger = null;
OpenAPI openAPI = null;
CommandLine cmd = null;
try {
@@ -89,7 +89,7 @@ public class Codegen extends DefaultGenerator {
return;
}
if (cmd.hasOption("i")) {
swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true);
openAPI = new OpenAPIV3Parser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), null);
}
if (cmd.hasOption("c")) {
String configFile = cmd.getOptionValue("c");
@@ -113,7 +113,7 @@ public class Codegen extends DefaultGenerator {
try {
clientOptInput
.opts(clientOpts)
.swagger(swagger);
.openAPI(openAPI);
new Codegen().opts(clientOptInput).generate();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);

View File

@@ -4,13 +4,13 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Helper;
import com.samskivert.mustache.Mustache.Compiler;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.auth.SecuritySchemeDefinition;
import io.swagger.models.properties.Property;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.security.SecurityScheme;
public interface CodegenConfig {
CodegenType getTag();
@@ -65,7 +65,7 @@ public interface CodegenConfig {
String escapeQuotationMark(String input);
String getTypeDeclaration(Property p);
String getTypeDeclaration(Schema schema);
String getTypeDeclaration(String name);
@@ -87,15 +87,15 @@ public interface CodegenConfig {
void setOutputDir(String dir);
CodegenModel fromModel(String name, Model model);
CodegenModel fromModel(String name, Schema schema);
CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions);
CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allDefinitions);
CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger);
CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Schema> definitions, OpenAPI openAPI);
CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Model> definitions);
CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Schema> definitions);
List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes);
List<CodegenSecurity> fromSecurity(Map<String, SecurityScheme> schemes);
Set<String> defaultIncludes();
@@ -121,9 +121,9 @@ public interface CodegenConfig {
Map<String, String> reservedWordsMappings();
void preprocessSwagger(Swagger swagger);
void preprocessOpenAPI(OpenAPI openAPI);
void processSwagger(Swagger swagger);
void processOpenAPI(OpenAPI openAPI);
Compiler processCompiler(Compiler compiler);
@@ -216,4 +216,5 @@ public interface CodegenConfig {
String toGetter(String name);
void addHandlebarHelpers(Handlebars handlebars);
}

View File

@@ -1,5 +1,8 @@
package io.swagger.codegen;
import static io.swagger.codegen.VendorExtendable.PREFIX_HAS;
import static io.swagger.codegen.VendorExtendable.PREFIX_IS;
/**
* A class for storing constants that are used throughout the project.
*/
@@ -222,4 +225,82 @@ public class CodegenConstants {
public static final String REMOVE_OPERATION_ID_PREFIX = "removeOperationIdPrefix";
public static final String REMOVE_OPERATION_ID_PREFIX_DESC = "Remove prefix of operationId, e.g. config_getId => getId";
public static final String IS_ENUM_EXT_NAME = PREFIX_IS + "enum";
public static final String IS_ALIAS_EXT_NAME = PREFIX_IS + "alias";
public static final String IS_ARRAY_MODEL_EXT_NAME = PREFIX_IS + "array-model";
public static final String HAS_VARS_EXT_NAME = PREFIX_HAS + "vars";
public static final String HAS_ENUMS_EXT_NAME = PREFIX_HAS + "enums";
public static final String HAS_MORE_MODELS_EXT_NAME = PREFIX_HAS + "more-models";
public static final String HAS_REQUIRED_EXT_NAME = PREFIX_HAS + "required";
public static final String HAS_OPTIONAL_EXT_NAME = PREFIX_HAS + "optional";
public static final String HAS_CHILDREN_EXT_NAME = PREFIX_HAS + "children";
public static final String HAS_ONLY_READ_ONLY_EXT_NAME = PREFIX_HAS + "only-read-only";
public static final String IS_SIMPLE_TYPE_EXT_NAME = PREFIX_IS + "simple-type";
public static final String IS_PRIMITIVE_TYPE_EXT_NAME = PREFIX_IS + "primitive-type";
public static final String IS_CONTAINER_EXT_NAME = PREFIX_IS + "container";
public static final String IS_NOT_CONTAINER_EXT_NAME = PREFIX_IS + "not-container";
public static final String IS_DEFAULT_EXT_NAME = PREFIX_IS + "default";
public static final String IS_STRING_EXT_NAME = PREFIX_IS + "string";
public static final String IS_NUMERIC_EXT_NAME = PREFIX_IS + "numeric";
public static final String IS_INTEGER_EXT_NAME = PREFIX_IS + "integer";
public static final String IS_LONG_EXT_NAME = PREFIX_IS + "long";
public static final String IS_NUMBER_EXT_NAME = PREFIX_IS + "number";
public static final String IS_FLOAT_EXT_NAME = PREFIX_IS + "float";
public static final String IS_DOUBLE_EXT_NAME = PREFIX_IS + "double";
public static final String IS_BYTE_ARRAY_EXT_NAME = PREFIX_IS + "byte-array";
public static final String IS_BINARY_EXT_NAME = PREFIX_IS + "binary";
public static final String IS_FILE_EXT_NAME = PREFIX_IS + "file";
public static final String IS_BOOLEAN_EXT_NAME = PREFIX_IS + "boolean";
public static final String IS_DATE_EXT_NAME = PREFIX_IS + "date";
public static final String IS_DATE_TIME_EXT_NAME = PREFIX_IS + "date-time";
public static final String IS_UUID_EXT_NAME = PREFIX_IS + "uuid";
public static final String IS_LIST_CONTAINER_EXT_NAME = PREFIX_IS + "list-container";
public static final String IS_MAP_CONTAINER_EXT_NAME = PREFIX_IS + "map-container";
public static final String IS_READ_ONLY_EXT_NAME = PREFIX_IS + "read-only";
public static final String IS_INHERITED_EXT_NAME = PREFIX_IS + "inherited";
public static final String IS_XML_ATTRIBUTE_EXT_NAME = PREFIX_IS + "xml-attribute";
public static final String IS_XML_WRAPPED_EXT_NAME = PREFIX_IS + "xml-wrapped";
public static final String IS_MULTIPART_EXT_NAME = PREFIX_IS + "multipart";
public static final String IS_RESPONSE_BINARY_EXT_NAME = PREFIX_IS + "response-binary";
public static final String IS_RESPONSE_FILE_EXT_NAME = PREFIX_IS + "response-file";
public static final String IS_RESTFUL_INDEX_EXT_NAME = PREFIX_IS + "restful-index";
public static final String IS_RESTFUL_SHOW_EXT_NAME = PREFIX_IS + "restful-show";
public static final String IS_RESTFUL_CREATE_EXT_NAME = PREFIX_IS + "restful-create";
public static final String IS_RESTFUL_UPDATE_EXT_NAME = PREFIX_IS + "restful-update";
public static final String IS_RESTFUL_DESTROY_EXT_NAME = PREFIX_IS + "restful-destroy";
public static final String IS_RESTFUL_EXT_NAME = PREFIX_IS + "restful";
public static final String IS_DEPRECATED_EXT_NAME = PREFIX_IS + "deprecated";
public static final String IS_FORM_PARAM_EXT_NAME = PREFIX_IS + "form-param";
public static final String IS_QUERY_PARAM_EXT_NAME = PREFIX_IS + "query-param";
public static final String IS_PATH_PARAM_EXT_NAME = PREFIX_IS + "path-param";
public static final String IS_HEADER_PARAM_EXT_NAME = PREFIX_IS + "header-param";
public static final String IS_COOKIE_PARAM_EXT_NAME = PREFIX_IS + "cookie-param";
public static final String IS_BODY_PARAM_EXT_NAME = PREFIX_IS + "body-param";
public static final String IS_COLLECTION_FORMAT_MULTI_EXT_NAME = PREFIX_IS + "collection-format-multi";
public static final String IS_BASIC_EXT_NAME = PREFIX_IS + "basic";
public static final String IS_OAUTH_EXT_NAME = PREFIX_IS + "oauth";
public static final String IS_API_KEY_EXT_NAME = PREFIX_IS + "api-key";
public static final String IS_KEY_IN_QUERY_EXT_NAME = PREFIX_IS + "key-in-query";
public static final String IS_KEY_IN_HEADER_EXT_NAME = PREFIX_IS + "key-in-header";
public static final String IS_CODE_EXT_NAME = PREFIX_IS + "code";
public static final String IS_PASSWORD_EXT_NAME = PREFIX_IS + "password";
public static final String IS_APPLICATION_EXT_NAME = PREFIX_IS + "application";
public static final String IS_IMPLICIT_EXT_NAME = PREFIX_IS + "implicit";
public static final String HAS_MORE_EXT_NAME = PREFIX_HAS + "more";
public static final String HAS_MORE_NON_READ_ONLY_EXT_NAME = PREFIX_HAS + "more-non-read-only";
public static final String HAS_VALIDATION_EXT_NAME = PREFIX_HAS + "validation";
public static final String HAS_AUTH_METHODS_EXT_NAME = PREFIX_HAS + "auth-methods";
public static final String HAS_CONSUMES_EXT_NAME = PREFIX_HAS + "consumes";
public static final String HAS_PRODUCES_EXT_NAME = PREFIX_HAS + "produces";
public static final String HAS_PARAMS_EXT_NAME = PREFIX_HAS + "params";
public static final String HAS_OPTIONAL_PARAMS_EXT_NAME = PREFIX_HAS + "optional-params";
public static final String HAS_REQUIRED_PARAMS_EXT_NAME = PREFIX_HAS + "required-params";
public static final String HAS_REFERENCE_EXT_NAME = PREFIX_HAS + "reference";
public static final String HAS_HEADERS_EXT_NAME = PREFIX_HAS + "headers";
}

View File

@@ -0,0 +1,111 @@
package io.swagger.codegen;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class CodegenHelper {
static Set<String> getDefaultIncludes() {
return new HashSet<>(
Arrays.asList("double",
"int",
"long",
"short",
"char",
"float",
"String",
"boolean",
"Boolean",
"Double",
"Void",
"Integer",
"Long",
"Float")
);
}
static Map<String, String> getTypeMappings() {
final Map<String, String> typeMapping = new HashMap<>();
typeMapping.put("array", "List");
typeMapping.put("map", "Map");
typeMapping.put("List", "List");
typeMapping.put("boolean", "Boolean");
typeMapping.put("string", "String");
typeMapping.put("int", "Integer");
typeMapping.put("float", "Float");
typeMapping.put("number", "BigDecimal");
typeMapping.put("DateTime", "Date");
typeMapping.put("long", "Long");
typeMapping.put("short", "Short");
typeMapping.put("char", "String");
typeMapping.put("double", "Double");
typeMapping.put("object", "Object");
typeMapping.put("integer", "Integer");
typeMapping.put("ByteArray", "byte[]");
typeMapping.put("binary", "byte[]");
typeMapping.put("file", "File");
typeMapping.put("UUID", "UUID");
typeMapping.put("BigDecimal", "BigDecimal");
return typeMapping;
}
static Map<String, String> getImportMappings() {
final Map<String, String> importMapping = new HashMap<>();
importMapping.put("BigDecimal", "java.math.BigDecimal");
importMapping.put("UUID", "java.util.UUID");
importMapping.put("File", "java.io.File");
importMapping.put("Date", "java.util.Date");
importMapping.put("Timestamp", "java.sql.Timestamp");
importMapping.put("Map", "java.util.Map");
importMapping.put("HashMap", "java.util.HashMap");
importMapping.put("Array", "java.util.List");
importMapping.put("ArrayList", "java.util.ArrayList");
importMapping.put("List", "java.util.*");
importMapping.put("Set", "java.util.*");
importMapping.put("DateTime", "org.joda.time.*");
importMapping.put("LocalDateTime", "org.joda.time.*");
importMapping.put("LocalDate", "org.joda.time.*");
importMapping.put("LocalTime", "org.joda.time.*");
return importMapping;
}
static void initalizeSpecialCharacterMapping(Map<String, String> specialCharReplacements) {
specialCharReplacements.put("$", "Dollar");
specialCharReplacements.put("^", "Caret");
specialCharReplacements.put("|", "Pipe");
specialCharReplacements.put("=", "Equal");
specialCharReplacements.put("*", "Star");
specialCharReplacements.put("-", "Minus");
specialCharReplacements.put("&", "Ampersand");
specialCharReplacements.put("%", "Percent");
specialCharReplacements.put("#", "Hash");
specialCharReplacements.put("@", "At");
specialCharReplacements.put("!", "Exclamation");
specialCharReplacements.put("+", "Plus");
specialCharReplacements.put(":", "Colon");
specialCharReplacements.put(">", "Greater_Than");
specialCharReplacements.put("<", "Less_Than");
specialCharReplacements.put(".", "Period");
specialCharReplacements.put("_", "Underscore");
specialCharReplacements.put("?", "Question_Mark");
specialCharReplacements.put(",", "Comma");
specialCharReplacements.put("'", "Quote");
specialCharReplacements.put("\"", "Double_Quote");
specialCharReplacements.put("/", "Slash");
specialCharReplacements.put("\\", "Back_Slash");
specialCharReplacements.put("(", "Left_Parenthesis");
specialCharReplacements.put(")", "Right_Parenthesis");
specialCharReplacements.put("{", "Left_Curly_Bracket");
specialCharReplacements.put("}", "Right_Curly_Bracket");
specialCharReplacements.put("[", "Left_Square_Bracket");
specialCharReplacements.put("]", "Right_Square_Bracket");
specialCharReplacements.put("~", "Tilde");
specialCharReplacements.put("`", "Backtick");
specialCharReplacements.put("<=", "Less_Than_Or_Equal_To");
specialCharReplacements.put(">=", "Greater_Than_Or_Equal_To");
specialCharReplacements.put("!=", "Not_Equal");
}
}

View File

@@ -1,15 +1,18 @@
package io.swagger.codegen;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.media.Discriminator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.Objects;
import io.swagger.models.ExternalDocs;
public class CodegenModel implements VendorExtendable {
public class CodegenModel {
public String parent, parentSchema;
public List<String> interfaces;
@@ -21,10 +24,9 @@ public class CodegenModel {
public String name, classname, title, description, classVarName, modelJson, dataType, xmlPrefix, xmlNamespace, xmlName;
public String classFilename; // store the class file name, mainly used for import
public String unescapedDescription;
public String discriminator;
public Discriminator discriminator;
public String defaultValue;
public String arrayModelType;
public boolean isAlias; // Is this effectively an alias of another simple type
public List<CodegenProperty> vars = new ArrayList<CodegenProperty>();
public List<CodegenProperty> requiredVars = new ArrayList<CodegenProperty>(); // a list of required properties
public List<CodegenProperty> optionalVars = new ArrayList<CodegenProperty>(); // a list of optional properties
@@ -39,11 +41,10 @@ public class CodegenModel {
public Set<String> allMandatory;
public Set<String> imports = new TreeSet<String>();
public boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, hasOptional, isArrayModel, hasChildren;
public boolean hasOnlyReadOnly = true; // true if all properties are read-only
public ExternalDocs externalDocs;
public boolean emptyVars;
public ExternalDocumentation externalDocumentation;
public Map<String, Object> vendorExtensions;
public Map<String, Object> vendorExtensions = new HashMap<>();
//The type of the value from additional properties. Used in map like objects.
public String additionalPropertiesType;
@@ -121,22 +122,8 @@ public class CodegenModel {
return false;
if (imports != null ? !imports.equals(that.imports) : that.imports != null)
return false;
if (hasVars != that.hasVars)
return false;
if (emptyVars != that.emptyVars)
return false;
if (hasMoreModels != that.hasMoreModels)
return false;
if (hasEnums != that.hasEnums)
return false;
if (isEnum != that.isEnum)
return false;
if (externalDocs != null ? !externalDocs.equals(that.externalDocs) : that.externalDocs != null)
return false;
if (!Objects.equals(hasOnlyReadOnly, that.hasOnlyReadOnly))
return false;
if (!Objects.equals(hasChildren, that.hasChildren))
return false;
if (!Objects.equals(parentVars, that.parentVars))
return false;
return vendorExtensions != null ? vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions == null;
@@ -172,16 +159,298 @@ public class CodegenModel {
result = 31 * result + (mandatory != null ? mandatory.hashCode() : 0);
result = 31 * result + (allMandatory != null ? allMandatory.hashCode() : 0);
result = 31 * result + (imports != null ? imports.hashCode() : 0);
result = 31 * result + (hasVars ? 13:31);
result = 31 * result + (emptyVars ? 13:31);
result = 31 * result + (hasMoreModels ? 13:31);
result = 31 * result + (hasEnums ? 13:31);
result = 31 * result + (isEnum ? 13:31);
result = 31 * result + (externalDocs != null ? externalDocs.hashCode() : 0);
result = 31 * result + (externalDocumentation != null ? externalDocumentation.hashCode() : 0);
result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0);
result = 31 * result + Objects.hash(hasOnlyReadOnly);
result = 31 * result + Objects.hash(hasChildren);
result = 31 * result + Objects.hash(parentVars);
return result;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public String getParentSchema() {
return parentSchema;
}
public void setParentSchema(String parentSchema) {
this.parentSchema = parentSchema;
}
public List<String> getInterfaces() {
return interfaces;
}
public void setInterfaces(List<String> interfaces) {
this.interfaces = interfaces;
}
public CodegenModel getParentModel() {
return parentModel;
}
public void setParentModel(CodegenModel parentModel) {
this.parentModel = parentModel;
}
public List<CodegenModel> getInterfaceModels() {
return interfaceModels;
}
public void setInterfaceModels(List<CodegenModel> interfaceModels) {
this.interfaceModels = interfaceModels;
}
public List<CodegenModel> getChildren() {
return children;
}
public void setChildren(List<CodegenModel> children) {
this.children = children;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getClassVarName() {
return classVarName;
}
public void setClassVarName(String classVarName) {
this.classVarName = classVarName;
}
public String getModelJson() {
return modelJson;
}
public void setModelJson(String modelJson) {
this.modelJson = modelJson;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getXmlPrefix() {
return xmlPrefix;
}
public void setXmlPrefix(String xmlPrefix) {
this.xmlPrefix = xmlPrefix;
}
public String getXmlNamespace() {
return xmlNamespace;
}
public void setXmlNamespace(String xmlNamespace) {
this.xmlNamespace = xmlNamespace;
}
public String getXmlName() {
return xmlName;
}
public void setXmlName(String xmlName) {
this.xmlName = xmlName;
}
public String getClassFilename() {
return classFilename;
}
public void setClassFilename(String classFilename) {
this.classFilename = classFilename;
}
public String getUnescapedDescription() {
return unescapedDescription;
}
public void setUnescapedDescription(String unescapedDescription) {
this.unescapedDescription = unescapedDescription;
}
public Discriminator getDiscriminator() {
return discriminator;
}
public void setDiscriminator(Discriminator discriminator) {
this.discriminator = discriminator;
}
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public String getArrayModelType() {
return arrayModelType;
}
public void setArrayModelType(String arrayModelType) {
this.arrayModelType = arrayModelType;
}
public List<CodegenProperty> getVars() {
return vars;
}
public void setVars(List<CodegenProperty> vars) {
this.vars = vars;
}
public List<CodegenProperty> getRequiredVars() {
return requiredVars;
}
public void setRequiredVars(List<CodegenProperty> requiredVars) {
this.requiredVars = requiredVars;
}
public List<CodegenProperty> getOptionalVars() {
return optionalVars;
}
public void setOptionalVars(List<CodegenProperty> optionalVars) {
this.optionalVars = optionalVars;
}
public List<CodegenProperty> getReadOnlyVars() {
return readOnlyVars;
}
public void setReadOnlyVars(List<CodegenProperty> readOnlyVars) {
this.readOnlyVars = readOnlyVars;
}
public List<CodegenProperty> getReadWriteVars() {
return readWriteVars;
}
public void setReadWriteVars(List<CodegenProperty> readWriteVars) {
this.readWriteVars = readWriteVars;
}
public List<CodegenProperty> getAllVars() {
return allVars;
}
public void setAllVars(List<CodegenProperty> allVars) {
this.allVars = allVars;
}
public List<CodegenProperty> getParentVars() {
return parentVars;
}
public void setParentVars(List<CodegenProperty> parentVars) {
this.parentVars = parentVars;
}
public Map<String, Object> getAllowableValues() {
return allowableValues;
}
public void setAllowableValues(Map<String, Object> allowableValues) {
this.allowableValues = allowableValues;
}
public Set<String> getMandatory() {
return mandatory;
}
public void setMandatory(Set<String> mandatory) {
this.mandatory = mandatory;
}
public Set<String> getAllMandatory() {
return allMandatory;
}
public void setAllMandatory(Set<String> allMandatory) {
this.allMandatory = allMandatory;
}
public Set<String> getImports() {
return imports;
}
public void setImports(Set<String> imports) {
this.imports = imports;
}
public boolean isEmptyVars() {
return emptyVars;
}
public void setEmptyVars(boolean emptyVars) {
this.emptyVars = emptyVars;
}
public ExternalDocumentation getExternalDocumentation() {
return externalDocumentation;
}
public void setExternalDocumentation(ExternalDocumentation externalDocumentation) {
this.externalDocumentation = externalDocumentation;
}
public Map<String, Object> getVendorExtensions() {
return vendorExtensions;
}
public void setVendorExtensions(Map<String, Object> vendorExtensions) {
this.vendorExtensions = vendorExtensions;
}
public String getAdditionalPropertiesType() {
return additionalPropertiesType;
}
public void setAdditionalPropertiesType(String additionalPropertiesType) {
this.additionalPropertiesType = additionalPropertiesType;
}
}

View File

@@ -1,25 +1,26 @@
package io.swagger.codegen;
import io.swagger.models.ExternalDocs;
import io.swagger.models.Tag;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.media.Discriminator;
import io.swagger.v3.oas.models.parameters.RequestBody;
import io.swagger.v3.oas.models.tags.Tag;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Arrays;
public class CodegenOperation {
public class CodegenOperation implements VendorExtendable {
public final List<CodegenProperty> responseHeaders = new ArrayList<CodegenProperty>();
public boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams, hasRequiredParams,
returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer,
isListContainer, isMultipart, hasMore = true,
isResponseBinary = false, isResponseFile = false, hasReference = false,
isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy,
isRestful, isDeprecated;
public boolean returnTypeIsPrimitive, returnSimpleType, subresourceOperation;
public String path, operationId, returnType, httpMethod, returnBaseType,
returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse, discriminator;
returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse;
public Discriminator discriminator;
public List<Map<String, String>> consumes, produces, prioritizedContentTypes;
public CodegenParameter bodyParam;
public List<CodegenParameter> allParams = new ArrayList<CodegenParameter>();
@@ -35,8 +36,8 @@ public class CodegenOperation {
public Set<String> imports = new HashSet<String>();
public List<Map<String, String>> examples;
public List<Map<String, String>> requestBodyExamples;
public ExternalDocs externalDocs;
public Map<String, Object> vendorExtensions;
public ExternalDocumentation externalDocs;
public Map<String, Object> vendorExtensions = new HashMap<>();
public String nickname; // legacy support
public String operationIdLowerCase; // for markdown documentation
public String operationIdCamelCase; // for class names
@@ -202,38 +203,6 @@ public class CodegenOperation {
if (responseHeaders != null ? !responseHeaders.equals(that.responseHeaders) : that.responseHeaders != null)
return false;
if (hasAuthMethods != that.hasAuthMethods)
return false;
if (hasConsumes != that.hasConsumes)
return false;
if (hasProduces != that.hasProduces)
return false;
if (hasParams != that.hasParams)
return false;
if (hasOptionalParams != that.hasOptionalParams)
return false;
if (returnTypeIsPrimitive != that.returnTypeIsPrimitive)
return false;
if (returnSimpleType != that.returnSimpleType)
return false;
if (subresourceOperation != that.subresourceOperation)
return false;
if (isMapContainer != that.isMapContainer)
return false;
if (isListContainer != that.isListContainer)
return false;
if (isMultipart != that.isMultipart)
return false;
if (hasMore != that.hasMore)
return false;
if (isResponseBinary != that.isResponseBinary)
return false;
if (hasReference != that.hasReference)
return false;
if (isResponseFile != that.isResponseFile)
return false;
if (isDeprecated != that.isDeprecated)
return false;
if (path != null ? !path.equals(that.path) : that.path != null)
return false;
if (operationId != null ? !operationId.equals(that.operationId) : that.operationId != null)
@@ -303,22 +272,6 @@ public class CodegenOperation {
@Override
public int hashCode() {
int result = responseHeaders.hashCode();
result = 31 * result + (hasAuthMethods ? 13:31);
result = 31 * result + (hasConsumes ? 13:31);
result = 31 * result + (hasProduces ? 13:31);
result = 31 * result + (hasParams ? 13:31);
result = 31 * result + (hasOptionalParams ? 13:31);
result = 31 * result + (returnTypeIsPrimitive ? 13:31);
result = 31 * result + (returnSimpleType ? 13:31);
result = 31 * result + (subresourceOperation ? 13:31);
result = 31 * result + (isMapContainer ? 13:31);
result = 31 * result + (isListContainer ? 13:31);
result = 31 * result + (isMultipart ? 13:31);
result = 31 * result + (hasMore ? 13:31);
result = 31 * result + (isResponseBinary ? 13:31);
result = 31 * result + (isResponseFile ? 13:31);
result = 31 * result + (hasReference ? 13:31);
result = 31 * result + (isDeprecated ? 13:31);
result = 31 * result + (path != null ? path.hashCode() : 0);
result = 31 * result + (operationId != null ? operationId.hashCode() : 0);
result = 31 * result + (returnType != null ? returnType.hashCode() : 0);
@@ -353,4 +306,161 @@ public class CodegenOperation {
result = 31 * result + (operationIdCamelCase != null ? operationIdCamelCase.hashCode() : 0);
return result;
}
public List<CodegenProperty> getResponseHeaders() {
return responseHeaders;
}
public String getPath() {
return path;
}
public String getOperationId() {
return operationId;
}
public String getReturnType() {
return returnType;
}
public String getHttpMethod() {
return httpMethod;
}
public String getReturnBaseType() {
return returnBaseType;
}
public String getReturnContainer() {
return returnContainer;
}
public String getSummary() {
return summary;
}
public String getUnescapedNotes() {
return unescapedNotes;
}
public String getNotes() {
return notes;
}
public String getBaseName() {
return baseName;
}
public String getDefaultResponse() {
return defaultResponse;
}
public Discriminator getDiscriminator() {
return discriminator;
}
public List<Map<String, String>> getConsumes() {
return consumes;
}
public List<Map<String, String>> getProduces() {
return produces;
}
public List<Map<String, String>> getPrioritizedContentTypes() {
return prioritizedContentTypes;
}
public CodegenParameter getBodyParam() {
return bodyParam;
}
public List<CodegenParameter> getAllParams() {
return allParams;
}
public List<CodegenParameter> getBodyParams() {
return bodyParams;
}
public List<CodegenParameter> getPathParams() {
return pathParams;
}
public List<CodegenParameter> getQueryParams() {
return queryParams;
}
public List<CodegenParameter> getHeaderParams() {
return headerParams;
}
public List<CodegenParameter> getFormParams() {
return formParams;
}
public boolean getReturnTypeIsPrimitive() {
return returnTypeIsPrimitive;
}
public boolean getReturnSimpleType() {
return returnSimpleType;
}
public boolean getSubresourceOperation() {
return subresourceOperation;
}
public List<CodegenParameter> getRequiredParams() {
return requiredParams;
}
public List<CodegenSecurity> getAuthMethods() {
return authMethods;
}
public List<Tag> getTags() {
return tags;
}
public List<CodegenResponse> getResponses() {
return responses;
}
public Set<String> getImports() {
return imports;
}
public List<Map<String, String>> getExamples() {
return examples;
}
public List<Map<String, String>> getRequestBodyExamples() {
return requestBodyExamples;
}
public ExternalDocumentation getExternalDocs() {
return externalDocs;
}
public String getNickname() {
return nickname;
}
public String getOperationIdLowerCase() {
return operationIdLowerCase;
}
public String getOperationIdCamelCase() {
return operationIdCamelCase;
}
public String getOperationIdSnakeCase() {
return operationIdSnakeCase;
}
@Override
public Map<String, Object> getVendorExtensions() {
return this.vendorExtensions;
}
}

View File

@@ -5,24 +5,17 @@ import java.util.HashMap;
import java.util.Map;
import java.util.List;
public class CodegenParameter {
public boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
isCookieParam, isBodyParam, hasMore, isContainer,
secondaryParam, isCollectionFormatMulti, isPrimitiveType;
public class CodegenParameter implements VendorExtendable {
public boolean secondaryParam, notFile;
public String baseName, paramName, dataType, datatypeWithEnum, dataFormat,
collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName;
public String example; // example value (x-example)
public String jsonSchema;
public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid;
public boolean isListContainer, isMapContainer;
public boolean isFile, notFile;
public boolean isEnum;
public List<String> _enum;
public Map<String, Object> allowableValues;
public CodegenProperty items;
public Map<String, Object> vendorExtensions;
public boolean hasValidation;
public Map<String, Object> vendorExtensions = new HashMap<>();
/**
* Determines whether this parameter is mandatory. If the parameter is in "path",
@@ -78,10 +71,7 @@ public class CodegenParameter {
public CodegenParameter copy() {
CodegenParameter output = new CodegenParameter();
output.isFile = this.isFile;
output.notFile = this.notFile;
output.hasMore = this.hasMore;
output.isContainer = this.isContainer;
output.secondaryParam = this.secondaryParam;
output.baseName = this.baseName;
output.paramName = this.paramName;
@@ -90,17 +80,9 @@ public class CodegenParameter {
output.enumName = this.enumName;
output.dataFormat = this.dataFormat;
output.collectionFormat = this.collectionFormat;
output.isCollectionFormatMulti = this.isCollectionFormatMulti;
output.isPrimitiveType = this.isPrimitiveType;
output.description = this.description;
output.unescapedDescription = this.unescapedDescription;
output.baseType = this.baseType;
output.isFormParam = this.isFormParam;
output.isQueryParam = this.isQueryParam;
output.isPathParam = this.isPathParam;
output.isHeaderParam = this.isHeaderParam;
output.isCookieParam = this.isCookieParam;
output.isBodyParam = this.isBodyParam;
output.required = this.required;
output.maximum = this.maximum;
output.exclusiveMaximum = this.exclusiveMaximum;
@@ -116,7 +98,6 @@ public class CodegenParameter {
output.jsonSchema = this.jsonSchema;
output.defaultValue = this.defaultValue;
output.example = this.example;
output.isEnum = this.isEnum;
if (this._enum != null) {
output._enum = new ArrayList<String>(this._enum);
}
@@ -129,22 +110,6 @@ public class CodegenParameter {
if(this.vendorExtensions != null){
output.vendorExtensions = new HashMap<String, Object>(this.vendorExtensions);
}
output.hasValidation = this.hasValidation;
output.isBinary = this.isBinary;
output.isByteArray = this.isByteArray;
output.isString = this.isString;
output.isNumeric = this.isNumeric;
output.isInteger = this.isInteger;
output.isLong = this.isLong;
output.isDouble = this.isDouble;
output.isFloat = this.isFloat;
output.isNumber = this.isNumber;
output.isBoolean = this.isBoolean;
output.isDate = this.isDate;
output.isDateTime = this.isDateTime;
output.isUuid = this.isUuid;
output.isListContainer = this.isListContainer;
output.isMapContainer = this.isMapContainer;
return output;
}
@@ -161,29 +126,8 @@ public class CodegenParameter {
CodegenParameter that = (CodegenParameter) o;
if (isEnum != that.isEnum) return false;
if (isFormParam != that.isFormParam)
return false;
if (isQueryParam != that.isQueryParam)
return false;
if (isPathParam != that.isPathParam)
return false;
if (isHeaderParam != that.isHeaderParam)
return false;
if (isCookieParam != that.isCookieParam)
return false;
if (isBodyParam != that.isBodyParam)
return false;
if (hasMore != that.hasMore)
return false;
if (isContainer != that.isContainer)
return false;
if (secondaryParam != that.secondaryParam)
return false;
if (isCollectionFormatMulti != that.isCollectionFormatMulti)
return false;
if (isPrimitiveType != that.isPrimitiveType)
return false;
if (baseName != null ? !baseName.equals(that.baseName) : that.baseName != null)
return false;
if (paramName != null ? !paramName.equals(that.paramName) : that.paramName != null)
@@ -210,38 +154,6 @@ public class CodegenParameter {
return false;
if (jsonSchema != null ? !jsonSchema.equals(that.jsonSchema) : that.jsonSchema != null)
return false;
if (isString != that.isString)
return false;
if (isNumeric != that.isNumeric)
return false;
if (isInteger != that.isInteger)
return false;
if (isLong != that.isLong)
return false;
if (isNumber != that.isNumber)
return false;
if (isFloat != that.isFloat)
return false;
if (isDouble != that.isDouble)
return false;
if (isByteArray != that.isByteArray)
return false;
if (isBinary != that.isBinary)
return false;
if (isBoolean != that.isBoolean)
return false;
if (isDate != that.isDate)
return false;
if (isDateTime != that.isDateTime)
return false;
if (isUuid != that.isUuid)
return false;
if (isListContainer != that.isListContainer)
return false;
if (isMapContainer != that.isMapContainer)
return false;
if (isFile != that.isFile)
return false;
if (notFile != that.notFile)
return false;
if (_enum != null ? !_enum.equals(that._enum) : that._enum != null)
@@ -252,8 +164,6 @@ public class CodegenParameter {
return false;
if (vendorExtensions != null ? !vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions != null)
return false;
if (hasValidation != that.hasValidation)
return false;
if (required != that.required)
return false;
if (maximum != null ? !maximum.equals(that.maximum) : that.maximum != null)
@@ -282,17 +192,7 @@ public class CodegenParameter {
@Override
public int hashCode() {
int result = isFormParam ? 13:31;
result = 31 * result + (isQueryParam ? 13:31);
result = 31 * result + (isPathParam ? 13:31);
result = 31 * result + (isHeaderParam ? 13:31);
result = 31 * result + (isCookieParam ? 13:31);
result = 31 * result + (isBodyParam ? 13:31);
result = 31 * result + (hasMore ? 13:31);
result = 31 * result + (isContainer ? 13:31);
result = 31 * result + (secondaryParam ? 13:31);
result = 31 * result + (isCollectionFormatMulti ? 13:31);
result = 31 * result + (isPrimitiveType ? 13:31);
int result = secondaryParam ? 13:31;
result = 31 * result + (baseName != null ? baseName.hashCode() : 0);
result = 31 * result + (paramName != null ? paramName.hashCode() : 0);
result = 31 * result + (dataType != null ? dataType.hashCode() : 0);
@@ -306,29 +206,11 @@ public class CodegenParameter {
result = 31 * result + (defaultValue != null ? defaultValue.hashCode() : 0);
result = 31 * result + (example != null ? example.hashCode() : 0);
result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0);
result = 31 * result + (isString ? 13:31);
result = 31 * result + (isNumeric ? 13:31);
result = 31 * result + (isInteger ? 13:31);
result = 31 * result + (isLong ? 13:31);
result = 31 * result + (isFloat ? 13:31);
result = 31 * result + (isNumber ? 13:31);
result = 31 * result + (isDouble ? 13:31);
result = 31 * result + (isByteArray ? 13:31);
result = 31 * result + (isBinary ? 13:31);
result = 31 * result + (isBoolean ? 13:31);
result = 31 * result + (isDate ? 13:31);
result = 31 * result + (isDateTime ? 13:31);
result = 31 * result + (isUuid ? 13:31);
result = 31 * result + (isListContainer ? 13:31);
result = 31 * result + (isMapContainer ? 13:31);
result = 31 * result + (isFile ? 13:31);
result = 31 * result + (notFile ? 13:31);
result = 31 * result + (isEnum ? 1 : 0);
result = 31 * result + (_enum != null ? _enum.hashCode() : 0);
result = 31 * result + (allowableValues != null ? allowableValues.hashCode() : 0);
result = 31 * result + (items != null ? items.hashCode() : 0);
result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0);
result = 31 * result + (hasValidation ? 13:31);
result = 31 * result + (required ? 13:31);
result = 31 * result + (maximum != null ? maximum.hashCode() : 0);
result = 31 * result + (exclusiveMaximum ? 13:31);
@@ -343,5 +225,129 @@ public class CodegenParameter {
result = 31 * result + (multipleOf != null ? multipleOf.hashCode() : 0);
return result;
}
public boolean getSecondaryParam() {
return secondaryParam;
}
public String getBaseName() {
return baseName;
}
public String getParamName() {
return paramName;
}
public String getDataType() {
return dataType;
}
public String getDatatypeWithEnum() {
return datatypeWithEnum;
}
public String getDataFormat() {
return dataFormat;
}
public String getCollectionFormat() {
return collectionFormat;
}
public String getDescription() {
return description;
}
public String getUnescapedDescription() {
return unescapedDescription;
}
public String getBaseType() {
return baseType;
}
public String getDefaultValue() {
return defaultValue;
}
public String getEnumName() {
return enumName;
}
public String getExample() {
return example;
}
public String getJsonSchema() {
return jsonSchema;
}
public boolean getIsNotFile() {
return notFile;
}
public List<String> get_enum() {
return _enum;
}
public Map<String, Object> getAllowableValues() {
return allowableValues;
}
public CodegenProperty getItems() {
return items;
}
public Map<String, Object> getVendorExtensions() {
return vendorExtensions;
}
public boolean getRequired() {
return required;
}
public String getMaximum() {
return maximum;
}
public boolean getExclusiveMaximum() {
return exclusiveMaximum;
}
public String getMinimum() {
return minimum;
}
public boolean getExclusiveMinimum() {
return exclusiveMinimum;
}
public Integer getMaxLength() {
return maxLength;
}
public Integer getMinLength() {
return minLength;
}
public String getPattern() {
return pattern;
}
public Integer getMaxItems() {
return maxItems;
}
public Integer getMinItems() {
return minItems;
}
public boolean getUniqueItems() {
return uniqueItems;
}
public Number getMultipleOf() {
return multipleOf;
}
}

View File

@@ -6,7 +6,7 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
public class CodegenProperty implements Cloneable {
public class CodegenProperty implements Cloneable, VendorExtendable {
public String baseName, complexType, getter, setter, description, datatype,
datatypeWithEnum, dataFormat, name, min, max, defaultValue, defaultValueWithParam,
baseType, containerType, title;
@@ -36,33 +36,337 @@ public class CodegenProperty implements Cloneable {
public String maximum;
public boolean exclusiveMinimum;
public boolean exclusiveMaximum;
public boolean hasMore, required, secondaryParam;
public boolean hasMoreNonReadOnly; // for model constructor, true if next properyt is not readonly
public boolean isPrimitiveType, isContainer, isNotContainer;
public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBinary, isFile, isBoolean, isDate, isDateTime, isUuid;
public boolean isListContainer, isMapContainer;
public boolean isEnum;
public boolean isReadOnly = false;
public boolean required, secondaryParam;
public List<String> _enum;
public Map<String, Object> allowableValues;
public CodegenProperty items;
public Map<String, Object> vendorExtensions;
public boolean hasValidation; // true if pattern, maximum, etc are set (only used in the mustache template)
public boolean isInherited;
public Map<String, Object> vendorExtensions = new HashMap<>();
public String discriminatorValue;
public String nameInCamelCase; // property name in camel case
// enum name based on the property name, usually use as a prefix (e.g. VAR_NAME) for enum name (e.g. VAR_NAME_VALUE1)
public String enumName;
public Integer maxItems;
public Integer minItems;
// XML
public boolean isXmlAttribute = false;
public String xmlPrefix;
public String xmlName;
public String xmlNamespace;
public boolean isXmlWrapped = false;
public String getBaseName() {
return baseName;
}
public void setBaseName(String baseName) {
this.baseName = baseName;
}
public String getComplexType() {
return complexType;
}
public void setComplexType(String complexType) {
this.complexType = complexType;
}
public String getGetter() {
return getter;
}
public void setGetter(String getter) {
this.getter = getter;
}
public String getSetter() {
return setter;
}
public void setSetter(String setter) {
this.setter = setter;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDatatype() {
return datatype;
}
public void setDatatype(String datatype) {
this.datatype = datatype;
}
public String getDatatypeWithEnum() {
return datatypeWithEnum;
}
public void setDatatypeWithEnum(String datatypeWithEnum) {
this.datatypeWithEnum = datatypeWithEnum;
}
public String getDataFormat() {
return dataFormat;
}
public void setDataFormat(String dataFormat) {
this.dataFormat = dataFormat;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMin() {
return min;
}
public void setMin(String min) {
this.min = min;
}
public String getMax() {
return max;
}
public void setMax(String max) {
this.max = max;
}
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public String getDefaultValueWithParam() {
return defaultValueWithParam;
}
public void setDefaultValueWithParam(String defaultValueWithParam) {
this.defaultValueWithParam = defaultValueWithParam;
}
public String getBaseType() {
return baseType;
}
public void setBaseType(String baseType) {
this.baseType = baseType;
}
public String getContainerType() {
return containerType;
}
public void setContainerType(String containerType) {
this.containerType = containerType;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUnescapedDescription() {
return unescapedDescription;
}
public void setUnescapedDescription(String unescapedDescription) {
this.unescapedDescription = unescapedDescription;
}
public Integer getMaxLength() {
return maxLength;
}
public void setMaxLength(Integer maxLength) {
this.maxLength = maxLength;
}
public Integer getMinLength() {
return minLength;
}
public void setMinLength(Integer minLength) {
this.minLength = minLength;
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getJsonSchema() {
return jsonSchema;
}
public void setJsonSchema(String jsonSchema) {
this.jsonSchema = jsonSchema;
}
public String getMinimum() {
return minimum;
}
public void setMinimum(String minimum) {
this.minimum = minimum;
}
public String getMaximum() {
return maximum;
}
public void setMaximum(String maximum) {
this.maximum = maximum;
}
public boolean getExclusiveMinimum() {
return exclusiveMinimum;
}
public void setExclusiveMinimum(boolean exclusiveMinimum) {
this.exclusiveMinimum = exclusiveMinimum;
}
public boolean getIExclusiveMaximum() {
return exclusiveMaximum;
}
public void setExclusiveMaximum(boolean exclusiveMaximum) {
this.exclusiveMaximum = exclusiveMaximum;
}
public boolean getRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public boolean getSecondaryParam() {
return secondaryParam;
}
public void setSecondaryParam(boolean secondaryParam) {
this.secondaryParam = secondaryParam;
}
public List<String> get_enum() {
return _enum;
}
public void set_enum(List<String> _enum) {
this._enum = _enum;
}
public Map<String, Object> getAllowableValues() {
return allowableValues;
}
public void setAllowableValues(Map<String, Object> allowableValues) {
this.allowableValues = allowableValues;
}
public CodegenProperty getItems() {
return items;
}
public void setItems(CodegenProperty items) {
this.items = items;
}
public Map<String, Object> getVendorExtensions() {
return vendorExtensions;
}
public void setVendorExtensions(Map<String, Object> vendorExtensions) {
this.vendorExtensions = vendorExtensions;
}
public String getNameInCamelCase() {
return nameInCamelCase;
}
public void setNameInCamelCase(String nameInCamelCase) {
this.nameInCamelCase = nameInCamelCase;
}
public String getEnumName() {
return enumName;
}
public void setEnumName(String enumName) {
this.enumName = enumName;
}
public Integer getMaxItems() {
return maxItems;
}
public void setMaxItems(Integer maxItems) {
this.maxItems = maxItems;
}
public Integer getMinItems() {
return minItems;
}
public void setMinItems(Integer minItems) {
this.minItems = minItems;
}
public String getXmlPrefix() {
return xmlPrefix;
}
public void setXmlPrefix(String xmlPrefix) {
this.xmlPrefix = xmlPrefix;
}
public String getXmlName() {
return xmlName;
}
public void setXmlName(String xmlName) {
this.xmlName = xmlName;
}
public String getXmlNamespace() {
return xmlNamespace;
}
public void setXmlNamespace(String xmlNamespace) {
this.xmlNamespace = xmlNamespace;
}
@Override
public String toString() {
@@ -92,13 +396,6 @@ public class CodegenProperty implements Cloneable {
result = prime * result + (exclusiveMaximum ? 13:31);
result = prime * result + (exclusiveMinimum ? 13:31);
result = prime * result + ((getter == null) ? 0 : getter.hashCode());
result = prime * result + (hasMore ? 13:31);
result = prime * result + ((hasMoreNonReadOnly ? 13:31));
result = prime * result + ((isContainer ? 13:31));
result = prime * result + (isEnum ? 1231 : 1237);
result = prime * result + ((isNotContainer ? 13:31));
result = prime * result + ((isPrimitiveType ? 13:31));
result = prime * result + ((isReadOnly ? 13:31));
result = prime * result + ((items == null) ? 0 : items.hashCode());
result = prime * result + ((jsonSchema == null) ? 0 : jsonSchema.hashCode());
result = prime * result + ((max == null) ? 0 : max.hashCode());
@@ -114,34 +411,13 @@ public class CodegenProperty implements Cloneable {
result = prime * result + ((setter == null) ? 0 : setter.hashCode());
result = prime * result + ((unescapedDescription == null) ? 0 : unescapedDescription.hashCode());
result = prime * result + ((vendorExtensions == null) ? 0 : vendorExtensions.hashCode());
result = prime * result + ((hasValidation ? 13:31));
result = prime * result + ((isString ? 13:31));
result = prime * result + ((isNumeric ? 13:31));
result = prime * result + ((isInteger ? 13:31));
result = prime * result + ((isLong ?13:31));
result = prime * result + ((isNumber ? 13:31));
result = prime * result + ((isFloat ? 13:31));
result = prime * result + ((isDouble ? 13:31));
result = prime * result + ((isByteArray ? 13:31));
result = prime * result + ((isBinary ? 13:31));
result = prime * result + ((isFile ? 13:31));
result = prime * result + ((isBoolean ? 13:31));
result = prime * result + ((isDate ? 13:31));
result = prime * result + ((isDateTime ? 13:31));
result = prime * result + ((isUuid ? 13:31));
result = prime * result + ((isMapContainer ? 13:31));
result = prime * result + ((isListContainer ? 13:31));
result = prime * result + Objects.hashCode(isInherited);
result = prime * result + Objects.hashCode(discriminatorValue);
result = prime * result + Objects.hashCode(nameInCamelCase);
result = prime * result + Objects.hashCode(enumName);
result = prime * result + ((maxItems == null) ? 0 : maxItems.hashCode());
result = prime * result + ((minItems == null) ? 0 : minItems.hashCode());
result = prime * result + ((isXmlAttribute ? 13:31));
result = prime * result + ((xmlPrefix == null) ? 0 : xmlPrefix.hashCode());
result = prime * result + ((xmlName == null) ? 0 : xmlName.hashCode());
result = prime * result + ((xmlNamespace == null) ? 0 : xmlNamespace.hashCode());
result = prime * result + ((isXmlWrapped ? 13:31));
return result;
}
@@ -232,21 +508,6 @@ public class CodegenProperty implements Cloneable {
if (this.secondaryParam != other.secondaryParam) {
return false;
}
if (this.isPrimitiveType != other.isPrimitiveType) {
return false;
}
if (this.isContainer != other.isContainer) {
return false;
}
if (this.isNotContainer != other.isNotContainer) {
return false;
}
if (this.isEnum != other.isEnum) {
return false;
}
if (this.isReadOnly != other.isReadOnly) {
return false;
}
if (this._enum != other._enum && (this._enum == null || !this._enum.equals(other._enum))) {
return false;
}
@@ -257,66 +518,6 @@ public class CodegenProperty implements Cloneable {
if (this.vendorExtensions != other.vendorExtensions && (this.vendorExtensions == null || !this.vendorExtensions.equals(other.vendorExtensions))) {
return false;
}
if (this.hasValidation != other.hasValidation) {
return false;
}
if (this.isString != other.isString) {
return false;
}
if (this.isNumeric != other.isNumeric) {
return false;
}
if (this.isInteger != other.isInteger) {
return false;
}
if (this.isLong != other.isLong) {
return false;
}
if (this.isNumber != other.isNumber) {
return false;
}
if (this.isFloat != other.isFloat) {
return false;
}
if (this.isDouble != other.isDouble) {
return false;
}
if (this.isByteArray != other.isByteArray) {
return false;
}
if (this.isBoolean != other.isBoolean) {
return false;
}
if (this.isDate != other.isDate) {
return false;
}
if (this.isDateTime != other.isDateTime) {
return false;
}
if (this.isUuid != other.isUuid) {
return false;
}
if (this.isBinary != other.isBinary) {
return false;
}
if (this.isFile != other.isFile) {
return false;
}
if (this.isListContainer != other.isListContainer) {
return false;
}
if (this.isMapContainer != other.isMapContainer) {
return false;
}
if (!Objects.equals(this.isInherited, other.isInherited)) {
return false;
}
if (!Objects.equals(this.discriminatorValue, other.discriminatorValue)) {
return false;
}
if (!Objects.equals(this.nameInCamelCase, other.nameInCamelCase)) {
return false;
}
@@ -329,9 +530,6 @@ public class CodegenProperty implements Cloneable {
if (this.minItems != other.minItems && (this.minItems == null || !this.minItems.equals(other.minItems))) {
return false;
}
if (!Objects.equals(this.isXmlAttribute, other.isXmlAttribute)) {
return false;
}
if (!Objects.equals(this.xmlPrefix, other.xmlPrefix)) {
return false;
}
@@ -341,9 +539,6 @@ public class CodegenProperty implements Cloneable {
if (!Objects.equals(this.xmlNamespace, other.xmlNamespace)) {
return false;
}
if (!Objects.equals(this.isXmlWrapped, other.isXmlWrapped)) {
return false;
}
return true;
}

View File

@@ -1,27 +1,18 @@
package io.swagger.codegen;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CodegenResponse {
public class CodegenResponse implements VendorExtendable {
public final List<CodegenProperty> headers = new ArrayList<CodegenProperty>();
public String code, message;
public boolean hasMore;
public List<Map<String, Object>> examples;
public String dataType, baseType, containerType;
public boolean hasHeaders;
public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBoolean, isDate, isDateTime, isUuid;
public boolean isDefault;
public boolean simpleType;
public boolean primitiveType;
public boolean isMapContainer;
public boolean isListContainer;
public boolean isBinary = false;
public boolean isFile = false;
public Object schema;
public String jsonSchema;
public Map<String, Object> vendorExtensions;
public Map<String, Object> vendorExtensions = new HashMap<>();
public boolean isWildcard() {
return "0".equals(code) || "default".equals(code);
@@ -45,8 +36,6 @@ public class CodegenResponse {
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (hasMore != that.hasMore)
return false;
if (examples != null ? !examples.equals(that.examples) : that.examples != null)
return false;
if (dataType != null ? !dataType.equals(that.dataType) : that.dataType != null)
@@ -55,22 +44,6 @@ public class CodegenResponse {
return false;
if (containerType != null ? !containerType.equals(that.containerType) : that.containerType != null)
return false;
if (isDefault != that.isDefault)
return false;
if (simpleType != that.simpleType)
return false;
if (primitiveType != that.primitiveType)
return false;
if (isMapContainer != that.isMapContainer)
return false;
if (isListContainer != that.isListContainer)
return false;
if (isBinary != that.isBinary)
return false;
if (isFile != that.isFile)
return false;
if (isNumeric != that.isNumeric)
return false;
if (schema != null ? !schema.equals(that.schema) : that.schema != null)
return false;
if (vendorExtensions != null ? !vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions != null)
@@ -83,22 +56,54 @@ public class CodegenResponse {
int result = headers.hashCode();
result = 31 * result + (code != null ? code.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + (hasMore ? 13:31);
result = 31 * result + (examples != null ? examples.hashCode() : 0);
result = 31 * result + (dataType != null ? dataType.hashCode() : 0);
result = 31 * result + (baseType != null ? baseType.hashCode() : 0);
result = 31 * result + (containerType != null ? containerType.hashCode() : 0);
result = 31 * result + (isDefault ? 13:31);
result = 31 * result + (isNumeric ? 13:31);
result = 31 * result + (simpleType ? 13:31);
result = 31 * result + (primitiveType ? 13:31);
result = 31 * result + (isMapContainer ? 13:31);
result = 31 * result + (isListContainer ? 13:31);
result = 31 * result + (isBinary ? 13:31);
result = 31 * result + (isFile ? 13:31);
result = 31 * result + (schema != null ? schema.hashCode() : 0);
result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0);
result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0);
return result;
}
public List<CodegenProperty> getHeaders() {
return headers;
}
public String getCode() {
return code;
}
public String getMessage() {
return message;
}
public List<Map<String, Object>> getExamples() {
return examples;
}
public String getDataType() {
return dataType;
}
public String getBaseType() {
return baseType;
}
public String getContainerType() {
return containerType;
}
public Object getSchema() {
return schema;
}
public String getJsonSchema() {
return jsonSchema;
}
@Override
public Map<String, Object> getVendorExtensions() {
return this.vendorExtensions;
}
}

View File

@@ -1,19 +1,20 @@
package io.swagger.codegen;
import io.swagger.v3.oas.models.security.Scopes;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CodegenSecurity {
public class CodegenSecurity implements VendorExtendable {
public String name;
public String type;
public Boolean hasMore, isBasic, isOAuth, isApiKey;
// ApiKey specific
public String keyParamName;
public Boolean isKeyInQuery, isKeyInHeader;
// Oauth specific
public String flow, authorizationUrl, tokenUrl;
public List<Map<String, Object>> scopes;
public Boolean isCode, isPassword, isApplication, isImplicit;
public Scopes scopes;
public Map<String, Object> vendorExtensions = new HashMap<>();
@Override
public String toString() {
@@ -31,34 +32,14 @@ public class CodegenSecurity {
return false;
if (type != null ? !type.equals(that.type) : that.type != null)
return false;
if (hasMore != null ? !hasMore.equals(that.hasMore) : that.hasMore != null)
return false;
if (isBasic != null ? !isBasic.equals(that.isBasic) : that.isBasic != null)
return false;
if (isOAuth != null ? !isOAuth.equals(that.isOAuth) : that.isOAuth != null)
return false;
if (isApiKey != null ? !isApiKey.equals(that.isApiKey) : that.isApiKey != null)
return false;
if (keyParamName != null ? !keyParamName.equals(that.keyParamName) : that.keyParamName != null)
return false;
if (isKeyInQuery != null ? !isKeyInQuery.equals(that.isKeyInQuery) : that.isKeyInQuery != null)
return false;
if (isKeyInHeader != null ? !isKeyInHeader.equals(that.isKeyInHeader) : that.isKeyInHeader != null)
return false;
if (flow != null ? !flow.equals(that.flow) : that.flow != null)
return false;
if (authorizationUrl != null ? !authorizationUrl.equals(that.authorizationUrl) : that.authorizationUrl != null)
return false;
if (tokenUrl != null ? !tokenUrl.equals(that.tokenUrl) : that.tokenUrl != null)
return false;
if (isCode != null ? !isCode.equals(that.isCode) : that.isCode != null)
return false;
if (isPassword != null ? !isPassword.equals(that.isPassword) : that.isPassword != null)
return false;
if (isApplication != null ? !isApplication.equals(that.isApplication) : that.isApplication != null)
return false;
if (isImplicit != null ? !isImplicit.equals(that.isImplicit) : that.isImplicit != null)
return false;
return scopes != null ? scopes.equals(that.scopes) : that.scopes == null;
}
@@ -67,21 +48,44 @@ public class CodegenSecurity {
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (hasMore != null ? hasMore.hashCode() : 0);
result = 31 * result + (isBasic != null ? isBasic.hashCode() : 0);
result = 31 * result + (isOAuth != null ? isOAuth.hashCode() : 0);
result = 31 * result + (isApiKey != null ? isApiKey.hashCode() : 0);
result = 31 * result + (keyParamName != null ? keyParamName.hashCode() : 0);
result = 31 * result + (isKeyInQuery != null ? isKeyInQuery.hashCode() : 0);
result = 31 * result + (isKeyInHeader != null ? isKeyInHeader.hashCode() : 0);
result = 31 * result + (flow != null ? flow.hashCode() : 0);
result = 31 * result + (authorizationUrl != null ? authorizationUrl.hashCode() : 0);
result = 31 * result + (tokenUrl != null ? tokenUrl.hashCode() : 0);
result = 31 * result + (isCode != null ? isCode.hashCode() : 0);
result = 31 * result + (isPassword != null ? isPassword.hashCode() : 0);
result = 31 * result + (isApplication != null ? isApplication.hashCode() : 0);
result = 31 * result + (isImplicit != null ? isImplicit.hashCode() : 0);
result = 31 * result + (scopes != null ? scopes.hashCode() : 0);
return result;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public String getKeyParamName() {
return keyParamName;
}
public String getFlow() {
return flow;
}
public String getAuthorizationUrl() {
return authorizationUrl;
}
public String getTokenUrl() {
return tokenUrl;
}
public Scopes getScopes() {
return scopes;
}
@Override
public Map<String, Object> getVendorExtensions() {
return this.vendorExtensions;
}
}

View File

@@ -1,30 +1,80 @@
package io.swagger.codegen;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.codegen.ignore.CodegenIgnoreProcessor;
import io.swagger.codegen.languages.AbstractJavaCodegen;
import io.swagger.codegen.utils.ImplementationVersion;
import io.swagger.models.*;
import io.swagger.models.auth.OAuth2Definition;
import io.swagger.models.auth.SecuritySchemeDefinition;
import io.swagger.models.parameters.Parameter;
import io.swagger.util.Json;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Helper;
import com.github.jknack.handlebars.Options;
import com.github.jknack.handlebars.io.AbstractTemplateLoader;
import com.github.jknack.handlebars.io.AbstractTemplateSource;
import com.github.jknack.handlebars.io.ClassPathTemplateLoader;
import com.github.jknack.handlebars.io.FileTemplateLoader;
import com.github.jknack.handlebars.io.StringTemplateSource;
import com.github.jknack.handlebars.io.TemplateLoader;
import com.github.jknack.handlebars.io.TemplateSource;
import io.swagger.codegen.languages.helpers.ExtensionHelper;
import io.swagger.codegen.languages.helpers.NoneExtensionHelper;
import io.swagger.codegen.utils.URLPathUtil;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.Paths;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.security.OAuthFlow;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.oas.models.tags.Tag;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.*;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.codegen.ignore.CodegenIgnoreProcessor;
//import io.swagger.codegen.languages.AbstractJavaCodegen;
import io.swagger.codegen.utils.ImplementationVersion;
import static com.google.common.base.Objects.equal;
public class DefaultGenerator extends AbstractGenerator implements Generator {
protected final Logger LOGGER = LoggerFactory.getLogger(DefaultGenerator.class);
protected CodegenConfig config;
protected ClientOptInput opts;
protected Swagger swagger;
protected OpenAPI openAPI;
protected CodegenIgnoreProcessor ignoreProcessor;
private Boolean generateApis = null;
private Boolean generateModels = null;
@@ -42,21 +92,21 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
@Override
public Generator opts(ClientOptInput opts) {
this.opts = opts;
this.swagger = opts.getSwagger();
this.openAPI = opts.getOpenAPI();
this.config = opts.getConfig();
this.config.additionalProperties().putAll(opts.getOpts().getProperties());
String ignoreFileLocation = this.config.getIgnoreFilePathOverride();
if (ignoreFileLocation != null) {
if(ignoreFileLocation != null) {
final File ignoreFile = new File(ignoreFileLocation);
if (ignoreFile.exists() && ignoreFile.canRead()) {
if(ignoreFile.exists() && ignoreFile.canRead()) {
this.ignoreProcessor = new CodegenIgnoreProcessor(ignoreFile);
} else {
LOGGER.warn("Ignore file specified at {} is not valid. This will fall back to an existing ignore file if present in the output directory.", ignoreFileLocation);
}
}
if (this.ignoreProcessor == null) {
if(this.ignoreProcessor == null) {
this.ignoreProcessor = new CodegenIgnoreProcessor(this.config.getOutputDir());
}
@@ -96,31 +146,14 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
private String getScheme() {
String scheme;
if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) {
scheme = config.escapeText(swagger.getSchemes().get(0).toValue());
} else {
String scheme = URLPathUtil.getScheme(this.openAPI, this.config);
if (StringUtils.isBlank(scheme)) {
scheme = "https";
}
scheme = config.escapeText(scheme);
return scheme;
}
private String getHost() {
StringBuilder hostBuilder = new StringBuilder();
hostBuilder.append(getScheme());
hostBuilder.append("://");
if (!StringUtils.isEmpty(swagger.getHost())) {
hostBuilder.append(swagger.getHost());
} else {
hostBuilder.append("localhost");
}
if (!StringUtils.isEmpty(swagger.getBasePath()) && !swagger.getBasePath().equals("/")) {
hostBuilder.append(swagger.getBasePath());
}
return hostBuilder.toString();
}
private void configureGeneratorProperties() {
// allows generating only models by specifying a CSV of models to generate, or empty for all
// NOTE: Boolean.TRUE is required below rather than `true` because of JVM boxing constraints and type inference.
@@ -132,13 +165,13 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
// no specifics are set, generate everything
generateApis = generateModels = generateSupportingFiles = true;
} else {
if (generateApis == null) {
if(generateApis == null) {
generateApis = false;
}
if (generateModels == null) {
if(generateModels == null) {
generateModels = false;
}
if (generateSupportingFiles == null) {
if(generateSupportingFiles == null) {
generateSupportingFiles = false;
}
}
@@ -149,7 +182,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
generateApiTests = System.getProperty(CodegenConstants.API_TESTS) != null ? Boolean.valueOf(System.getProperty(CodegenConstants.API_TESTS)) : getGeneratorPropertyDefaultSwitch(CodegenConstants.API_TESTS, true);
generateApiDocumentation = System.getProperty(CodegenConstants.API_DOCS) != null ? Boolean.valueOf(System.getProperty(CodegenConstants.API_DOCS)) : getGeneratorPropertyDefaultSwitch(CodegenConstants.API_DOCS, true);
// Additional properties added for tests to exclude references in project related files
config.additionalProperties().put(CodegenConstants.GENERATE_API_TESTS, generateApiTests);
config.additionalProperties().put(CodegenConstants.GENERATE_MODEL_TESTS, generateModelTests);
@@ -157,31 +189,33 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
config.additionalProperties().put(CodegenConstants.GENERATE_API_DOCS, generateApiDocumentation);
config.additionalProperties().put(CodegenConstants.GENERATE_MODEL_DOCS, generateModelDocumentation);
if (!generateApiTests && !generateModelTests) {
if(!generateApiTests && !generateModelTests) {
config.additionalProperties().put(CodegenConstants.EXCLUDE_TESTS, true);
}
if (System.getProperty("debugSwagger") != null) {
Json.prettyPrint(swagger);
Json.prettyPrint(this.openAPI);
}
config.processOpts();
config.preprocessSwagger(swagger);
config.preprocessOpenAPI(this.openAPI);
config.additionalProperties().put("generatorVersion", ImplementationVersion.read());
config.additionalProperties().put("generatedDate", DateTime.now().toString());
config.additionalProperties().put("generatedYear", String.valueOf(DateTime.now().getYear()));
config.additionalProperties().put("generatorClass", config.getClass().getName());
config.additionalProperties().put("inputSpec", config.getInputSpec());
if (swagger.getVendorExtensions() != null) {
config.vendorExtensions().putAll(swagger.getVendorExtensions());
if (this.openAPI.getExtensions() != null) {
config.vendorExtensions().putAll(this.openAPI.getExtensions());
}
contextPath = config.escapeText(swagger.getBasePath() == null ? "" : swagger.getBasePath());
basePath = config.escapeText(getHost());
basePathWithoutHost = config.escapeText(swagger.getBasePath());
URL url = URLPathUtil.getServerURL(openAPI);
contextPath = config.escapeText(url == null ? StringUtils.EMPTY : url.getPath());
basePath = config.escapeText(URLPathUtil.getHost(openAPI));
basePathWithoutHost = config.escapeText(contextPath);
}
private void configureSwaggerInfo() {
Info info = swagger.getInfo();
Info info = openAPI.getInfo();
if (info == null) {
return;
}
@@ -194,7 +228,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
LOGGER.error("Missing required field info version. Default appVersion set to 1.0.0");
config.additionalProperties().put("appVersion", "1.0.0");
}
if (StringUtils.isEmpty(info.getDescription())) {
// set a default description if none if provided
config.additionalProperties().put("appDescription",
@@ -240,7 +274,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
}
private void generateModelTests(List<File> files, Map<String, Object> models, String modelName) throws IOException {
private void generateModelTests(List<File> files, Map<String, Object> models, String modelName) throws IOException{
// to generate model test files
for (String templateName : config.modelTestTemplateFiles().keySet()) {
String suffix = config.modelTestTemplateFiles().get(templateName);
@@ -278,22 +312,22 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
return;
}
final Map<String, Model> definitions = swagger.getDefinitions();
if (definitions == null) {
final Map<String, Schema> schemas = this.openAPI.getComponents().getSchemas();
if (schemas == null) {
return;
}
String modelNames = System.getProperty("models");
Set<String> modelsToGenerate = null;
if (modelNames != null && !modelNames.isEmpty()) {
if(modelNames != null && !modelNames.isEmpty()) {
modelsToGenerate = new HashSet<String>(Arrays.asList(modelNames.split(",")));
}
Set<String> modelKeys = definitions.keySet();
if (modelsToGenerate != null && !modelsToGenerate.isEmpty()) {
Set<String> modelKeys = schemas.keySet();
if(modelsToGenerate != null && !modelsToGenerate.isEmpty()) {
Set<String> updatedKeys = new HashSet<String>();
for (String m : modelKeys) {
if (modelsToGenerate.contains(m)) {
for(String m : modelKeys) {
if(modelsToGenerate.contains(m)) {
updatedKeys.add(m);
}
}
@@ -301,53 +335,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
// store all processed models
Map<String, Object> allProcessedModels = new TreeMap<String, Object>(new Comparator<String>() {
Map<String,Object> allProcessedModels = new TreeMap<String, Object>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
Model model1 = definitions.get(o1);
Model model2 = definitions.get(o2);
int model1InheritanceDepth = getInheritanceDepth(model1);
int model2InheritanceDepth = getInheritanceDepth(model2);
if (model1InheritanceDepth == model2InheritanceDepth) {
return ObjectUtils.compare(config.toModelName(o1), config.toModelName(o2));
} else if (model1InheritanceDepth > model2InheritanceDepth) {
return 1;
} else {
return -1;
}
}
private int getInheritanceDepth(Model model) {
int inheritanceDepth = 0;
Model parent = getParent(model);
while (parent != null) {
inheritanceDepth++;
parent = getParent(parent);
}
return inheritanceDepth;
}
private Model getParent(Model model) {
if (model instanceof ComposedModel) {
Model parent = ((ComposedModel) model).getParent();
if (parent == null) {
// check for interfaces
List<RefModel> interfaces = ((ComposedModel) model).getInterfaces();
if (interfaces.size() > 0) {
RefModel interf = interfaces.get(0);
return definitions.get(interf.getSimpleRef());
}
}
if (parent != null) {
return definitions.get(parent.getReference());
}
}
return null;
return ObjectUtils.compare(config.toModelName(o1), config.toModelName(o2));
}
});
@@ -355,14 +346,14 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
for (String name : modelKeys) {
try {
//don't generate models that have an import mapping
if (config.importMapping().containsKey(name)) {
if(config.importMapping().containsKey(name)) {
LOGGER.info("Model " + name + " not imported due to import mapping");
continue;
}
Model model = definitions.get(name);
Map<String, Model> modelMap = new HashMap<String, Model>();
modelMap.put(name, model);
Map<String, Object> models = processModels(config, modelMap, definitions);
Schema schema = schemas.get(name);
Map<String, Schema> schemaMap = new HashMap<>();
schemaMap.put(name, schema);
Map<String, Object> models = processModels(config, schemaMap, schemas);
models.put("classname", config.toModelName(name));
models.putAll(config.additionalProperties());
allProcessedModels.put(name, models);
@@ -375,20 +366,19 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
allProcessedModels = config.postProcessAllModels(allProcessedModels);
// generate files based on processed models
for (String modelName : allProcessedModels.keySet()) {
Map<String, Object> models = (Map<String, Object>) allProcessedModels.get(modelName);
models.put("modelPackage", config.modelPackage());
for (String modelName: allProcessedModels.keySet()) {
Map<String, Object> models = (Map<String, Object>)allProcessedModels.get(modelName);
try {
//don't generate models that have an import mapping
if (config.importMapping().containsKey(modelName)) {
if(config.importMapping().containsKey(modelName)) {
continue;
}
Map<String, Object> modelTemplate = (Map<String, Object>) ((List<Object>) models.get("models")).get(0);
if (config instanceof AbstractJavaCodegen) {
if (isJavaCodegen(config.getName())) {
// Special handling of aliases only applies to Java
if (modelTemplate != null && modelTemplate.containsKey("model")) {
CodegenModel m = (CodegenModel) modelTemplate.get("model");
if (m.isAlias) {
CodegenModel codegenModel = (CodegenModel) modelTemplate.get("model");
if (ExtensionHelper.getBooleanValue(codegenModel, CodegenConstants.IS_ALIAS_EXT_NAME)) {
continue; // Don't create user-defined classes for aliases
}
}
@@ -402,14 +392,14 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
continue;
}
File written = processTemplateToFile(models, templateName, filename);
if (written != null) {
if(written != null) {
files.add(written);
}
}
if (generateModelTests) {
if(generateModelTests) {
generateModelTests(files, models, modelName);
}
if (generateModelDocumentation) {
if(generateModelDocumentation) {
// to generate model documentation files
generateModelDocumentation(files, models, modelName);
}
@@ -428,16 +418,16 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
if (!generateApis) {
return;
}
Map<String, List<CodegenOperation>> paths = processPaths(swagger.getPaths());
Map<String, List<CodegenOperation>> paths = processPaths(this.openAPI.getPaths());
Set<String> apisToGenerate = null;
String apiNames = System.getProperty("apis");
if (apiNames != null && !apiNames.isEmpty()) {
if(apiNames != null && !apiNames.isEmpty()) {
apisToGenerate = new HashSet<String>(Arrays.asList(apiNames.split(",")));
}
if (apisToGenerate != null && !apisToGenerate.isEmpty()) {
if(apisToGenerate != null && !apisToGenerate.isEmpty()) {
Map<String, List<CodegenOperation>> updatedPaths = new TreeMap<String, List<CodegenOperation>>();
for (String m : paths.keySet()) {
if (apisToGenerate.contains(m)) {
for(String m : paths.keySet()) {
if(apisToGenerate.contains(m)) {
updatedPaths.put(m, paths.get(m));
}
}
@@ -458,7 +448,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
operation.put("basePathWithoutHost", basePathWithoutHost);
operation.put("contextPath", contextPath);
operation.put("baseName", tag);
operation.put("apiPackage", config.apiPackage());
operation.put("modelPackage", config.modelPackage());
operation.putAll(config.additionalProperties());
operation.put("classname", config.toApiName(tag));
@@ -466,7 +455,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
operation.put("importPath", config.toApiImport(tag));
operation.put("classFilename", config.toApiFilename(tag));
if (!config.vendorExtensions().isEmpty()) {
if(!config.vendorExtensions().isEmpty()) {
operation.put("vendorExtensions", config.vendorExtensions());
}
@@ -477,9 +466,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
operation.put("sortParamsByRequiredFlag", sortParamsByRequiredFlag);
processMimeTypes(swagger.getConsumes(), operation, "consumes");
processMimeTypes(swagger.getProduces(), operation, "produces");
allOperations.add(new HashMap<String, Object>(operation));
for (int i = 0; i < allOperations.size(); i++) {
Map<String, Object> oo = (Map<String, Object>) allOperations.get(i);
@@ -496,12 +482,12 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
File written = processTemplateToFile(operation, templateName, filename);
if (written != null) {
if(written != null) {
files.add(written);
}
}
if (generateApiTests) {
if(generateApiTests) {
// to generate api test files
for (String templateName : config.apiTestTemplateFiles().keySet()) {
String filename = config.apiTestFilename(templateName, tag);
@@ -519,7 +505,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
if (generateApiDocumentation) {
if(generateApiDocumentation) {
// to generate api documentation files
for (String templateName : config.apiDocTemplateFiles().keySet()) {
String filename = config.apiDocFilename(templateName, tag);
@@ -572,35 +558,27 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
continue;
}
String templateFile;
if (support instanceof GlobalSupportingFile) {
templateFile = config.getCommonTemplateDir() + File.separator + support.templateFile;
if( support instanceof GlobalSupportingFile) {
templateFile = config.getCommonTemplateDir() + File.separator + support.templateFile;
} else {
templateFile = getFullTemplateFile(config, support.templateFile);
}
boolean shouldGenerate = true;
if (supportingFilesToGenerate != null && !supportingFilesToGenerate.isEmpty()) {
if(supportingFilesToGenerate != null && !supportingFilesToGenerate.isEmpty()) {
shouldGenerate = supportingFilesToGenerate.contains(support.destinationFilename);
}
if (!shouldGenerate) {
if (!shouldGenerate){
continue;
}
if (ignoreProcessor.allowsFile(new File(outputFilename))) {
if(ignoreProcessor.allowsFile(new File(outputFilename))) {
if (templateFile.endsWith("mustache")) {
String template = readTemplate(templateFile);
Mustache.Compiler compiler = Mustache.compiler();
compiler = config.processCompiler(compiler);
Template tmpl = compiler
.withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
})
.defaultValue("")
.compile(template);
String templateName = templateFile.replace("\\", "/");
final com.github.jknack.handlebars.Template hTemplate = getHandlebars(templateName.replace(config.templateDir(), StringUtils.EMPTY));
String rendered = hTemplate.apply(bundle);
writeToFile(outputFilename, rendered);
writeToFile(outputFilename, tmpl.execute(bundle));
// writeToFile(outputFilename, tmpl.execute(bundle));
files.add(new File(outputFilename));
} else {
InputStream in = null;
@@ -688,31 +666,33 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
Map<String, Object> apis = new HashMap<String, Object>();
apis.put("apis", allOperations);
if (swagger.getHost() != null) {
bundle.put("host", swagger.getHost());
URL url = URLPathUtil.getServerURL(openAPI);
if (url != null) {
bundle.put("host", url.getHost());
}
bundle.put("swagger", this.swagger);
bundle.put("openAPI", openAPI);
bundle.put("basePath", basePath);
bundle.put("basePathWithoutHost", basePathWithoutHost);
bundle.put("scheme", getScheme());
bundle.put("basePathWithoutHost",basePathWithoutHost);
bundle.put("scheme", URLPathUtil.getScheme(openAPI, config));
bundle.put("contextPath", contextPath);
bundle.put("apiInfo", apis);
bundle.put("models", allModels);
bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar));
bundle.put("modelPackage", config.modelPackage());
List<CodegenSecurity> authMethods = config.fromSecurity(swagger.getSecurityDefinitions());
List<CodegenSecurity> authMethods = config.fromSecurity(openAPI.getComponents().getSecuritySchemes());
if (authMethods != null && !authMethods.isEmpty()) {
bundle.put("authMethods", authMethods);
bundle.put("hasAuthMethods", true);
}
if (swagger.getExternalDocs() != null) {
bundle.put("externalDocs", swagger.getExternalDocs());
if (openAPI.getExternalDocs() != null) {
bundle.put("externalDocs", openAPI.getExternalDocs());
}
for (int i = 0; i < allModels.size() - 1; i++) {
HashMap<String, CodegenModel> cm = (HashMap<String, CodegenModel>) allModels.get(i);
CodegenModel m = cm.get("model");
m.hasMoreModels = true;
m.getVendorExtensions().put(CodegenConstants.HAS_MORE_MODELS_EXT_NAME, Boolean.TRUE);
}
config.postProcessSupportingFileData(bundle);
@@ -727,16 +707,15 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
@Override
public List<File> generate() {
if (swagger == null || config == null) {
throw new RuntimeException("missing swagger input or config!");
if (openAPI == null) {
throw new RuntimeException("missing OpenAPI input!");
}
if (config == null) {
throw new RuntimeException("missing configuration input!");
}
configureGeneratorProperties();
configureSwaggerInfo();
// resolve inline models
InlineModelResolver inlineModelResolver = new InlineModelResolver();
inlineModelResolver.flatten(swagger);
List<File> files = new ArrayList<File>();
// models
List<Object> allModels = new ArrayList<Object>();
@@ -748,29 +727,17 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
// supporting files
Map<String, Object> bundle = buildSupportFileBundle(allOperations, allModels);
generateSupportingFiles(files, bundle);
config.processSwagger(swagger);
config.processOpenAPI(openAPI);
return files;
}
private File processTemplateToFile(Map<String, Object> templateData, String templateName, String outputFilename) throws IOException {
String adjustedOutputFilename = outputFilename.replaceAll("//", "/").replace('/', File.separatorChar);
if (ignoreProcessor.allowsFile(new File(adjustedOutputFilename))) {
if(ignoreProcessor.allowsFile(new File(adjustedOutputFilename))) {
String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile);
Mustache.Compiler compiler = Mustache.compiler();
compiler = config.processCompiler(compiler);
Template tmpl = compiler
.withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
})
.defaultValue("")
.compile(template);
writeToFile(adjustedOutputFilename, tmpl.execute(templateData));
final com.github.jknack.handlebars.Template hTemplate = getHandlebars(templateFile);
String rendered = hTemplate.apply(templateData);
writeToFile(adjustedOutputFilename, rendered);
return new File(adjustedOutputFilename);
}
@@ -779,7 +746,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
private static void processMimeTypes(List<String> mimeTypeList, Map<String, Object> operation, String source) {
if (mimeTypeList == null || mimeTypeList.isEmpty()) {
if (mimeTypeList == null || mimeTypeList.isEmpty()){
return;
}
List<Map<String, String>> c = new ArrayList<Map<String, String>>();
@@ -801,10 +768,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
public Map<String, List<CodegenOperation>> processPaths(Map<String, Path> paths) {
public Map<String, List<CodegenOperation>> processPaths(Paths paths) {
Map<String, List<CodegenOperation>> ops = new TreeMap<String, List<CodegenOperation>>();
for (String resourcePath : paths.keySet()) {
Path path = paths.get(resourcePath);
PathItem path = paths.get(resourcePath);
processOperation(resourcePath, "get", path.getGet(), ops, path);
processOperation(resourcePath, "head", path.getHead(), ops, path);
processOperation(resourcePath, "put", path.getPut(), ops, path);
@@ -816,17 +783,17 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
return ops;
}
private void processOperation(String resourcePath, String httpMethod, Operation operation, Map<String, List<CodegenOperation>> operations, Path path) {
private void processOperation(String resourcePath, String httpMethod, Operation operation, Map<String, List<CodegenOperation>> operations, PathItem path) {
if (operation == null) {
return;
}
if (System.getProperty("debugOperations") != null) {
LOGGER.info("processOperation: resourcePath= " + resourcePath + "\t;" + httpMethod + " " + operation + "\n");
}
List<Tag> tags = new ArrayList<Tag>();
List<Tag> tags = new ArrayList<>();
List<String> tagNames = operation.getTags();
List<Tag> swaggerTags = swagger.getTags();
List<Tag> swaggerTags = this.openAPI.getTags();
if (tagNames != null) {
if (swaggerTags == null) {
for (String tagName : tagNames) {
@@ -870,64 +837,40 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
if (path.getParameters() != null) {
for (Parameter parameter : path.getParameters()) {
//skip propagation if a parameter with the same name is already defined at the operation level
if (!operationParameters.contains(generateParameterId(parameter))) {
operation.addParameter(parameter);
if (!operationParameters.contains(generateParameterId(parameter)) && operation.getParameters() != null) {
operation.getParameters().add(parameter);
}
}
}
for (Tag tag : tags) {
try {
CodegenOperation codegenOperation = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions(), swagger);
codegenOperation.tags = new ArrayList<Tag>(tags);
CodegenOperation codegenOperation = config.fromOperation(resourcePath, httpMethod, operation, openAPI.getComponents().getSchemas(), openAPI);
codegenOperation.tags = new ArrayList<>(tags);
config.addOperationToGroup(config.sanitizeTag(tag.getName()), resourcePath, operation, codegenOperation, operations);
List<Map<String, List<String>>> securities = operation.getSecurity();
if (securities == null && swagger.getSecurity() != null) {
securities = new ArrayList<Map<String, List<String>>>();
for (SecurityRequirement sr : swagger.getSecurity()) {
securities.add(sr.getRequirements());
}
}
if (securities == null || swagger.getSecurityDefinitions() == null) {
final Map<String, SecurityScheme> securitySchemes = openAPI.getComponents().getSecuritySchemes();
List<SecurityRequirement> globalSecurities = openAPI.getSecurity();
List<SecurityRequirement> securities = operation.getSecurity();
if (securities != null && securities.isEmpty()) {
continue;
}
Map<String, SecuritySchemeDefinition> authMethods = new HashMap<String, SecuritySchemeDefinition>();
for (Map<String, List<String>> security : securities) {
for (String securityName : security.keySet()) {
SecuritySchemeDefinition securityDefinition = swagger.getSecurityDefinitions().get(securityName);
if (securityDefinition == null) {
continue;
}
if (securityDefinition instanceof OAuth2Definition) {
OAuth2Definition oauth2Definition = (OAuth2Definition) securityDefinition;
OAuth2Definition oauth2Operation = new OAuth2Definition();
oauth2Operation.setType(oauth2Definition.getType());
oauth2Operation.setAuthorizationUrl(oauth2Definition.getAuthorizationUrl());
oauth2Operation.setFlow(oauth2Definition.getFlow());
oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl());
oauth2Operation.setScopes(new HashMap<String, String>());
for (String scope : security.get(securityName)) {
if (oauth2Definition.getScopes().containsKey(scope)) {
oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope));
}
}
authMethods.put(securityName, oauth2Operation);
} else {
authMethods.put(securityName, securityDefinition);
}
}
Map<String, SecurityScheme> authMethods = getAuthMethods(securities, securitySchemes);
if (authMethods == null || authMethods.isEmpty()) {
authMethods = getAuthMethods(globalSecurities, securitySchemes);
}
if (!authMethods.isEmpty()) {
if (authMethods != null && !authMethods.isEmpty()) {
codegenOperation.authMethods = config.fromSecurity(authMethods);
codegenOperation.hasAuthMethods = true;
codegenOperation.getVendorExtensions().put(CodegenConstants.HAS_AUTH_METHODS_EXT_NAME, Boolean.TRUE);
}
} catch (Exception ex) {
ex.printStackTrace();
String msg = "Could not process operation:\n" //
+ " Tag: " + tag + "\n"//
+ " Operation: " + operation.getOperationId() + "\n" //
+ " Resource: " + httpMethod + " " + resourcePath + "\n"//
+ " Definitions: " + swagger.getDefinitions() + "\n" //
// + " Definitions: " + swagger.getDefinitions() + "\n" //
+ " Exception: " + ex.getMessage();
throw new RuntimeException(msg, ex);
}
@@ -994,22 +937,22 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
if (os != null && os.size() > 0) {
CodegenOperation op = os.get(os.size() - 1);
op.hasMore = false;
op.getVendorExtensions().put(CodegenConstants.HAS_MORE_EXT_NAME, Boolean.FALSE);
}
}
return operations;
}
private Map<String, Object> processModels(CodegenConfig config, Map<String, Model> definitions, Map<String, Model> allDefinitions) {
Map<String, Object> objs = new HashMap<String, Object>();
private Map<String, Object> processModels(CodegenConfig config, Map<String, Schema> definitions, Map<String, Schema> allDefinitions) {
Map<String, Object> objs = new HashMap<>();
objs.put("package", config.modelPackage());
List<Object> models = new ArrayList<Object>();
Set<String> allImports = new LinkedHashSet<String>();
List<Object> models = new ArrayList<>();
Set<String> allImports = new LinkedHashSet<>();
for (String key : definitions.keySet()) {
Model mm = definitions.get(key);
CodegenModel cm = config.fromModel(key, mm, allDefinitions);
Map<String, Object> mo = new HashMap<String, Object>();
Schema schema = definitions.get(key);
CodegenModel cm = config.fromModel(key, schema, allDefinitions);
Map<String, Object> mo = new HashMap<>();
mo.put("model", cm);
mo.put("importPath", config.toModelImport(cm.classname));
models.add(mo);
@@ -1033,7 +976,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
}
List<Map<String, String>> imports = new ArrayList<Map<String, String>>();
for (String s : importSet) {
for(String s: importSet) {
Map<String, String> item = new HashMap<String, String>();
item.put("import", s);
imports.add(item);
@@ -1042,4 +985,36 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
config.postProcessModels(objs);
return objs;
}
private Map<String, SecurityScheme> getAuthMethods(List<SecurityRequirement> securities, Map<String, SecurityScheme> securitySchemes) {
if (securities == null || (securitySchemes == null || securitySchemes.isEmpty())) {
return null;
}
final Map<String, SecurityScheme> authMethods = new HashMap<>();
for (SecurityRequirement requirement : securities) {
for (String key : requirement.keySet()) {
SecurityScheme securityScheme = securitySchemes.get(key);
if (securityScheme != null) {
authMethods.put(key, securityScheme);
}
}
}
return authMethods;
}
private com.github.jknack.handlebars.Template getHandlebars(String templateFile) throws IOException {
if (templateFile.startsWith(config.templateDir())) {
templateFile = templateFile.replaceFirst(config.templateDir(), StringUtils.EMPTY);
}
final TemplateLoader templateLoader = new ClassPathTemplateLoader("/" + config.templateDir(), ".mustache");
final Handlebars handlebars = new Handlebars(templateLoader);
config.addHandlebarHelpers(handlebars);
return handlebars.compile(templateFile.replace(".mustache", StringUtils.EMPTY));
}
private boolean isJavaCodegen(String name) {
return name.equalsIgnoreCase("java")
|| name.equalsIgnoreCase("inflector");
}
}

View File

@@ -1,466 +0,0 @@
package io.swagger.codegen;
import io.swagger.models.*;
import io.swagger.models.parameters.BodyParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.*;
import io.swagger.util.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class InlineModelResolver {
private Swagger swagger;
private boolean skipMatches;
static Logger LOGGER = LoggerFactory.getLogger(InlineModelResolver.class);
Map<String, Model> addedModels = new HashMap<String, Model>();
Map<String, String> generatedSignature = new HashMap<String, String>();
public void flatten(Swagger swagger) {
this.swagger = swagger;
if (swagger.getDefinitions() == null) {
swagger.setDefinitions(new HashMap<String, Model>());
}
// operations
Map<String, Path> paths = swagger.getPaths();
Map<String, Model> models = swagger.getDefinitions();
if (paths != null) {
for (String pathname : paths.keySet()) {
Path path = paths.get(pathname);
for (Operation operation : path.getOperations()) {
List<Parameter> parameters = operation.getParameters();
if (parameters != null) {
for (Parameter parameter : parameters) {
if (parameter instanceof BodyParameter) {
BodyParameter bp = (BodyParameter) parameter;
if (bp.getSchema() != null) {
Model model = bp.getSchema();
if (model instanceof ModelImpl) {
ModelImpl obj = (ModelImpl) model;
if (obj.getType() == null || "object".equals(obj.getType())) {
if (obj.getProperties() != null && obj.getProperties().size() > 0) {
flattenProperties(obj.getProperties(), pathname);
String modelName = resolveModelName(obj.getTitle(), bp.getName());
bp.setSchema(new RefModel(modelName));
addGenerated(modelName, model);
swagger.addDefinition(modelName, model);
}
}
} else if (model instanceof ArrayModel) {
ArrayModel am = (ArrayModel) model;
Property inner = am.getItems();
if (inner instanceof ObjectProperty) {
ObjectProperty op = (ObjectProperty) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(op.getProperties(), pathname);
String modelName = resolveModelName(op.getTitle(), bp.getName());
Model innerModel = modelFromProperty(op, modelName);
String existing = matchGenerated(innerModel);
if (existing != null) {
RefProperty refProperty = new RefProperty(existing);
refProperty.setRequired(op.getRequired());
am.setItems(refProperty);
} else {
RefProperty refProperty = new RefProperty(modelName);
refProperty.setRequired(op.getRequired());
am.setItems(refProperty);
addGenerated(modelName, innerModel);
swagger.addDefinition(modelName, innerModel);
}
}
}
}
}
}
}
}
Map<String, Response> responses = operation.getResponses();
if (responses != null) {
for (String key : responses.keySet()) {
Response response = responses.get(key);
if (response.getSchema() != null) {
Property property = response.getSchema();
if (property instanceof ObjectProperty) {
ObjectProperty op = (ObjectProperty) property;
if (op.getProperties() != null && op.getProperties().size() > 0) {
String modelName = resolveModelName(op.getTitle(), "inline_response_" + key);
Model model = modelFromProperty(op, modelName);
String existing = matchGenerated(model);
if (existing != null) {
Property refProperty = this.makeRefProperty(existing, property);
refProperty.setRequired(op.getRequired());
response.setSchema(refProperty);
} else {
Property refProperty = this.makeRefProperty(modelName, property);
refProperty.setRequired(op.getRequired());
response.setSchema(refProperty);
addGenerated(modelName, model);
swagger.addDefinition(modelName, model);
}
}
} else if (property instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) property;
Property inner = ap.getItems();
if (inner instanceof ObjectProperty) {
ObjectProperty op = (ObjectProperty) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(op.getProperties(), pathname);
String modelName = resolveModelName(op.getTitle(),
"inline_response_" + key);
Model innerModel = modelFromProperty(op, modelName);
String existing = matchGenerated(innerModel);
if (existing != null) {
Property refProperty = this.makeRefProperty(existing, op);
refProperty.setRequired(op.getRequired());
ap.setItems(refProperty);
} else {
Property refProperty = this.makeRefProperty(modelName, op);
refProperty.setRequired(op.getRequired());
ap.setItems(refProperty);
addGenerated(modelName, innerModel);
swagger.addDefinition(modelName, innerModel);
}
}
}
} else if (property instanceof MapProperty) {
MapProperty mp = (MapProperty) property;
Property innerProperty = mp.getAdditionalProperties();
if (innerProperty instanceof ObjectProperty) {
ObjectProperty op = (ObjectProperty) innerProperty;
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(op.getProperties(), pathname);
String modelName = resolveModelName(op.getTitle(),
"inline_response_" + key);
Model innerModel = modelFromProperty(op, modelName);
String existing = matchGenerated(innerModel);
if (existing != null) {
RefProperty refProperty = new RefProperty(existing);
refProperty.setRequired(op.getRequired());
mp.setAdditionalProperties(refProperty);
} else {
RefProperty refProperty = new RefProperty(modelName);
refProperty.setRequired(op.getRequired());
mp.setAdditionalProperties(refProperty);
addGenerated(modelName, innerModel);
swagger.addDefinition(modelName, innerModel);
}
}
}
}
}
}
}
}
}
}
// definitions
if (models != null) {
List<String> modelNames = new ArrayList<String>(models.keySet());
for (String modelName : modelNames) {
Model model = models.get(modelName);
if (model instanceof ModelImpl) {
ModelImpl m = (ModelImpl) model;
Map<String, Property> properties = m.getProperties();
flattenProperties(properties, modelName);
fixStringModel(m);
} else if (model instanceof ArrayModel) {
ArrayModel m = (ArrayModel) model;
Property inner = m.getItems();
if (inner instanceof ObjectProperty) {
ObjectProperty op = (ObjectProperty) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) {
String innerModelName = resolveModelName(op.getTitle(), modelName + "_inner");
Model innerModel = modelFromProperty(op, innerModelName);
String existing = matchGenerated(innerModel);
if (existing == null) {
swagger.addDefinition(innerModelName, innerModel);
addGenerated(innerModelName, innerModel);
RefProperty refProperty = new RefProperty(innerModelName);
refProperty.setRequired(op.getRequired());
m.setItems(refProperty);
} else {
RefProperty refProperty = new RefProperty(existing);
refProperty.setRequired(op.getRequired());
m.setItems(refProperty);
}
}
}
} else if (model instanceof ComposedModel) {
ComposedModel m = (ComposedModel) model;
if (m.getChild() != null) {
Map<String, Property> properties = m.getChild().getProperties();
flattenProperties(properties, modelName);
}
}
}
}
}
/**
* This function fix models that are string (mostly enum). Before this fix, the example
* would look something like that in the doc: "\"example from def\""
* @param m Model implementation
*/
private void fixStringModel(ModelImpl m) {
if (m.getType() != null && m.getType().equals("string") && m.getExample() != null) {
String example = m.getExample().toString();
if (example.substring(0, 1).equals("\"") &&
example.substring(example.length() - 1).equals("\"")) {
m.setExample(example.substring(1, example.length() - 1));
}
}
}
private String resolveModelName(String title, String key) {
if (title == null) {
return uniqueName(key);
} else {
return uniqueName(title);
}
}
public String matchGenerated(Model model) {
if (this.skipMatches) {
return null;
}
String json = Json.pretty(model);
if (generatedSignature.containsKey(json)) {
return generatedSignature.get(json);
}
return null;
}
public void addGenerated(String name, Model model) {
generatedSignature.put(Json.pretty(model), name);
}
public String uniqueName(String key) {
int count = 0;
boolean done = false;
key = key.replaceAll("[^a-z_\\.A-Z0-9 ]", ""); // FIXME: a parameter
// should not be
// assigned. Also declare
// the methods parameters
// as 'final'.
while (!done) {
String name = key;
if (count > 0) {
name = key + "_" + count;
}
if (swagger.getDefinitions() == null) {
return name;
} else if (!swagger.getDefinitions().containsKey(name)) {
return name;
}
count += 1;
}
return key;
}
public void flattenProperties(Map<String, Property> properties, String path) {
if (properties == null) {
return;
}
Map<String, Property> propsToUpdate = new HashMap<String, Property>();
Map<String, Model> modelsToAdd = new HashMap<String, Model>();
for (String key : properties.keySet()) {
Property property = properties.get(key);
if (property instanceof ObjectProperty && ((ObjectProperty) property).getProperties() != null
&& ((ObjectProperty) property).getProperties().size() > 0) {
ObjectProperty op = (ObjectProperty) property;
String modelName = resolveModelName(op.getTitle(), path + "_" + key);
Model model = modelFromProperty(op, modelName);
String existing = matchGenerated(model);
if (existing != null) {
RefProperty refProperty = new RefProperty(existing);
refProperty.setRequired(op.getRequired());
propsToUpdate.put(key, refProperty);
} else {
RefProperty refProperty = new RefProperty(modelName);
refProperty.setRequired(op.getRequired());
propsToUpdate.put(key, refProperty);
modelsToAdd.put(modelName, model);
addGenerated(modelName, model);
swagger.addDefinition(modelName, model);
}
} else if (property instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) property;
Property inner = ap.getItems();
if (inner instanceof ObjectProperty) {
ObjectProperty op = (ObjectProperty) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(op.getProperties(), path);
String modelName = resolveModelName(op.getTitle(), path + "_" + key);
Model innerModel = modelFromProperty(op, modelName);
String existing = matchGenerated(innerModel);
if (existing != null) {
RefProperty refProperty = new RefProperty(existing);
refProperty.setRequired(op.getRequired());
ap.setItems(refProperty);
} else {
RefProperty refProperty = new RefProperty(modelName);
refProperty.setRequired(op.getRequired());
ap.setItems(refProperty);
addGenerated(modelName, innerModel);
swagger.addDefinition(modelName, innerModel);
}
}
}
} else if (property instanceof MapProperty) {
MapProperty mp = (MapProperty) property;
Property inner = mp.getAdditionalProperties();
if (inner instanceof ObjectProperty) {
ObjectProperty op = (ObjectProperty) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(op.getProperties(), path);
String modelName = resolveModelName(op.getTitle(), path + "_" + key);
Model innerModel = modelFromProperty(op, modelName);
String existing = matchGenerated(innerModel);
if (existing != null) {
RefProperty refProperty = new RefProperty(existing);
refProperty.setRequired(op.getRequired());
mp.setAdditionalProperties(refProperty);
} else {
RefProperty refProperty = new RefProperty(modelName);
refProperty.setRequired(op.getRequired());
mp.setAdditionalProperties(refProperty);
addGenerated(modelName, innerModel);
swagger.addDefinition(modelName, innerModel);
}
}
}
}
}
if (propsToUpdate.size() > 0) {
for (String key : propsToUpdate.keySet()) {
properties.put(key, propsToUpdate.get(key));
}
}
for (String key : modelsToAdd.keySet()) {
swagger.addDefinition(key, modelsToAdd.get(key));
this.addedModels.put(key, modelsToAdd.get(key));
}
}
@SuppressWarnings("static-method")
public Model modelFromProperty(ArrayProperty object, @SuppressWarnings("unused") String path) {
String description = object.getDescription();
String example = null;
Object obj = object.getExample();
if (obj != null) {
example = obj.toString();
}
Property inner = object.getItems();
if (inner instanceof ObjectProperty) {
ArrayModel model = new ArrayModel();
model.setDescription(description);
model.setExample(example);
model.setItems(object.getItems());
return model;
}
return null;
}
public Model modelFromProperty(ObjectProperty object, String path) {
String description = object.getDescription();
String example = null;
Object obj = object.getExample();
if (obj != null) {
example = obj.toString();
}
String name = object.getName();
Xml xml = object.getXml();
Map<String, Property> properties = object.getProperties();
ModelImpl model = new ModelImpl();
model.setDescription(description);
model.setExample(example);
model.setName(name);
model.setXml(xml);
if (properties != null) {
flattenProperties(properties, path);
model.setProperties(properties);
}
return model;
}
@SuppressWarnings("static-method")
public Model modelFromProperty(MapProperty object, @SuppressWarnings("unused") String path) {
String description = object.getDescription();
String example = null;
Object obj = object.getExample();
if (obj != null) {
example = obj.toString();
}
ArrayModel model = new ArrayModel();
model.setDescription(description);
model.setExample(example);
model.setItems(object.getAdditionalProperties());
return model;
}
/**
* Make a RefProperty
*
* @param ref new property name
* @param property Property
* @return
*/
public Property makeRefProperty(String ref, Property property) {
RefProperty newProperty = new RefProperty(ref);
this.copyVendorExtensions(property, newProperty);
return newProperty;
}
/**
* Copy vendor extensions from Property to another Property
*
* @param source source property
* @param target target property
*/
public void copyVendorExtensions(Property source, AbstractProperty target) {
Map<String, Object> vendorExtensions = source.getVendorExtensions();
for (String extName : vendorExtensions.keySet()) {
target.setVendorExtension(extName, vendorExtensions.get(extName));
}
}
public boolean isSkipMatches() {
return skipMatches;
}
public void setSkipMatches(boolean skipMatches) {
this.skipMatches = skipMatches;
}
}

View File

@@ -0,0 +1,11 @@
package io.swagger.codegen;
import java.util.Map;
public interface VendorExtendable {
String PREFIX_IS = "x-is-";
String PREFIX_HAS = "x-has-";
Map<String, Object> getVendorExtensions();
}

View File

@@ -1,17 +1,14 @@
package io.swagger.codegen.auth;
import io.swagger.models.auth.AuthorizationValue;
import io.swagger.v3.parser.core.models.AuthorizationValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import config.ConfigParser;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
public class AuthParser {

View File

@@ -9,10 +9,12 @@ import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConfigLoader;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.auth.AuthParser;
import io.swagger.models.Swagger;
import io.swagger.models.auth.AuthorizationValue;
import io.swagger.parser.SwaggerParser;
import io.swagger.util.Json;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.parser.core.models.AuthorizationValue;
import io.swagger.v3.parser.core.models.SwaggerParseResult;
import io.swagger.v3.parser.OpenAPIV3Parser;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -428,10 +430,67 @@ public class CodegenConfigurator implements Serializable {
final List<AuthorizationValue> authorizationValues = AuthParser.parse(auth);
Swagger swagger = new SwaggerParser().read(inputSpec, authorizationValues, true);
SwaggerParseResult result = new OpenAPIParser().readLocation(inputSpec, authorizationValues, null);
OpenAPI openAPI = result.getOpenAPI();
input.opts(new ClientOpts())
.swagger(swagger);
.openAPI(openAPI);
return input;
}
public ClientOptInput toClientOptInput(String content) {
Validate.notEmpty(lang, "language must be specified");
setVerboseFlags();
setSystemProperties();
CodegenConfig config = CodegenConfigLoader.forName(lang);
config.setOutputDir(outputDir);
config.setSkipOverwrite(skipOverwrite);
config.setIgnoreFilePathOverride(ignoreFileOverride);
config.setRemoveOperationIdPrefix(removeOperationIdPrefix);
config.instantiationTypes().putAll(instantiationTypes);
config.typeMapping().putAll(typeMappings);
config.importMapping().putAll(importMappings);
config.languageSpecificPrimitives().addAll(languageSpecificPrimitives);
config.reservedWordsMappings().putAll(reservedWordMappings);
checkAndSetAdditionalProperty(apiPackage, CodegenConstants.API_PACKAGE);
checkAndSetAdditionalProperty(modelPackage, CodegenConstants.MODEL_PACKAGE);
checkAndSetAdditionalProperty(invokerPackage, CodegenConstants.INVOKER_PACKAGE);
checkAndSetAdditionalProperty(groupId, CodegenConstants.GROUP_ID);
checkAndSetAdditionalProperty(artifactId, CodegenConstants.ARTIFACT_ID);
checkAndSetAdditionalProperty(artifactVersion, CodegenConstants.ARTIFACT_VERSION);
checkAndSetAdditionalProperty(templateDir, toAbsolutePathStr(templateDir), CodegenConstants.TEMPLATE_DIR);
checkAndSetAdditionalProperty(modelNamePrefix, CodegenConstants.MODEL_NAME_PREFIX);
checkAndSetAdditionalProperty(modelNameSuffix, CodegenConstants.MODEL_NAME_SUFFIX);
checkAndSetAdditionalProperty(gitUserId, CodegenConstants.GIT_USER_ID);
checkAndSetAdditionalProperty(gitRepoId, CodegenConstants.GIT_REPO_ID);
checkAndSetAdditionalProperty(releaseNote, CodegenConstants.RELEASE_NOTE);
checkAndSetAdditionalProperty(httpUserAgent, CodegenConstants.HTTP_USER_AGENT);
handleDynamicProperties(config);
if (isNotEmpty(library)) {
config.setLibrary(library);
}
config.additionalProperties().putAll(additionalProperties);
ClientOptInput input = new ClientOptInput()
.config(config);
final List<AuthorizationValue> authorizationValues = AuthParser.parse(auth);
SwaggerParseResult result = new OpenAPIParser().readContents(content, authorizationValues, null);
OpenAPI openAPI = result.getOpenAPI();
input.opts(new ClientOpts())
.openAPI(openAPI);
return input;
}

View File

@@ -1,19 +1,29 @@
package io.swagger.codegen.examples;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.properties.*;
import io.swagger.util.Json;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.FileSchema;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import io.swagger.v3.oas.models.media.ObjectSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.media.UUIDSchema;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import io.swagger.v3.core.util.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.util.*;
import static io.swagger.models.properties.StringProperty.Format.URI;
import static io.swagger.models.properties.StringProperty.Format.URL;
//import static io.swagger.models.properties.StringProperty.Format.URI;
//import static io.swagger.models.properties.StringProperty.Format.URL;
public class ExampleGenerator {
private static final Logger logger = LoggerFactory.getLogger(ExampleGenerator.class);
// TODO: move constants to more appropriate location
@@ -24,17 +34,19 @@ public class ExampleGenerator {
private static final String CONTENT_TYPE = "contentType";
private static final String OUTPUT = "output";
private static final String NONE = "none";
private static final String URL = "url";
private static final String URI = "uri";
protected Map<String, Model> examples;
protected Map<String, Schema> examples;
private Random random;
public ExampleGenerator(Map<String, Model> examples) {
public ExampleGenerator(Map<String, Schema> examples) {
this.examples = examples;
// use a fixed seed to make the "random" numbers reproducible.
this.random = new Random("ExampleGenerator".hashCode());
}
public List<Map<String, String>> generate(Map<String, Object> examples, List<String> mediaTypes, Property property) {
public List<Map<String, String>> generate(Map<String, Object> examples, List<String> mediaTypes, Schema property) {
List<Map<String, String>> output = new ArrayList<>();
Set<String> processedModels = new HashSet<>();
if (examples == null) {
@@ -68,6 +80,7 @@ public class ExampleGenerator {
output.add(kv);
}
}
System.out.println("the size is: " + output.size());
if (output.size() == 0) {
Map<String, String> kv = new HashMap<>();
kv.put(OUTPUT, NONE);
@@ -88,10 +101,10 @@ public class ExampleGenerator {
Map<String, String> kv = new HashMap<>();
kv.put(CONTENT_TYPE, mediaType);
if (modelName != null && mediaType.startsWith(MIME_TYPE_JSON)) {
final Model model = this.examples.get(modelName);
if (model != null) {
final Schema schema = this.examples.get(modelName);
if (schema != null) {
String example = Json.pretty(resolveModelToExample(modelName, mediaType, model, processedModels));
String example = Json.pretty(resolveModelToExample(modelName, mediaType, schema, processedModels));
if (example != null) {
kv.put(EXAMPLE, example);
@@ -99,8 +112,8 @@ public class ExampleGenerator {
}
}
} else if (modelName != null && mediaType.startsWith(MIME_TYPE_XML)) {
final Model model = this.examples.get(modelName);
String example = new XmlExampleGenerator(this.examples).toXml(model, 0, Collections.<String>emptySet());
final Schema schema = this.examples.get(modelName);
String example = new XmlExampleGenerator(this.examples).toXml(schema, 0, Collections.<String>emptySet());
if (example != null) {
kv.put(EXAMPLE, example);
output.add(kv);
@@ -123,40 +136,40 @@ public class ExampleGenerator {
return output;
}
private Object resolvePropertyToExample(String propertyName, String mediaType, Property property, Set<String> processedModels) {
private Object resolvePropertyToExample(String propertyName, String mediaType, Schema property, Set<String> processedModels) {
logger.debug("Resolving example for property {}...", property);
if (property.getExample() != null) {
logger.debug("Example set in swagger spec, returning example: '{}'", property.getExample().toString());
return property.getExample();
} else if (property instanceof StringProperty) {
} else if (property instanceof StringSchema) {
logger.debug("String property");
String defaultValue = ((StringProperty) property).getDefault();
String defaultValue = ((StringSchema) property).getDefault();
if (defaultValue != null && !defaultValue.isEmpty()) {
logger.debug("Default value found: '{}'", defaultValue);
return defaultValue;
}
List<String> enumValues = ((StringProperty) property).getEnum();
List<String> enumValues = ((StringSchema) property).getEnum();
if (enumValues != null && !enumValues.isEmpty()) {
logger.debug("Enum value found: '{}'", enumValues.get(0));
return enumValues.get(0);
}
String format = property.getFormat();
if (format != null && (URI.getName().equals(format) || URL.getName().equals(format))) {
if (format != null && (URI.equals(format) || URL.equals(format))) {
logger.debug("URI or URL format, without default or enum, generating random one.");
return "http://example.com/aeiou";
}
logger.debug("No values found, using property name " + propertyName + " as example");
return propertyName;
} else if (property instanceof BooleanProperty) {
Boolean defaultValue = ((BooleanProperty) property).getDefault();
} else if (property instanceof BooleanSchema) {
Object defaultValue = property.getDefault();
if (defaultValue != null) {
return defaultValue;
}
return Boolean.TRUE;
} else if (property instanceof ArrayProperty) {
Property innerType = ((ArrayProperty) property).getItems();
} else if (property instanceof ArraySchema) {
Schema innerType = ((ArraySchema) property).getItems();
if (innerType != null) {
int arrayLength = null == ((ArrayProperty) property).getMaxItems() ? 2 : ((ArrayProperty) property).getMaxItems();
int arrayLength = null == ((ArraySchema) property).getMaxItems() ? 2 : ((ArraySchema) property).getMaxItems();
Object[] objectProperties = new Object[arrayLength];
Object objProperty = resolvePropertyToExample(propertyName, mediaType, innerType, processedModels);
for(int i=0; i < arrayLength; i++) {
@@ -164,45 +177,41 @@ public class ExampleGenerator {
}
return objectProperties;
}
} else if (property instanceof DateProperty) {
} else if (property instanceof DateSchema) {
return "2000-01-23";
} else if (property instanceof DateTimeProperty) {
} else if (property instanceof DateTimeSchema) {
return "2000-01-23T04:56:07.000+00:00";
} else if (property instanceof DoubleProperty) {
Double min = ((DecimalProperty) property).getMinimum() == null ? null : ((DecimalProperty) property).getMinimum().doubleValue();
Double max = ((DecimalProperty) property).getMaximum() == null ? null : ((DecimalProperty) property).getMaximum().doubleValue();
} else if (property instanceof NumberSchema) {
Double min = property.getMinimum() == null ? null : property.getMinimum().doubleValue();
Double max = property.getMaximum() == null ? null : property.getMaximum().doubleValue();
if(SchemaTypeUtil.FLOAT_FORMAT.equals(property.getFormat())) {
return (float) randomNumber(min, max);
}
return randomNumber(min, max);
} else if (property instanceof FloatProperty) {
Double min = ((DecimalProperty) property).getMinimum() == null ? null : ((DecimalProperty) property).getMinimum().doubleValue();
Double max = ((DecimalProperty) property).getMaximum() == null ? null : ((DecimalProperty) property).getMaximum().doubleValue();
return (float) randomNumber(min, max);
} else if (property instanceof DecimalProperty) {
Double min = ((DecimalProperty) property).getMinimum() == null ? null : ((DecimalProperty) property).getMinimum().doubleValue();
Double max = ((DecimalProperty) property).getMaximum() == null ? null : ((DecimalProperty) property).getMaximum().doubleValue();
return new BigDecimal(randomNumber(min, max));
} else if (property instanceof FileProperty) {
} else if (property instanceof FileSchema) {
return ""; // TODO
} else if (property instanceof LongProperty) {
Double min = ((BaseIntegerProperty) property).getMinimum() == null ? null : ((BaseIntegerProperty) property).getMinimum().doubleValue();
Double max = ((BaseIntegerProperty) property).getMaximum() == null ? null : ((BaseIntegerProperty) property).getMaximum().doubleValue();
return (long) randomNumber(min, max);
} else if (property instanceof BaseIntegerProperty) { // Includes IntegerProperty
Double min = ((BaseIntegerProperty) property).getMinimum() == null ? null : ((BaseIntegerProperty) property).getMinimum().doubleValue();
Double max = ((BaseIntegerProperty) property).getMaximum() == null ? null : ((BaseIntegerProperty) property).getMaximum().doubleValue();
} else if (property instanceof IntegerSchema) {
Double min = property.getMinimum() == null ? null : property.getMinimum().doubleValue();
Double max = property.getMaximum() == null ? null : property.getMaximum().doubleValue();
if(SchemaTypeUtil.INTEGER32_FORMAT.equals(property.getFormat())) {
return (long) randomNumber(min, max);
}
return (int) randomNumber(min, max);
} else if (property instanceof MapProperty) {
} else if (property instanceof MapSchema && property.getAdditionalProperties() != null && property.getAdditionalProperties() instanceof Schema) {
Map<String, Object> mp = new HashMap<String, Object>();
if (property.getName() != null) {
mp.put(property.getName(),
resolvePropertyToExample(propertyName, mediaType, ((MapProperty) property).getAdditionalProperties(), processedModels));
resolvePropertyToExample(propertyName, mediaType, (Schema) property.getAdditionalProperties(), processedModels));
} else {
mp.put("key",
resolvePropertyToExample(propertyName, mediaType, ((MapProperty) property).getAdditionalProperties(), processedModels));
resolvePropertyToExample(propertyName, mediaType, (Schema) property.getAdditionalProperties(), processedModels));
}
return mp;
} else if (property instanceof ObjectProperty) {
} else if (property instanceof ObjectSchema) {
return "{}";
} else if (property instanceof RefProperty) {
}
/** this concep no longer exists
else if (property instanceof RefProperty) {
String simpleName = ((RefProperty) property).getSimpleRef();
logger.debug("Ref property, simple name: {}", simpleName);
Model model = examples.get(simpleName);
@@ -210,7 +219,8 @@ public class ExampleGenerator {
return resolveModelToExample(simpleName, mediaType, model, processedModels);
}
logger.warn("Ref property with empty model.");
} else if (property instanceof UUIDProperty) {
}*/ else if (property instanceof UUIDSchema) {
return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
}
@@ -230,30 +240,26 @@ public class ExampleGenerator {
}
}
private Object resolveModelToExample(String name, String mediaType, Model model, Set<String> processedModels) {
private Object resolveModelToExample(String name, String mediaType, Schema schema, Set<String> processedModels) {
if (processedModels.contains(name)) {
return model.getExample();
return schema.getExample();
}
if (model instanceof ModelImpl) {
processedModels.add(name);
ModelImpl impl = (ModelImpl) model;
Map<String, Object> values = new HashMap<>();
processedModels.add(name);
Map<String, Object> values = new HashMap<>();
logger.debug("Resolving model '{}' to example", name);
logger.debug("Resolving model '{}' to example", name);
if (impl.getExample() != null) {
logger.debug("Using example from spec: {}", impl.getExample());
return impl.getExample();
} else if (impl.getProperties() != null) {
logger.debug("Creating example from model values");
for (String propertyName : impl.getProperties().keySet()) {
Property property = impl.getProperties().get(propertyName);
values.put(propertyName, resolvePropertyToExample(propertyName, mediaType, property, processedModels));
}
impl.setExample(values);
if (schema.getExample() != null) {
logger.debug("Using example from spec: {}", schema.getExample());
return schema.getExample();
} else if (schema.getProperties() != null) {
logger.debug("Creating example from model values");
for (Object propertyName : schema.getProperties().keySet()) {
schema.getProperties().get(propertyName.toString());
values.put(propertyName.toString(), resolvePropertyToExample(propertyName.toString(), mediaType, schema, processedModels));
}
return values;
schema.setExample(values);
}
return "";
return values;
}
}

View File

@@ -1,25 +1,16 @@
package io.swagger.codegen.examples;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.RefModel;
import io.swagger.models.Xml;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.DecimalProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.BaseIntegerProperty;
import io.swagger.models.properties.AbstractNumericProperty;
import io.swagger.models.properties.PasswordProperty;
import io.swagger.models.properties.UUIDProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import io.swagger.v3.oas.models.media.PasswordSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.media.UUIDSchema;
import io.swagger.v3.oas.models.media.XML;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
@@ -34,40 +25,38 @@ import java.util.Map;
import java.util.Set;
public class XmlExampleGenerator {
protected final Logger LOGGER = LoggerFactory.getLogger(XmlExampleGenerator.class);
public static String NEWLINE = "\n";
public static String TAG_START = "<";
public static String CLOSE_TAG = ">";
public static String TAG_END = "</";
private static String EMPTY = "";
protected Map<String, Model> examples;
protected Map<String, Schema> examples;
public XmlExampleGenerator(Map<String, Model> examples) {
public XmlExampleGenerator(Map<String, Schema> examples) {
this.examples = examples;
if (examples == null) {
this.examples = new HashMap<String, Model>();
this.examples = new HashMap<String, Schema>();
}
}
public String toXml(Property property) {
public String toXml(Schema property) {
return toXml(null, property, 0, Collections.<String>emptySet());
}
protected String toXml(Model model, int indent, Collection<String> path) {
if (model instanceof RefModel) {
RefModel ref = (RefModel) model;
Model actualModel = examples.get(ref.getSimpleRef());
if (actualModel instanceof ModelImpl) {
return modelImplToXml((ModelImpl) actualModel, indent, path);
protected String toXml(Schema schema, int indent, Collection<String> path) {
if (StringUtils.isNotEmpty(schema.get$ref())) {
Schema actualSchema = examples.get(schema.get$ref());
if (actualSchema != null) {
return modelImplToXml(actualSchema, indent, path);
}
} else if (model instanceof ModelImpl) {
return modelImplToXml((ModelImpl) model, indent, path);
}
return null;
return modelImplToXml(schema, indent, path);
}
protected String modelImplToXml(ModelImpl model, int indent, Collection<String> path) {
final String modelName = model.getName();
protected String modelImplToXml(Schema schema, int indent, Collection<String> path) {
final String modelName = schema.getName();
if (path.contains(modelName)) {
return EMPTY;
}
@@ -76,37 +65,38 @@ public class XmlExampleGenerator {
StringBuilder sb = new StringBuilder();
// attributes
Map<String, Property> attributes = new LinkedHashMap<String, Property>();
Map<String, Property> elements = new LinkedHashMap<String, Property>();
Map<String, Schema> attributes = new LinkedHashMap<>();
Map<String, Schema> elements = new LinkedHashMap<>();
String name = modelName;
Xml xml = model.getXml();
XML xml = schema.getXml();
if (xml != null) {
if (xml.getName() != null) {
name = xml.getName();
}
}
// TODO: map objects will not enter this block
if(model.getProperties() != null) {
for (String pName : model.getProperties().keySet()) {
Property p = model.getProperties().get(pName);
if (p != null && p.getXml() != null && p.getXml().getAttribute() != null && p.getXml().getAttribute()) {
attributes.put(pName, p);
Map<String, Schema> properties = schema.getProperties();
if(properties != null && !properties.isEmpty()) {
for (String pName : properties.keySet()) {
Schema property = properties.get(pName);
if (property != null && property.getXml() != null && property.getXml().getAttribute() != null && property.getXml().getAttribute()) {
attributes.put(pName, property);
} else {
elements.put(pName, p);
elements.put(pName, property);
}
}
}
sb.append(indent(indent)).append(TAG_START);
sb.append(name);
for (String pName : attributes.keySet()) {
Property p = attributes.get(pName);
sb.append(" ").append(pName).append("=").append(quote(toXml(null, p, 0, selfPath)));
Schema property = attributes.get(pName);
sb.append(" ").append(pName).append("=").append(quote(toXml(null, property, 0, selfPath)));
}
sb.append(CLOSE_TAG);
sb.append(NEWLINE);
for (String pName : elements.keySet()) {
Property p = elements.get(pName);
Schema p = elements.get(pName);
final String asXml = toXml(pName, p, indent + 1, selfPath);
if (StringUtils.isEmpty(asXml)) {
continue;
@@ -124,15 +114,15 @@ public class XmlExampleGenerator {
return "\"" + string + "\"";
}
protected String toXml(String name, Property property, int indent, Collection<String> path) {
protected String toXml(String name, Schema property, int indent, Collection<String> path) {
if (property == null) {
return "";
}
StringBuilder sb = new StringBuilder();
if (property instanceof ArrayProperty) {
ArrayProperty p = (ArrayProperty) property;
Property inner = p.getItems();
if (property instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) property;
Schema inner = arraySchema.getItems();
boolean wrapped = false;
if (property.getXml() != null && property.getXml().getWrapped() != null && property.getXml().getWrapped()) {
wrapped = true;
@@ -156,10 +146,9 @@ public class XmlExampleGenerator {
} else {
sb.append(toXml(name, inner, indent, path));
}
} else if (property instanceof RefProperty) {
RefProperty ref = (RefProperty) property;
Model actualModel = examples.get(ref.getSimpleRef());
sb.append(toXml(actualModel, indent, path));
} else if (StringUtils.isNotEmpty(property.get$ref())) {
Schema actualSchema = examples.get(property.get$ref());
sb.append(toXml(actualSchema, indent, path));
} else {
if (name != null) {
sb.append(indent(indent));
@@ -182,32 +171,29 @@ public class XmlExampleGenerator {
*
* @return Example String
*/
protected String getExample(Property property) {
protected String getExample(Schema property) {
if (property.getExample() != null) {
return property.getExample().toString();
} else if (property instanceof DateTimeProperty) {
} else if (property instanceof DateTimeSchema) {
return "2000-01-23T04:56:07.000Z";
} else if (property instanceof DateProperty) {
} else if (property instanceof DateSchema) {
return "2000-01-23";
} else if (property instanceof BooleanProperty) {
} else if (property instanceof BooleanSchema) {
return "true";
} else if (property instanceof LongProperty) {
} else if (property instanceof IntegerSchema) {
if(SchemaTypeUtil.INTEGER32_FORMAT.equals(property.getFormat())) {
return "123";
}
return "123456789";
} else if (property instanceof DoubleProperty) { // derived from DecimalProperty so make sure this is first
return "3.149";
} else if (property instanceof DecimalProperty) {
} else if (property instanceof NumberSchema) {
return "1.3579";
} else if (property instanceof PasswordProperty) {
} else if (property instanceof PasswordSchema) {
return "********";
} else if (property instanceof UUIDProperty) {
} else if (property instanceof UUIDSchema) {
return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
// do these last in case the specific types above are derived from these classes
} else if (property instanceof StringProperty) {
} else if (property instanceof StringSchema) {
return "aeiou";
} else if (property instanceof BaseIntegerProperty) {
return "123";
} else if (property instanceof AbstractNumericProperty) {
return "1.23";
}
LOGGER.warn("default example value not implemented for " + property);
return "";

View File

@@ -3,16 +3,32 @@ package io.swagger.codegen.languages;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.samskivert.mustache.Escapers;
import com.samskivert.mustache.Mustache;
import io.swagger.codegen.*;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Response;
import io.swagger.models.Swagger;
import io.swagger.models.properties.*;
import io.swagger.util.Json;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenSecurity;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.languages.helpers.ExtensionHelper;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.FileSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.responses.ApiResponse;
import java.util.*;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
abstract public class AbstractAdaCodegen extends DefaultCodegen implements CodegenConfig {
protected String packageName = "swagger";
protected String projectName = "Swagger";
@@ -231,13 +247,11 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
}
@Override
public CodegenProperty fromProperty(String name, Property p) {
CodegenProperty property = super.fromProperty(name, p);
if (property != null) {
String nameInCamelCase = property.nameInCamelCase;
nameInCamelCase = sanitizeName(nameInCamelCase);
property.nameInCamelCase = nameInCamelCase;
}
public CodegenProperty fromProperty(String name, Schema schema) {
CodegenProperty property = super.fromProperty(name, schema);
String nameInCamelCase = property.nameInCamelCase;
nameInCamelCase = sanitizeName(nameInCamelCase);
property.nameInCamelCase = nameInCamelCase;
return property;
}
@@ -288,21 +302,21 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
* `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
String swaggerType = getSwaggerType(p);
public String getTypeDeclaration(Schema property) {
String schemaType = getSchemaType(property);
if (swaggerType != null) {
swaggerType = swaggerType.replace("-", "_");
if (schemaType != null) {
schemaType = schemaType.replace("-", "_");
}
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
if (property instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) property;
Schema inner = arraySchema.getItems();
return getTypeDeclaration(inner) + "_Vectors.Vector";
}
if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
if (property instanceof MapSchema && hasSchemaProperties(property)) {
MapSchema mapSchema = (MapSchema) property;
Schema inner = (Schema) mapSchema.getAdditionalProperties();
String name = getTypeDeclaration(inner) + "_Map";
if (name.startsWith("Swagger.")) {
return name;
@@ -310,20 +324,22 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
return "Swagger." + name;
}
}
if (typeMapping.containsKey(swaggerType)) {
if (p.getRequired()) {
return typeMapping.get(swaggerType);
if (typeMapping.containsKey(schemaType)) {
/** todo: find out how to check if a schema property is required on oas 3
if (property.getRequired()) {
return typeMapping.get(schemaType);
} else {
return nullableTypeMapping.get(swaggerType);
return nullableTypeMapping.get(schemaType);
}
*/
}
// LOGGER.info("Swagger type " + swaggerType);
if (languageSpecificPrimitives.contains(swaggerType)) {
return swaggerType;
if (languageSpecificPrimitives.contains(schemaType)) {
return schemaType;
}
String modelType = toModelName(swaggerType).replace("-", "_");
if (p instanceof StringProperty || p instanceof DateProperty
|| p instanceof DateTimeProperty || p instanceof FileProperty
String modelType = toModelName(schemaType).replace("-", "_");
if (property instanceof StringSchema || property instanceof DateSchema
|| property instanceof DateTimeSchema || property instanceof FileSchema
|| languageSpecificPrimitives.contains(modelType)) {
return modelType;
}
@@ -338,7 +354,7 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
* @param parameter CodegenParameter object to be processed.
*/
@Override
public void postProcessParameter(CodegenParameter parameter){
public void postProcessParameter(CodegenParameter parameter) {
// Give the base class a chance to process
super.postProcessParameter(parameter);
@@ -346,8 +362,12 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
return;
}
boolean isModel = parameter.dataType.startsWith(modelPackage);
if (!isModel && !parameter.isPrimitiveType && !parameter.isDate
&& !parameter.isString && !parameter.isContainer && !parameter.isFile) {
if (!isModel
&& !getBooleanValue(parameter, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME)
&& !getBooleanValue(parameter, CodegenConstants.IS_DATE_EXT_NAME)
&& !getBooleanValue(parameter, CodegenConstants.IS_STRING_EXT_NAME)
&& !getBooleanValue(parameter, CodegenConstants.IS_CONTAINER_EXT_NAME)
&& !getBooleanValue(parameter, CodegenConstants.IS_FILE_EXT_NAME)) {
isModel = true;
}
parameter.vendorExtensions.put("x-is-model-type", isModel);
@@ -378,24 +398,24 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation,
Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Schema> definitions, OpenAPI openAPI) {
CodegenOperation codegenOperation = super.fromOperation(path, httpMethod, operation, definitions, openAPI);
if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
Response methodResponse = findMethodResponse(operation.getResponses());
ApiResponse methodResponse = findMethodResponse(operation.getResponses());
if (methodResponse != null) {
if (methodResponse.getSchema() != null) {
CodegenProperty cm = fromProperty("response", methodResponse.getSchema());
op.vendorExtensions.put("x-codegen-response", cm);
if(cm.datatype == "HttpContent") {
op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
Schema schema = getSchemaFromResponse(methodResponse);
if (schema != null) {
CodegenProperty codegenProperty = fromProperty("response", schema);
codegenOperation.vendorExtensions.put("x-codegen-response", codegenProperty);
if(codegenProperty.datatype == "HttpContent") {
codegenOperation.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
}
}
}
}
return op;
return codegenOperation;
}
@SuppressWarnings("unchecked")
@@ -404,36 +424,37 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op1 : operationList) {
if (op1.summary != null) {
op1.summary = op1.summary.trim();
for (CodegenOperation codegenOperation : operationList) {
if (codegenOperation.summary != null) {
codegenOperation.summary = codegenOperation.summary.trim();
}
if (op1.notes != null) {
op1.notes = op1.notes.trim();
if (codegenOperation.notes != null) {
codegenOperation.notes = codegenOperation.notes.trim();
}
op1.vendorExtensions.put("x-has-uniq-produces", postProcessMediaTypes(op1.produces) == 1);
op1.vendorExtensions.put("x-has-uniq-consumes", postProcessMediaTypes(op1.consumes) == 1);
op1.vendorExtensions.put("x-has-notes", op1.notes != null && op1.notes.length() > 0);
codegenOperation.vendorExtensions.put("x-has-uniq-produces", postProcessMediaTypes(codegenOperation.produces) == 1);
codegenOperation.vendorExtensions.put("x-has-uniq-consumes", postProcessMediaTypes(codegenOperation.consumes) == 1);
codegenOperation.vendorExtensions.put("x-has-notes", codegenOperation.notes != null && codegenOperation.notes.length() > 0);
// Set the file parameter type for both allParams and formParams.
for (CodegenParameter p : op1.allParams) {
if (p.isFormParam && p.isFile) {
p.dataType = "Swagger.File_Part_Type";
for (CodegenParameter codegenParameter : codegenOperation.allParams) {
if (getBooleanValue(codegenParameter, CodegenConstants.IS_FORM_PARAM_EXT_NAME)
&& getBooleanValue(codegenParameter, CodegenConstants.IS_FILE_EXT_NAME)) {
codegenParameter.dataType = "Swagger.File_Part_Type";
}
}
for (CodegenParameter p : op1.formParams) {
if (p.isFile) {
p.dataType = "Swagger.File_Part_Type";
for (CodegenParameter codegenParameter : codegenOperation.formParams) {
if (getBooleanValue(codegenParameter, CodegenConstants.IS_FILE_EXT_NAME)) {
codegenParameter.dataType = "Swagger.File_Part_Type";
}
}
postProcessAuthMethod(op1.authMethods);
postProcessAuthMethod(codegenOperation.authMethods);
/*
* Scan the path parameter to construct a x-path-index that tells the index of
* the path parameter.
*/
for (CodegenParameter p : op1.pathParams) {
String path = op1.path;
for (CodegenParameter p : codegenOperation.pathParams) {
String path = codegenOperation.path;
int pos = 0;
int index = 0;
while (pos >= 0 && pos < path.length()) {
@@ -463,28 +484,32 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// Collect the model dependencies.
List<Map<String, Object>> models = (List<Map<String, Object>>) objs.get("models");
for (Map<String, Object> model : models) {
Object v = model.get("model");
if (v instanceof CodegenModel) {
CodegenModel m = (CodegenModel) v;
for (Map<String, Object> modelMap : models) {
Object model = modelMap.get("model");
if (model instanceof CodegenModel) {
CodegenModel codegenModel = (CodegenModel) model;
List<String> d = new ArrayList<String>();
for (CodegenProperty p : m.allVars) {
for (CodegenProperty codegenProperty : codegenModel.allVars) {
boolean isModel = false;
CodegenProperty item = p;
if (p.isContainer) {
item = p.items;
CodegenProperty item = codegenProperty;
if (getBooleanValue(codegenProperty, CodegenConstants.IS_CONTAINER_EXT_NAME)) {
item = codegenProperty.items;
}
if (item != null && !item.isString && !item.isPrimitiveType && !item.isContainer && !item.isInteger) {
if (item != null
&& !getBooleanValue(item, CodegenConstants.IS_STRING_EXT_NAME)
&& !getBooleanValue(item, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME)
&& !getBooleanValue(item, CodegenConstants.IS_CONTAINER_EXT_NAME)
&& !getBooleanValue(item, CodegenConstants.IS_INTEGER_EXT_NAME)) {
if (!d.contains(item.datatype)) {
// LOGGER.info("Model " + m.name + " uses " + p.datatype);
d.add(item.datatype);
isModel = true;
}
}
p.vendorExtensions.put("x-is-model-type", isModel);
codegenProperty.vendorExtensions.put("x-is-model-type", isModel);
}
modelDepends.put(m.name, d);
orderedModels.add(model);
modelDepends.put(codegenModel.name, d);
orderedModels.add(modelMap);
}
}
@@ -549,16 +574,13 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
objs.put("orderedModels", orderedModels);
Swagger swagger = (Swagger)objs.get("swagger");
if(swagger != null) {
String host = swagger.getBasePath();
OpenAPI openAPI = (OpenAPI) objs.get("openapi");
if(openAPI != null) {
try {
swagger.setHost("SWAGGER_HOST");
objs.put("swagger-json", Json.pretty().writeValueAsString(swagger).replace("\r\n", "\n"));
objs.put("openapi-json", Json.pretty().writeValueAsString(openAPI).replace("\r\n", "\n"));
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}
swagger.setHost(host);
}
/**
@@ -579,26 +601,24 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
if (authMethods != null) {
for (CodegenSecurity authMethod : authMethods) {
if (authMethod.scopes != null) {
for (Map<String, Object> scope : authMethod.scopes) {
String name = (String) scope.get("scope");
if (operationsScopes.containsKey(name)) {
scope.put("ident", operationsScopes.get(name));
String name = authMethod.scopes.get("scope");
if (operationsScopes.containsKey(name)) {
authMethod.scopes.put("ident", operationsScopes.get(name));
} else {
String ident;
if (name.startsWith("https://")) {
int pos = name.lastIndexOf('/');
ident = name.substring(pos + 1);
} else {
String ident;
if (name.startsWith("https://")) {
int pos = name.lastIndexOf('/');
ident = name.substring(pos + 1);
} else {
ident = name;
}
scopeIndex++;
ident = toAdaIdentifier(sanitizeName(ident.replaceAll(":", "_")), "S_");
if (operationsScopes.containsValue(ident)) {
ident = ident + "_" + scopeIndex;
}
operationsScopes.put(name, ident);
scope.put("ident", ident);
ident = name;
}
scopeIndex++;
ident = toAdaIdentifier(sanitizeName(ident.replaceAll(":", "_")), "S_");
if (operationsScopes.containsValue(ident)) {
ident = ident + "_" + scopeIndex;
}
operationsScopes.put(name, ident);
authMethod.scopes.put("ident", ident);
}
}
authMethod.name = camelize(sanitizeName(authMethod.name), true);

View File

@@ -1,8 +1,14 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import io.swagger.codegen.utils.ModelUtils;
import io.swagger.models.properties.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -10,6 +16,10 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
import static io.swagger.codegen.utils.ModelUtils.updateCodegenPropertyEnum;
public abstract class AbstractCSharpCodegen extends DefaultCodegen implements CodegenConfig {
protected boolean optionalAssemblyInfoFlag = true;
@@ -357,7 +367,8 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
Map<String, CodegenModel> enumRefs = new HashMap<String, CodegenModel>();
for (Map.Entry<String, Object> entry : models.entrySet()) {
CodegenModel model = ModelUtils.getModelByName(entry.getKey(), models);
if (model.isEnum) {
boolean isEnum = getBooleanValue(model, IS_ENUM_EXT_NAME);
if (isEnum) {
enumRefs.put(entry.getKey(), model);
}
}
@@ -373,17 +384,16 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
// while enums in many other languages are true objects.
CodegenModel refModel = enumRefs.get(var.datatype);
var.allowableValues = refModel.allowableValues;
var.isEnum = true;
updateCodegenPropertyEnum(var);
// We do these after updateCodegenPropertyEnum to avoid generalities that don't mesh with C#.
var.isPrimitiveType = true;
var.getVendorExtensions().put(CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME, Boolean.TRUE);
var.getVendorExtensions().put(IS_ENUM_EXT_NAME, Boolean.TRUE);
}
}
// We're looping all models here.
if (model.isEnum) {
if (getBooleanValue(model, CodegenConstants.IS_ENUM_EXT_NAME)) {
// We now need to make allowableValues.enumVars look like the context of CodegenProperty
Boolean isString = false;
Boolean isInteger = false;
@@ -437,33 +447,32 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
*
* @param var list of CodegenProperty
*/
@Override
public void updateCodegenPropertyEnum(CodegenProperty var) {
if (var.vendorExtensions == null) {
var.vendorExtensions = new HashMap<>();
}
super.updateCodegenPropertyEnum(var);
ModelUtils.updateCodegenPropertyEnum(var);
// Because C# uses nullable primitives for datatype, and datatype is used in DefaultCodegen for determining enum-ness, guard against weirdness here.
if (var.isEnum) {
if (getBooleanValue(var, CodegenConstants.IS_ENUM_EXT_NAME)) {
if ("byte".equals(var.dataFormat)) {// C# Actually supports byte and short enums.
var.vendorExtensions.put("x-enum-byte", true);
var.isString = false;
var.isLong = false;
var.isInteger = false;
var.vendorExtensions.put(CodegenConstants.IS_STRING_EXT_NAME, Boolean.FALSE);
var.vendorExtensions.put(CodegenConstants.IS_LONG_EXT_NAME, Boolean.FALSE);
var.vendorExtensions.put(CodegenConstants.IS_INTEGER_EXT_NAME, Boolean.FALSE);
} else if ("int32".equals(var.dataFormat)) {
var.isInteger = true;
var.isString = false;
var.isLong = false;
var.vendorExtensions.put(CodegenConstants.IS_INTEGER_EXT_NAME, Boolean.TRUE);
var.vendorExtensions.put(CodegenConstants.IS_STRING_EXT_NAME, Boolean.FALSE);
var.vendorExtensions.put(CodegenConstants.IS_LONG_EXT_NAME, Boolean.FALSE);
} else if ("int64".equals(var.dataFormat)) {
var.isLong = true;
var.isString = false;
var.isInteger = false;
var.vendorExtensions.put(CodegenConstants.IS_LONG_EXT_NAME, Boolean.TRUE);
var.vendorExtensions.put(CodegenConstants.IS_STRING_EXT_NAME, Boolean.FALSE);
var.vendorExtensions.put(CodegenConstants.IS_INTEGER_EXT_NAME, Boolean.FALSE);
} else {// C# doesn't support non-integral enums, so we need to treat everything else as strings (e.g. to not lose precision or data integrity)
var.isString = true;
var.isInteger = false;
var.isLong = false;
var.vendorExtensions.put(CodegenConstants.IS_STRING_EXT_NAME, Boolean.TRUE);
var.vendorExtensions.put(CodegenConstants.IS_LONG_EXT_NAME, Boolean.FALSE);
var.vendorExtensions.put(CodegenConstants.IS_INTEGER_EXT_NAME, Boolean.FALSE);
}
}
}
@@ -488,7 +497,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
}
if (this.collectionTypes.contains(typeMapping)) {
operation.isListContainer = true;
operation.getVendorExtensions().put(CodegenConstants.IS_LIST_CONTAINER_EXT_NAME, Boolean.TRUE);
operation.returnContainer = operation.returnType;
if (this.returnICollection && (
typeMapping.startsWith("List") ||
@@ -501,7 +510,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
}
} else {
operation.returnContainer = operation.returnType;
operation.isMapContainer = this.mapTypes.contains(typeMapping);
operation.getVendorExtensions().put(CodegenConstants.IS_MAP_CONTAINER_EXT_NAME, this.mapTypes.contains(typeMapping));
}
}
@@ -621,110 +630,67 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
/**
* Return the example value of the property
*
* @param p Swagger property object
* @param schema Schema property object
* @return string presentation of the example value of the property
*/
@Override
public String toExampleValue(Property p) {
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getExample() != null) {
return "\"" + dp.getExample().toString() + "\"";
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getExample() != null) {
return dp.getExample().toString();
}
} else if (p instanceof DateProperty) {
// TODO
} else if (p instanceof DateTimeProperty) {
// TODO
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getExample() != null) {
return dp.getExample().toString();
}
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getExample() != null) {
return dp.getExample().toString();
}
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getExample() != null) {
return dp.getExample().toString();
}
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getExample() != null) {
return dp.getExample().toString();
public String toExampleValue(Schema schema) {
if (schema instanceof StringSchema) {
if (schema.getExample() != null) {
return String.format("\"%s\"", schema.getExample().toString());
}
}
if (schema instanceof DateSchema || schema instanceof DateTimeSchema) {
// TODO still...
return null;
} else {
if (schema.getExample() != null) {
return schema.getExample().toString();
}
}
return null;
}
/**
* Return the default value of the property
*
* @param p Swagger property object
* @param schema Schema property object
* @return string presentation of the default value of the property
*/
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
String _default = dp.getDefault();
if (dp.getEnum() == null) {
return "\"" + _default + "\"";
public String toDefaultValue(Schema schema) {
if (schema instanceof StringSchema) {
if (schema.getDefault() != null) {
String _default = schema.getDefault().toString();
if (schema.getEnum() == null) {
return String.format("\"%s\"", _default);
} else {
// convert to enum var name later in postProcessModels
return _default;
}
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof DateProperty) {
// TODO
} else if (p instanceof DateTimeProperty) {
// TODO
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) {
return String.format("%1$sF", dp.getDefault());
}
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
if (schema instanceof DateSchema || schema instanceof DateTimeSchema) {
// TODO still...
return null;
} else {
if (schema.getDefault() != null) {
if(SchemaTypeUtil.INTEGER64_FORMAT.equals(schema.getFormat())) {
return String.format("%1$sF", schema.getDefault());
}
return schema.getDefault().toString();
}
}
return null;
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String swaggerType = super.getSchemaType(propertySchema);
String type;
if (swaggerType == null) {
swaggerType = ""; // set swagger type to empty string if null
swaggerType = StringUtils.EMPTY; // set swagger type to empty string if null
}
// TODO avoid using toLowerCase as typeMapping should be case-sensitive
@@ -740,18 +706,15 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<string, " + getTypeDeclaration(inner) + ">";
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s<%s>", getSchemaType(propertySchema), getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s<string, %s>", getSchemaType(propertySchema), getTypeDeclaration(inner));
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override

View File

@@ -3,7 +3,7 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.models.properties.Property;
import io.swagger.v3.oas.models.media.Schema;
import java.util.Arrays;
@@ -155,8 +155,8 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg
}
@Override
public CodegenProperty fromProperty(String name, Property p) {
CodegenProperty property = super.fromProperty(name, p);
public CodegenProperty fromProperty(String name, Schema propertySchema) {
CodegenProperty property = super.fromProperty(name, propertySchema);
String nameInCamelCase = property.nameInCamelCase;
if (nameInCamelCase.length() > 1) {
nameInCamelCase = sanitizeName(Character.toLowerCase(nameInCamelCase.charAt(0)) + nameInCamelCase.substring(1));

View File

@@ -1,6 +1,9 @@
package io.swagger.codegen.languages;
import static com.google.common.base.Strings.isNullOrEmpty;
import static io.swagger.codegen.CodegenConstants.HAS_ENUMS_EXT_NAME;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
import java.util.Arrays;
import java.util.Collection;
@@ -12,6 +15,9 @@ import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.ArrayListMultimap;
@@ -26,11 +32,7 @@ import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.utils.ModelUtils;
import io.swagger.models.Model;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.util.Json;
import io.swagger.v3.core.util.Json;
public abstract class AbstractEiffelCodegen extends DefaultCodegen implements CodegenConfig {
@@ -264,40 +266,38 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return "LIST [" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
public String getTypeDeclaration(Schema schema) {
if (schema instanceof ArraySchema) {
Schema inner = ((ArraySchema) schema).getItems();
return String.format("LIST [%s]", getTypeDeclaration(inner));
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (schema instanceof MapSchema && hasSchemaProperties(schema)) {
Schema inner = (Schema) schema.getAdditionalProperties();
return String.format("%s[%s]", getSchemaType(schema), getTypeDeclaration(inner));
}
// return super.getTypeDeclaration(p);
// Not using the supertype invocation, because we want to UpperCamelize
// the type.
String swaggerType = getSwaggerType(p);
if (typeMapping.containsKey(swaggerType)) {
return typeMapping.get(swaggerType);
String schemaType = getSchemaType(schema);
if (typeMapping.containsKey(schemaType)) {
return typeMapping.get(schemaType);
}
if (typeMapping.containsValue(swaggerType)) {
return swaggerType;
if (typeMapping.containsValue(schemaType)) {
return schemaType;
}
if (languageSpecificPrimitives.contains(swaggerType)) {
return swaggerType;
if (languageSpecificPrimitives.contains(schemaType)) {
return schemaType;
}
return toModelName(swaggerType);
return toModelName(schemaType);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String swaggerType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
@@ -446,17 +446,18 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
for (final CodegenProperty parentProperty : parent.vars) {
final CodegenProperty duplicatedByParent = childPropertiesByName.get(parentProperty.name);
if (duplicatedByParent != null) {
duplicatedByParent.isInherited = true;
duplicatedByParent.getVendorExtensions().put(CodegenConstants.IS_INHERITED_EXT_NAME, Boolean.TRUE);
}
}
}
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
if (allDefinitions != null && codegenModel.parentSchema != null && codegenModel.hasEnums) {
final Model parentModel = allDefinitions.get(codegenModel.parentSchema);
public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allSchemas) {
CodegenModel codegenModel = super.fromModel(name, schema, allSchemas);
boolean hasEnums = getBooleanValue(codegenModel, HAS_ENUMS_EXT_NAME);
if (allSchemas != null && codegenModel.parentSchema != null && hasEnums) {
final Schema parentModel = allSchemas.get(codegenModel.parentSchema);
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel);
codegenModel = AbstractEiffelCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel);
}
@@ -471,7 +472,8 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
// Because the child models extend the parents, the enums will be available via the parent.
// Only bother with reconciliation if the parent model has enums.
if (!parentCodegenModel.hasEnums) {
boolean hasEnums = getBooleanValue(parentCodegenModel, HAS_ENUMS_EXT_NAME);
if (!hasEnums) {
return codegenModel;
}
@@ -483,13 +485,15 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
boolean removedChildEnum = false;
for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) {
// Look for enums
if (parentModelCodegenPropery.isEnum) {
boolean isEnum = getBooleanValue(parentModelCodegenPropery, IS_ENUM_EXT_NAME);
if (isEnum) {
// Now that we have found an enum in the parent class,
// and search the child class for the same enum.
Iterator<CodegenProperty> iterator = codegenProperties.iterator();
while (iterator.hasNext()) {
CodegenProperty codegenProperty = iterator.next();
if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) {
isEnum = getBooleanValue(codegenProperty, IS_ENUM_EXT_NAME);
if (isEnum && codegenProperty.equals(parentModelCodegenPropery)) {
// We found an enum in the child class that is
// a duplicate of the one in the parent, so remove it.
iterator.remove();
@@ -504,7 +508,7 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
int count = 0, numVars = codegenProperties.size();
for(CodegenProperty codegenProperty : codegenProperties) {
count += 1;
codegenProperty.hasMore = (count < numVars) ? true : false;
codegenProperty.getVendorExtensions().put(CodegenConstants.HAS_MORE_EXT_NAME, (count < numVars) ? true : false);
}
codegenModel.vars = codegenProperties;
}
@@ -536,21 +540,21 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
}
@Override
public String toInstantiationType(Property p) {
if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
Property additionalProperties2 = ap.getAdditionalProperties();
public String toInstantiationType(Schema schema) {
if (schema instanceof MapSchema && hasSchemaProperties(schema)) {
Schema additionalProperties2 = (Schema) schema.getAdditionalProperties();
String type = additionalProperties2.getType();
if (null == type) {
LOGGER.error("No Type defined for Additional Property " + additionalProperties2 + "\n" //
+ "\tIn Property: " + p);
+ "\tIn Property: " + schema);
}
String inner = toModelName(getSwaggerType(additionalProperties2));
return instantiationTypes.get("map") + " [" + inner + "]";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = toModelName(getSwaggerType(ap.getItems()));
return instantiationTypes.get("array") + " [" + inner + "]";
String inner = toModelName(getSchemaType(additionalProperties2));
return String.format("%s [%s]", instantiationTypes.get("map"), inner);
} else if (schema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) schema;
String inner = toModelName(getSchemaType(arraySchema.getItems()));
//return instantiationTypes.get("array") + " [" + inner + "]";
return String.format("%s [%s]", instantiationTypes.get("array"), inner);
} else {
return null;
}
@@ -583,7 +587,7 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
if (!languageSpecificPrimitives.contains(innerProperty.baseType)) {
property.complexType = innerProperty.baseType;
} else {
property.isPrimitiveType = true;
property.getVendorExtensions().put(CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME, Boolean.TRUE);
}
property.items = innerProperty;
// inner item is Enum

View File

@@ -1,15 +1,14 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.Swagger;
import io.swagger.util.Yaml;
import java.util.*;
import io.swagger.v3.core.util.Yaml;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
@@ -219,41 +218,41 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
}
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
public String getTypeDeclaration(Schema schema) {
if(schema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) schema;
Schema inner = arraySchema.getItems();
return "[]" + getTypeDeclaration(inner);
}
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
else if (schema instanceof MapSchema && hasSchemaProperties(schema)) {
MapSchema mapSchema = (MapSchema) schema;
Schema inner = (Schema) mapSchema.getAdditionalProperties();
return getSwaggerType(p) + "[string]" + getTypeDeclaration(inner);
return getSchemaType(schema) + "[string]" + getTypeDeclaration(inner);
}
//return super.getTypeDeclaration(p);
// Not using the supertype invocation, because we want to UpperCamelize
// the type.
String swaggerType = getSwaggerType(p);
if (typeMapping.containsKey(swaggerType)) {
return typeMapping.get(swaggerType);
String schemaType = getSchemaType(schema);
if (typeMapping.containsKey(schemaType)) {
return typeMapping.get(schemaType);
}
if(typeMapping.containsValue(swaggerType)) {
return swaggerType;
if(typeMapping.containsValue(schemaType)) {
return schemaType;
}
if(languageSpecificPrimitives.contains(swaggerType)) {
return swaggerType;
if(languageSpecificPrimitives.contains(schemaType)) {
return schemaType;
}
return toModelName(swaggerType);
return toModelName(schemaType);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema schema) {
String swaggerType = super.getSchemaType(schema);
String type = null;
if(typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
@@ -367,10 +366,10 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
Swagger swagger = (Swagger)objs.get("swagger");
if(swagger != null) {
OpenAPI openAPI = (OpenAPI)objs.get("openapi");
if(openAPI != null) {
try {
objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger));
objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(openAPI));
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}

View File

@@ -10,6 +10,22 @@ import java.util.ListIterator;
import java.util.Map;
import java.util.regex.Pattern;
import com.github.jknack.handlebars.Handlebars;
import io.swagger.codegen.languages.helpers.ExtensionHelper;
import io.swagger.codegen.languages.helpers.JavaHelper;
import io.swagger.codegen.languages.helpers.NoneExtensionHelper;
import io.swagger.codegen.utils.ModelUtils;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
@@ -26,24 +42,15 @@ import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.BodyParameter;
import io.swagger.models.parameters.FormParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import static io.swagger.codegen.CodegenConstants.HAS_ENUMS_EXT_NAME;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
/**
* new version of this class can be found on: https://github.com/swagger-api/swagger-codegen-templates
*/
@Deprecated
public abstract class AbstractJavaCodegen extends DefaultCodegen implements CodegenConfig {
static Logger LOGGER = LoggerFactory.getLogger(AbstractJavaCodegen.class);
@@ -89,11 +96,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
public AbstractJavaCodegen() {
super();
supportsInheritance = true;
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
apiTestTemplateFiles.put("api_test.mustache", ".java");
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
setReservedWordsLowerCase(
Arrays.asList(
@@ -180,6 +182,12 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
public void processOpts() {
super.processOpts();
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
apiTestTemplateFiles.put("api_test.mustache", ".java");
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
if (additionalProperties.containsKey(SUPPORT_JAVA6)) {
this.setSupportJava6(Boolean.valueOf(additionalProperties.get(SUPPORT_JAVA6).toString()));
}
@@ -612,27 +620,29 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) propertySchema;
Schema inner = arraySchema.getItems();
if (inner == null) {
LOGGER.warn(ap.getName() + "(array property) does not have a proper inner type defined");
LOGGER.warn(arraySchema.getName() + "(array property) does not have a proper inner type defined");
// TODO maybe better defaulting to StringProperty than returning null
return null;
}
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
if (inner == null) {
LOGGER.warn(mp.getName() + "(map property) does not have a proper inner type defined");
// TODO maybe better defaulting to StringProperty than returning null
return null;
return String.format("%s<%s>", getSchemaType(propertySchema), getTypeDeclaration(inner));
// return getSwaggerType(propertySchema) + "<" + getTypeDeclaration(inner) + ">";
} else if (propertySchema instanceof MapSchema || propertySchema.getAdditionalProperties() != null) {
if (hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
if (inner == null) {
LOGGER.warn(propertySchema.getName() + "(map property) does not have a proper inner type defined");
// TODO maybe better defaulting to StringProperty than returning null
return null;
}
return getSchemaType(propertySchema) + "<String, " + getTypeDeclaration(inner) + ">";
}
return getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">";
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override
@@ -644,20 +654,20 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
@Override
public String toDefaultValue(Property p) {
if (p instanceof ArrayProperty) {
final ArrayProperty ap = (ArrayProperty) p;
public String toDefaultValue(Schema schema) {
if (schema instanceof ArraySchema) {
final ArraySchema arraySchema = (ArraySchema) schema;
final String pattern;
if (fullJavaUtil) {
pattern = "new java.util.ArrayList<%s>()";
} else {
pattern = "new ArrayList<%s>()";
}
if (ap.getItems() == null) {
if (arraySchema.getItems() == null) {
return null;
}
String typeDeclaration = getTypeDeclaration(ap.getItems());
String typeDeclaration = getTypeDeclaration(arraySchema.getItems());
Object java8obj = additionalProperties.get("java8");
if (java8obj != null) {
Boolean java8 = Boolean.valueOf(java8obj.toString());
@@ -667,19 +677,18 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
return String.format(pattern, typeDeclaration);
} else if (p instanceof MapProperty) {
final MapProperty ap = (MapProperty) p;
} else if (schema instanceof MapSchema && hasSchemaProperties(schema)) {
final String pattern;
if (fullJavaUtil) {
pattern = "new java.util.HashMap<%s>()";
} else {
pattern = "new HashMap<%s>()";
}
if (ap.getAdditionalProperties() == null) {
if (schema.getAdditionalProperties() == null) {
return null;
}
String typeDeclaration = String.format("String, %s", getTypeDeclaration(ap.getAdditionalProperties()));
String typeDeclaration = String.format("String, %s", getTypeDeclaration((Schema) schema.getAdditionalProperties()));
Object java8obj = additionalProperties.get("java8");
if (java8obj != null) {
Boolean java8 = Boolean.valueOf(java8obj.toString());
@@ -689,50 +698,30 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
return String.format(pattern, typeDeclaration);
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
} else if (schema instanceof IntegerSchema) {
if (schema.getDefault() != null && SchemaTypeUtil.INTEGER64_FORMAT.equals(schema.getFormat())) {
return String.format("%sl", schema.getDefault().toString());
}
return "null";
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString()+"l";
} else if (schema instanceof NumberSchema) {
if (schema.getDefault() != null) {
if (schema.getDefault() != null && SchemaTypeUtil.FLOAT_FORMAT.equals(schema.getFormat())) {
return String.format("%sf", schema.getDefault().toString());
} else if (schema.getDefault() != null && SchemaTypeUtil.DOUBLE_FORMAT.equals(schema.getFormat())) {
return String.format("%sd", schema.getDefault().toString());
}
}
return "null";
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString() + "d";
}
return "null";
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString() + "f";
}
return "null";
} else if (p instanceof BooleanProperty) {
BooleanProperty bp = (BooleanProperty) p;
if (bp.getDefault() != null) {
return bp.getDefault().toString();
}
return "null";
} else if (p instanceof StringProperty) {
StringProperty sp = (StringProperty) p;
if (sp.getDefault() != null) {
String _default = sp.getDefault();
if (sp.getEnum() == null) {
return "\"" + escapeText(_default) + "\"";
} else if (schema instanceof StringSchema) {
if (schema.getDefault() != null) {
String _default = schema.getDefault().toString();
if (schema.getEnum() == null) {
return String.format("\"%s\"", escapeText(_default));
} else {
// convert to enum var name later in postProcessModels
return _default;
}
}
return "null";
}
return super.toDefaultValue(p);
return super.toDefaultValue(schema);
}
@Override
@@ -790,9 +779,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
if (example == null) {
example = "null";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
example = "Arrays.asList(" + example + ")";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME)) {
example = "new HashMap()";
}
@@ -800,17 +789,17 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
@Override
public String toExampleValue(Property p) {
if(p.getExample() != null) {
return escapeText(p.getExample().toString());
public String toExampleValue(Schema schemaProperty) {
if(schemaProperty.getExample() != null) {
return escapeText(schemaProperty.getExample().toString());
} else {
return super.toExampleValue(p);
return super.toExampleValue(schemaProperty);
}
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema schema) {
String swaggerType = super.getSchemaType(schema);
swaggerType = getAlias(swaggerType);
@@ -820,7 +809,11 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
if (null == swaggerType) {
LOGGER.error("No Type defined for Property " + p);
if (schema.getName() != null) {
LOGGER.error("No Type defined for Property " + schema.getName());
} else {
// LOGGER.error("No Type defined.", new Exception());
}
}
return toModelName(swaggerType);
}
@@ -845,8 +838,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allSchemas) {
CodegenModel codegenModel = super.fromModel(name, schema, allSchemas);
if(codegenModel.description != null) {
codegenModel.imports.add("ApiModel");
}
@@ -854,8 +847,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
codegenModel.imports.add("JsonSubTypes");
codegenModel.imports.add("JsonTypeInfo");
}
if (allDefinitions != null && codegenModel.parentSchema != null && codegenModel.hasEnums) {
final Model parentModel = allDefinitions.get(codegenModel.parentSchema);
boolean hasEnums = getBooleanValue(codegenModel, HAS_ENUMS_EXT_NAME);
if (allSchemas != null && codegenModel.parentSchema != null && hasEnums) {
final Schema parentModel = allSchemas.get(codegenModel.parentSchema);
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel);
codegenModel = AbstractJavaCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel);
}
@@ -883,7 +877,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
}
if(!BooleanUtils.toBoolean(model.isEnum)) {
boolean isEnum = getBooleanValue(model, IS_ENUM_EXT_NAME);
if(!BooleanUtils.toBoolean(isEnum)) {
// needed by all pojos, but not enums
model.imports.add("ApiModelProperty");
model.imports.add("ApiModel");
@@ -931,60 +926,61 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
@Override
public void preprocessSwagger(Swagger swagger) {
if (swagger == null || swagger.getPaths() == null){
public void preprocessOpenAPI(OpenAPI openAPI) {
if (openAPI == null || openAPI.getPaths() == null){
return;
}
for (String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if (path.getOperations() == null){
continue;
}
for (Operation operation : path.getOperations()) {
boolean hasFormParameters = false;
boolean hasBodyParameters = false;
for (Parameter parameter : operation.getParameters()) {
if (parameter instanceof FormParameter) {
hasFormParameters = true;
}
if (parameter instanceof BodyParameter) {
hasBodyParameters = true;
}
for (String pathname : openAPI.getPaths().keySet()) {
PathItem pathItem = openAPI.getPaths().get(pathname);
for (Operation operation : pathItem.readOperations()) {
if (operation == null) {
continue;
}
if (hasBodyParameters || hasFormParameters){
String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json";
String contentType = operation.getConsumes() == null || operation.getConsumes().isEmpty() ? defaultContentType : operation.getConsumes().get(0);
operation.setVendorExtension("x-contentType", contentType);
//only add content-Type if its no a GET-Method
if (!operation.equals(pathItem.getGet())) {
String contentType = getContentType(operation.getRequestBody());
if (StringUtils.isBlank(contentType)) {
contentType = DEFAULT_CONTENT_TYPE;
}
operation.addExtension("x-contentType", contentType);
}
String accepts = getAccept(operation);
operation.setVendorExtension("x-accepts", accepts);
operation.addExtension("x-accepts", accepts);
}
}
}
private static String getAccept(Operation operation) {
String accepts = null;
String defaultContentType = "application/json";
if (operation.getProduces() != null && !operation.getProduces().isEmpty()) {
StringBuilder sb = new StringBuilder();
for (String produces : operation.getProduces()) {
if (defaultContentType.equalsIgnoreCase(produces)) {
accepts = defaultContentType;
break;
} else {
if (sb.length() > 0) {
sb.append(",");
if (operation != null && operation.getResponses() != null && !operation.getResponses().isEmpty()) {
StringBuilder mediaTypeBuilder = new StringBuilder();
responseLoop:
for (ApiResponse response : operation.getResponses().values()) {
if(response.getContent() == null || response.getContent().isEmpty()) {
continue;
}
mediaTypeLoop:
for (String mediaTypeKey : response.getContent().keySet()) {
if (DEFAULT_CONTENT_TYPE.equalsIgnoreCase(mediaTypeKey)) {
accepts = DEFAULT_CONTENT_TYPE;
break responseLoop;
} else {
if (mediaTypeBuilder.length() > 0) {
mediaTypeBuilder.append(",");
}
mediaTypeBuilder.append(mediaTypeKey);
}
sb.append(produces);
}
}
if (accepts == null) {
accepts = sb.toString();
accepts = mediaTypeBuilder.toString();
}
} else {
accepts = defaultContentType;
accepts = DEFAULT_CONTENT_TYPE;
}
return accepts;
}
@@ -1053,8 +1049,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Schema> schemas, OpenAPI openAPI) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, schemas, openAPI);
op.path = sanitizePath(op.path);
return op;
}
@@ -1067,7 +1063,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
// Because the child models extend the parents, the enums will be available via the parent.
// Only bother with reconciliation if the parent model has enums.
if (!parentCodegenModel.hasEnums) {
boolean hasEnums = getBooleanValue(parentCodegenModel, HAS_ENUMS_EXT_NAME);
if (!hasEnums) {
return codegenModel;
}
@@ -1079,13 +1076,15 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
boolean removedChildEnum = false;
for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) {
// Look for enums
if (parentModelCodegenPropery.isEnum) {
boolean isEnum = getBooleanValue(parentModelCodegenPropery, IS_ENUM_EXT_NAME);
if (isEnum) {
// Now that we have found an enum in the parent class,
// and search the child class for the same enum.
Iterator<CodegenProperty> iterator = codegenProperties.iterator();
while (iterator.hasNext()) {
CodegenProperty codegenProperty = iterator.next();
if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) {
isEnum = getBooleanValue(codegenProperty, IS_ENUM_EXT_NAME);
if (isEnum && codegenProperty.equals(parentModelCodegenPropery)) {
// We found an enum in the child class that is
// a duplicate of the one in the parent, so remove it.
iterator.remove();
@@ -1100,7 +1099,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
int count = 0, numVars = codegenProperties.size();
for(CodegenProperty codegenProperty : codegenProperties) {
count += 1;
codegenProperty.hasMore = (count < numVars) ? true : false;
codegenProperty.getVendorExtensions().put(CodegenConstants.HAS_MORE_EXT_NAME, (count < numVars) ? true : false);
}
codegenModel.vars = codegenProperties;
}
@@ -1289,4 +1288,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
return tag;
}
@Override
public void addHandlebarHelpers(Handlebars handlebars) {
super.addHandlebarHelpers(handlebars);
handlebars.registerHelpers(new JavaHelper());
}
}

View File

@@ -1,14 +1,5 @@
package io.swagger.codegen.languages;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
@@ -16,10 +7,22 @@ import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.codegen.languages.features.UseGenericResponseFeatures;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import io.swagger.codegen.utils.ModelUtils;
import io.swagger.codegen.utils.URLPathUtil;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen implements BeanValidationFeatures {
/**
@@ -86,46 +89,37 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
}
@Override
public void preprocessSwagger(Swagger swagger) {
if ( "/".equals(swagger.getBasePath()) ) {
swagger.setBasePath("");
}
public void preprocessOpenAPI(OpenAPI openAPI) {
if (!this.additionalProperties.containsKey("serverPort")) {
final String host = swagger.getHost();
final URL urlInfo = URLPathUtil.getServerURL(openAPI);
String port = "8080"; // Default value for a JEE Server
if ( host != null ) {
String[] parts = host.split(":");
if ( parts.length > 1 ) {
port = parts[1];
}
if ( urlInfo != null && urlInfo.getPort() != 0) {
port = String.valueOf(urlInfo.getPort());
}
this.additionalProperties.put("serverPort", port);
}
if ( swagger.getPaths() != null ) {
for ( String pathname : swagger.getPaths().keySet() ) {
Path path = swagger.getPath(pathname);
if ( path.getOperations() != null ) {
for ( Operation operation : path.getOperations() ) {
if ( operation.getTags() != null ) {
List<Map<String, String>> tags = new ArrayList<Map<String, String>>();
for ( String tag : operation.getTags() ) {
Map<String, String> value = new HashMap<String, String>();
value.put("tag", tag);
value.put("hasMore", "true");
tags.add(value);
}
if ( tags.size() > 0 ) {
tags.get(tags.size() - 1).remove("hasMore");
}
if ( operation.getTags().size() > 0 ) {
String tag = operation.getTags().get(0);
operation.setTags(Arrays.asList(tag));
}
operation.setVendorExtension("x-tags", tags);
if (openAPI.getPaths() != null) {
for (String pathname : openAPI.getPaths().keySet()) {
PathItem pathItem = openAPI.getPaths().get(pathname);
final Operation[] operations = ModelUtils.createOperationArray(pathItem);
for (Operation operation : operations) {
if (operation != null && operation.getTags() != null) {
List<Map<String, String>> tags = new ArrayList<Map<String, String>>();
for (String tag : operation.getTags()) {
Map<String, String> value = new HashMap<String, String>();
value.put("tag", tag);
value.put("hasMore", "true");
tags.add(value);
}
if (tags.size() > 0) {
tags.get(tags.size() - 1).remove("hasMore");
}
if (operation.getTags().size() > 0) {
String tag = operation.getTags().get(0);
operation.setTags(Arrays.asList(tag));
}
operation.addExtension("x-tags", tags);
}
}
}
@@ -140,11 +134,12 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
@SuppressWarnings("unchecked")
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for ( CodegenOperation operation : ops ) {
if (operation.hasConsumes == Boolean.TRUE) {
boolean hasConsumes = getBooleanValue(operation, CodegenConstants.HAS_CONSUMES_EXT_NAME);
if (hasConsumes) {
Map<String, String> firstType = operation.consumes.get(0);
if (firstType != null) {
if ("multipart/form-data".equals(firstType.get("mediaType"))) {
operation.isMultipart = Boolean.TRUE;
operation.getVendorExtensions().put(CodegenConstants.IS_MULTIPART_EXT_NAME, Boolean.TRUE);
}
}
}

View File

@@ -6,10 +6,7 @@ import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.*;
import java.io.File;
import java.util.Arrays;
@@ -19,11 +16,20 @@ import java.util.Map;
import java.util.HashSet;
import java.util.regex.Matcher;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public abstract class AbstractPhpCodegen extends DefaultCodegen implements CodegenConfig {
static Logger LOGGER = LoggerFactory.getLogger(AbstractPhpCodegen.class);
@@ -300,21 +306,20 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
public String getTypeDeclaration(Schema schema) {
if (schema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) schema;
Schema inner = arraySchema.getItems();
return getTypeDeclaration(inner) + "[]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
} else if (p instanceof RefProperty) {
String type = super.getTypeDeclaration(p);
} else if (schema instanceof MapSchema && hasSchemaProperties(schema)) {
Schema inner = (Schema) schema.getAdditionalProperties();
return String.format("%s[string,%s]", getSchemaType(schema), getTypeDeclaration(inner));
} else if (StringUtils.isNotBlank(schema.get$ref())) {
String type = super.getTypeDeclaration(schema);
return (!languageSpecificPrimitives.contains(type))
? "\\" + modelPackage + "\\" + type : type;
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(schema);
}
@Override
@@ -326,8 +331,8 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String swaggerType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
@@ -467,47 +472,21 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
/**
* Return the default value of the property
*
* @param p Swagger property object
* @param schema Schema property object
* @return string presentation of the default value of the property
*/
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
return "'" + dp.getDefault() + "'";
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof DateProperty) {
// TODO
} else if (p instanceof DateTimeProperty) {
// TODO
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
public String toDefaultValue(Schema schema) {
if (schema instanceof StringSchema && schema.getDefault() != null) {
return String.format("'%s'", schema.getDefault());
}
if (schema instanceof DateSchema || schema instanceof DateTimeSchema) {
// TODO still...
return null;
}
if (schema.getDefault() != null) {
return schema.getDefault().toString();
}
return null;
}
@@ -567,9 +546,9 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
if (example == null) {
example = "NULL";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
example = "array(" + example + ")";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME)) {
example = "array('key' => " + example + ")";
}

View File

@@ -11,17 +11,9 @@ import com.samskivert.mustache.Mustache;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.lang3.StringUtils;
public abstract class AbstractScalaCodegen extends DefaultCodegen {
@@ -154,76 +146,53 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]";
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s[%s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s[String, %s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String swaggerType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
} else {
if (languageSpecificPrimitives.contains(type))
return (type);
} else
type = swaggerType;
}
return toModelName(type);
return type;
}
@Override
public String toInstantiationType(Property p) {
if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return instantiationTypes.get("map") + "[String, " + inner + "]";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return instantiationTypes.get("array") + "[" + inner + "]";
public String toInstantiationType(Schema schemaProperty) {
if (schemaProperty instanceof MapSchema && hasSchemaProperties(schemaProperty)) {
String inner = getSchemaType((Schema) schemaProperty.getAdditionalProperties());
return String.format("%s[%s]", instantiationTypes.get("map"), inner);
} else if (schemaProperty instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) schemaProperty;
String inner = getSchemaType(arraySchema.getItems());
return String.format("%s[%s]", instantiationTypes.get("array"), inner);
} else {
return null;
}
}
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
return "null";
} else if (p instanceof BooleanProperty) {
return "null";
} else if (p instanceof DateProperty) {
return "null";
} else if (p instanceof DateTimeProperty) {
return "null";
} else if (p instanceof DoubleProperty) {
return "null";
} else if (p instanceof FloatProperty) {
return "null";
} else if (p instanceof IntegerProperty) {
return "null";
} else if (p instanceof LongProperty) {
return "null";
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "new HashMap[String, " + inner + "]() ";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "new ListBuffer[" + inner + "]() ";
public String toDefaultValue(Schema propertySchema) {
if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
String inner = getSchemaType((Schema) propertySchema.getAdditionalProperties());
return String.format("new HashMap[String, %s]()", inner);
} else if(propertySchema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) propertySchema;
String inner = getSchemaType(arraySchema.getItems());
return String.format("new ListBuffer[%s]()", inner);
} else {
return "null";
}

View File

@@ -1,5 +1,21 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
@@ -10,25 +26,8 @@ import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FileProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig {
private static final String UNDEFINED_VALUE = "undefined";
@@ -219,67 +218,51 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return "{ [key: string]: "+ getTypeDeclaration(inner) + "; }";
} else if (p instanceof FileProperty) {
return "any";
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s<%s>", getSchemaType(propertySchema), getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("{ [key, string]: %s;}", getTypeDeclaration(inner));
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
StringProperty sp = (StringProperty) p;
public String toDefaultValue(Schema propertySchema) {
if (propertySchema instanceof StringSchema) {
StringSchema sp = (StringSchema) propertySchema;
if (sp.getDefault() != null) {
return "\"" + sp.getDefault() + "\"";
}
return UNDEFINED_VALUE;
} else if (p instanceof BooleanProperty) {
} else if (propertySchema instanceof BooleanSchema) {
return UNDEFINED_VALUE;
} else if (p instanceof DateProperty) {
} else if (propertySchema instanceof DateSchema) {
return UNDEFINED_VALUE;
} else if (p instanceof DateTimeProperty) {
} else if (propertySchema instanceof DateTimeSchema) {
return UNDEFINED_VALUE;
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
} else if (propertySchema instanceof NumberSchema) {
NumberSchema dp = (NumberSchema) propertySchema;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
return UNDEFINED_VALUE;
} else if (p instanceof FloatProperty) {
FloatProperty fp = (FloatProperty) p;
if (fp.getDefault() != null) {
return fp.getDefault().toString();
}
return UNDEFINED_VALUE;
} else if (p instanceof IntegerProperty) {
IntegerProperty ip = (IntegerProperty) p;
} else if (propertySchema instanceof IntegerSchema) {
IntegerSchema ip = (IntegerSchema) propertySchema;
if (ip.getDefault() != null) {
return ip.getDefault().toString();
}
return UNDEFINED_VALUE;
} else if (p instanceof LongProperty) {
LongProperty lp = (LongProperty) p;
if (lp.getDefault() != null) {
return lp.getDefault().toString();
}
return UNDEFINED_VALUE;
} else {
return UNDEFINED_VALUE;
}
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema schema) {
String swaggerType = super.getSchemaType(schema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
@@ -406,7 +389,8 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
cm.imports = new TreeSet(cm.imports);
for (CodegenProperty var : cm.vars) {
// name enum with model name, e.g. StatuEnum => Pet.StatusEnum
if (Boolean.TRUE.equals(var.isEnum)) {
boolean isEnum = getBooleanValue(var, IS_ENUM_EXT_NAME);
if (Boolean.TRUE.equals(isEnum)) {
var.datatypeWithEnum = var.datatypeWithEnum.replace(var.enumName, cm.classname + "." + var.enumName);
}
}

View File

@@ -1,12 +1,41 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.FileSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.MediaType;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.responses.ApiResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.Writer;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.codegen.*;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig {
@@ -67,24 +96,22 @@ public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig {
additionalProperties.put("packageDir", "client");
additionalProperties.put("mainName", "client");
additionalProperties.put(CodegenConstants.PROJECT_NAME, projectName);
String names[] = this.modelPackage.split("\\.");
String pkgName = names[0];
additionalProperties.put("packageLevel1", pkgName);
supportingFiles.add(new SupportingFile("package-spec-level1.mustache", null,
"src" + File.separator + toFilename(names[0]) + ".ads"));
"src" + File.separator + toFilename(names[0]) + ".ads"));
if (names.length > 1) {
String fileName = toFilename(names[0]) + "-" + toFilename(names[1]) + ".ads";
pkgName = names[0] + "." + names[1];
additionalProperties.put("packageLevel2", pkgName);
supportingFiles.add(new SupportingFile("package-spec-level2.mustache", null,
"src" + File.separator + fileName));
"src" + File.separator + fileName));
}
pkgName = this.modelPackage;
supportingFiles.add(new SupportingFile("client.mustache", null,
"src" + File.separator + toFilename(pkgName) + "-client.adb"));
"src" + File.separator + toFilename(pkgName) + "-client.adb"));
additionalProperties.put("packageName", toFilename(pkgName));
// add lambda for mustache templates
additionalProperties.put("lambdaAdaComment", new Mustache.Lambda() {
@Override
@@ -94,6 +121,7 @@ public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig {
writer.write(content.replaceAll("\n", "\n -- "));
}
});
}
@Override
@@ -105,4 +133,215 @@ public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig {
public String modelFileFolder() {
return outputFolder + "/model/" + modelPackage().replace('.', File.separatorChar);
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle
* escaping those terms here. This logic is only called if a variable
* matches the reserved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "p_" + name; // add an underscore to the name
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
/**
* Optional - type declaration. This is a String which is used by the
* templates to instantiate your types. There is typically special handling
* for different property types
*
* @return a string value used as the `dataType` field for model templates,
* `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Schema propertySchema) {
String swaggerType = getSchemaType(propertySchema);
if (propertySchema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) propertySchema;
return String.format("%s_Vectors.Vector", getTypeDeclaration(arraySchema.getItems()));
}
if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
return String.format("Swagger._Map", getTypeDeclaration((Schema) propertySchema.getAdditionalProperties()));
}
if (typeMapping.containsKey(swaggerType)) {
return typeMapping.get(swaggerType);
}
// LOGGER.info("Swagger type " + swaggerType);
if (languageSpecificPrimitives.contains(swaggerType)) {
return swaggerType;
}
String modelType = toModelName(swaggerType);
if (propertySchema instanceof StringSchema || propertySchema instanceof DateSchema
|| propertySchema instanceof DateTimeSchema|| propertySchema instanceof FileSchema
|| languageSpecificPrimitives.contains(modelType)) {
return modelType;
}
return modelPackage + ".Models." + modelType;
}
/**
* Overrides postProcessParameter to add a vendor extension "x-is-model-type".
* This boolean indicates that the parameter comes from the model package.
*
* @param parameter CodegenParameter object to be processed.
*/
@Override
public void postProcessParameter(CodegenParameter parameter){
// Give the base class a chance to process
super.postProcessParameter(parameter);
boolean isModel = parameter.dataType.startsWith(modelPackage);
boolean isPrimitiveType = getBooleanValue(parameter, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME);
boolean isDate = getBooleanValue(parameter, CodegenConstants.IS_DATE_TIME_EXT_NAME);
boolean isString = getBooleanValue(parameter, CodegenConstants.IS_STRING_EXT_NAME);
boolean isContainer = getBooleanValue(parameter, CodegenConstants.IS_CONTAINER_EXT_NAME);
boolean isFile = getBooleanValue(parameter, CodegenConstants.IS_FILE_EXT_NAME);
if (!isModel && !isPrimitiveType && !isDate && !isString && !isContainer && !isFile) {
isModel = true;
}
parameter.vendorExtensions.put("x-is-model-type", isModel);
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Schema> definitions, OpenAPI openAPI) {
CodegenOperation codegenOperation = super.fromOperation(path, httpMethod, operation, definitions, openAPI);
if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
ApiResponse response = findMethodResponse(operation.getResponses());
if (response != null && response.getContent() != null && !response.getContent().isEmpty()) {
final MediaType mediaType = new ArrayList<>(response.getContent().values()).get(0);
if (mediaType.getSchema() != null) {
CodegenProperty cm = fromProperty("response", mediaType.getSchema());
codegenOperation.vendorExtensions.put("x-codegen-response", cm);
if(cm.datatype == "HttpContent") {
codegenOperation.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
}
}
}
}
return codegenOperation;
}
@SuppressWarnings("unchecked")
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op1 : operationList) {
op1.vendorExtensions.put("x-has-uniq-produces", postProcessMediaTypes(op1.produces) == 1);
op1.vendorExtensions.put("x-has-uniq-consumes", postProcessMediaTypes(op1.consumes) == 1);
op1.vendorExtensions.put("x-has-notes", op1.notes.length() > 0);
}
return objs;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// Collect the model dependencies.
List<Map<String, Object>> models = (List<Map<String, Object>>) objs.get("models");
for (Map<String, Object> model : models) {
Object v = model.get("model");
if (v instanceof CodegenModel) {
CodegenModel m = (CodegenModel) v;
List<String> d = new ArrayList<String>();
for (CodegenProperty p : m.allVars) {
boolean isModel = false;
CodegenProperty item = p;
if (getBooleanValue(p, CodegenConstants.IS_CONTAINER_EXT_NAME)) {
item = p.items;
}
boolean isString = getBooleanValue(p, CodegenConstants.IS_STRING_EXT_NAME);
boolean isPrimitiveType = getBooleanValue(p, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME);
boolean isContainer = getBooleanValue(p, CodegenConstants.IS_CONTAINER_EXT_NAME);
boolean isInteger = getBooleanValue(p, CodegenConstants.IS_INTEGER_EXT_NAME);
if (item != null && !isString && !isPrimitiveType && !isContainer && !isInteger) {
if (!d.contains(item.datatype)) {
// LOGGER.info("Model " + m.name + " uses " + p.datatype);
d.add(item.datatype);
isModel = true;
}
}
p.vendorExtensions.put("x-is-model-type", isModel);
}
modelDepends.put(m.name, d);
orderedModels.add(model);
}
}
// Sort the models according to dependencies so that model that depend
// on others appear at end of the list.
final Map<String, List<String>> deps = modelDepends;
Collections.sort(orderedModels, new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> lhs, Map<String, Object> rhs) {
Object v = lhs.get("model");
String lhsName = ((CodegenModel) v).name;
v = rhs.get("model");
String rhsName = ((CodegenModel) v).name;
List<String> lhsList = deps.get(lhsName);
List<String> rhsList = deps.get(rhsName);
if (lhsList == rhsList) {
// LOGGER.info("First compare " + lhsName + "<" + rhsName);
return lhsName.compareTo(rhsName);
}
// Put models without dependencies first.
if (lhsList == null) {
// LOGGER.info(" Empty " + lhsName + ", no check " + rhsName);
return -1;
}
if (rhsList == null) {
// LOGGER.info(" No check " + lhsName + ", empty " + rhsName);
return 1;
}
// Put models that depend on another after.
if (lhsList.contains(rhsName)) {
// LOGGER.info(" LSH " + lhsName + " uses " + rhsName);
return 1;
}
if (rhsList.contains(lhsName)) {
// LOGGER.info(" RHS " + rhsName + " uses " + lhsName);
return -1;
}
// Put models with less dependencies first.
if (lhsList.size() < rhsList.size()) {
// LOGGER.info(" LSH size " + lhsName + " < RHS size " + rhsName);
return -1;
}
if (lhsList.size() > rhsList.size()) {
// LOGGER.info(" LSH size " + lhsName + " > RHS size " + rhsName);
return 1;
}
// Sort models on their name.
// LOGGER.info("Compare " + lhsName + "<" + rhsName);
return lhsName.compareTo(rhsName);
}
});
/* for (Map<String, Object> model : orderedModels) {
Object v = model.get("model");
if (v instanceof CodegenModel) {
CodegenModel m = (CodegenModel) v;
LOGGER.info("Order: " + m.name);
}
}*/
return postProcessModelsEnum(objs);
}
}

View File

@@ -3,8 +3,6 @@ package io.swagger.codegen.languages;
import com.google.common.base.CaseFormat;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
@@ -13,18 +11,10 @@ import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.CodegenSecurity;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.auth.SecuritySchemeDefinition;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -41,6 +31,8 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class AkkaScalaClientCodegen extends AbstractScalaCodegen implements CodegenConfig {
protected String mainPackage = "io.swagger.client";
protected String groupId = "io.swagger";
@@ -195,7 +187,7 @@ public class AkkaScalaClientCodegen extends AbstractScalaCodegen implements Code
}
@Override
public List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes) {
public List<CodegenSecurity> fromSecurity(Map<String, SecurityScheme> schemes) {
final List<CodegenSecurity> codegenSecurities = super.fromSecurity(schemes);
if (!removeOAuthSecurities) {
return codegenSecurities;
@@ -205,7 +197,7 @@ public class AkkaScalaClientCodegen extends AbstractScalaCodegen implements Code
Iterator<CodegenSecurity> it = codegenSecurities.iterator();
while (it.hasNext()) {
final CodegenSecurity security = it.next();
if (security.isOAuth) {
if (getBooleanValue(security, CodegenConstants.IS_OAUTH_EXT_NAME)) {
it.remove();
}
}
@@ -213,7 +205,7 @@ public class AkkaScalaClientCodegen extends AbstractScalaCodegen implements Code
it = codegenSecurities.iterator();
while (it.hasNext()) {
final CodegenSecurity security = it.next();
security.hasMore = it.hasNext();
security.getVendorExtensions().put(CodegenConstants.HAS_MORE_EXT_NAME, it.hasNext());
}
if (codegenSecurities.isEmpty()) {
@@ -248,34 +240,14 @@ public class AkkaScalaClientCodegen extends AbstractScalaCodegen implements Code
}
@Override
public String toDefaultValue(Property p) {
if (!p.getRequired()) {
return "None";
}
if (p instanceof StringProperty) {
return "null";
} else if (p instanceof BooleanProperty) {
return "null";
} else if (p instanceof DateProperty) {
return "null";
} else if (p instanceof DateTimeProperty) {
return "null";
} else if (p instanceof DoubleProperty) {
return "null";
} else if (p instanceof FloatProperty) {
return "null";
} else if (p instanceof IntegerProperty) {
return "null";
} else if (p instanceof LongProperty) {
return "null";
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "Map[String, " + inner + "].empty ";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "Seq[" + inner + "].empty ";
public String toDefaultValue(Schema propertySchema) {
if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
String inner = getSchemaType((Schema) propertySchema.getAdditionalProperties());
return String.format("Map[String, %s].empty", inner);
} else if(propertySchema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) propertySchema;
String inner = getSchemaType(arraySchema.getItems());
return String.format("Seq[%s].empty", inner);
} else {
return "null";
}

View File

@@ -7,17 +7,18 @@ import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(AndroidClientCodegen.class);
@@ -166,23 +167,20 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">";
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s<%s>", getSchemaType(propertySchema), getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s<String, %s>", getSchemaType(propertySchema), getTypeDeclaration(inner));
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String swaggerType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
@@ -321,9 +319,9 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
if (example == null) {
example = "null";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
example = "Arrays.asList(" + example + ")";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME)) {
example = "new HashMap()";
}

View File

@@ -1,18 +1,39 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Info;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.*;
import io.swagger.codegen.utils.ModelUtils;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.ByteArraySchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.EmailSchema;
import io.swagger.v3.oas.models.media.FileSchema;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import io.swagger.v3.oas.models.media.ObjectSchema;
import io.swagger.v3.oas.models.media.PasswordSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.media.UUIDSchema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class ApexClientCodegen extends AbstractJavaCodegen {
private static final String CLASS_PREFIX = "classPrefix";
@@ -144,32 +165,32 @@ public class ApexClientCodegen extends AbstractJavaCodegen {
}
@Override
public String toDefaultValue(Property p) {
public String toDefaultValue(Schema propertySchema) {
String out = null;
if (p instanceof ArrayProperty) {
Property inner = ((ArrayProperty) p).getItems();
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
out = String.format(
"new List<%s>()",
inner == null ? "Object" : getTypeDeclaration(inner)
);
} else if (p instanceof BooleanProperty) {
} else if (propertySchema instanceof BooleanSchema) {
// true => "true", false => "false", null => "null"
out = String.valueOf(((BooleanProperty) p).getDefault());
} else if (p instanceof LongProperty) {
Long def = ((LongProperty) p).getDefault();
out = String.valueOf(((BooleanSchema) propertySchema).getDefault());
} else if (propertySchema instanceof IntegerSchema && SchemaTypeUtil.INTEGER64_FORMAT.equals(propertySchema.getFormat())) {
Long def = propertySchema.getDefault() != null ? Long.valueOf(propertySchema.getDefault().toString()) : null;
out = def == null ? out : def.toString() + "L";
} else if (p instanceof MapProperty) {
Property inner = ((MapProperty) p).getAdditionalProperties();
} else if (propertySchema instanceof MapSchema) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
String s = inner == null ? "Object" : getTypeDeclaration(inner);
out = String.format("new Map<String, %s>()", s);
} else if (p instanceof StringProperty) {
StringProperty sp = (StringProperty) p;
String def = sp.getDefault();
} else if (propertySchema instanceof StringSchema) {
StringSchema schema = (StringSchema) propertySchema;
String def = schema.getDefault();
if (def != null) {
out = sp.getEnum() == null ? String.format("'%s'", escapeText(def)) : def;
out = schema.getEnum() == null ? String.format("'%s'", escapeText(def)) : def;
}
} else {
out = super.toDefaultValue(p);
out = super.toDefaultValue(propertySchema);
}
// we'll skip over null defaults in the model template to avoid redundant initialization
@@ -177,30 +198,30 @@ public class ApexClientCodegen extends AbstractJavaCodegen {
}
@Override
public void setParameterExampleValue(CodegenParameter p) {
if (Boolean.TRUE.equals(p.isLong)) {
p.example = "2147483648L";
} else if (Boolean.TRUE.equals(p.isFile)) {
p.example = "Blob.valueOf('Sample text file\\nContents')";
} else if (Boolean.TRUE.equals(p.isDate)) {
p.example = "Date.newInstance(1960, 2, 17)";
} else if (Boolean.TRUE.equals(p.isDateTime)) {
p.example = "Datetime.newInstanceGmt(2013, 11, 12, 3, 3, 3)";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
p.example = "new " + p.dataType + "{" + p.items.example + "}";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
p.example = "new " + p.dataType + "{" + p.items.example + "}";
} else if (Boolean.TRUE.equals(p.isString)) {
p.example = "'" + p.example + "'";
} else if ("".equals(p.example) || p.example == null) {
public void setParameterExampleValue(CodegenParameter parameter) {
if (getBooleanValue(parameter, CodegenConstants.IS_LONG_EXT_NAME)) {
parameter.example = "2147483648L";
} else if (getBooleanValue(parameter, CodegenConstants.IS_FILE_EXT_NAME)) {
parameter.example = "Blob.valueOf('Sample text file\\nContents')";
} else if (getBooleanValue(parameter, CodegenConstants.IS_DATE_EXT_NAME)) {
parameter.example = "Date.newInstance(1960, 2, 17)";
} else if (getBooleanValue(parameter, CodegenConstants.IS_DATE_TIME_EXT_NAME)) {
parameter.example = "Datetime.newInstanceGmt(2013, 11, 12, 3, 3, 3)";
} else if (getBooleanValue(parameter, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
parameter.example = "new " + parameter.dataType + "{" + parameter.items.example + "}";
} else if (getBooleanValue(parameter, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME)) {
parameter.example = "new " + parameter.dataType + "{" + parameter.items.example + "}";
} else if (getBooleanValue(parameter, CodegenConstants.IS_STRING_EXT_NAME)) {
parameter.example = "'" + parameter.example + "'";
} else if ("".equals(parameter.example) || parameter.example == null) {
// Get an example object from the generated model
p.example = p.dataType + ".getExample()";
parameter.example = parameter.dataType + ".getExample()";
}
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel cm = super.fromModel(name, model, allDefinitions);
public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allSchemas) {
CodegenModel cm = super.fromModel(name, schema, allSchemas);
if (cm.interfaces == null) {
cm.interfaces = new ArrayList<String>();
}
@@ -219,6 +240,10 @@ public class ApexClientCodegen extends AbstractJavaCodegen {
}
}
if (cm.vendorExtensions == null) {
cm.vendorExtensions = new HashMap<>();
}
cm.vendorExtensions.put("hasPropertyMappings", !propertyMappings.isEmpty());
cm.vendorExtensions.put("hasDefaultValues", hasDefaultValues);
cm.vendorExtensions.put("propertyMappings", propertyMappings);
@@ -231,7 +256,8 @@ public class ApexClientCodegen extends AbstractJavaCodegen {
@Override
public void postProcessParameter(CodegenParameter parameter) {
if (parameter.isBodyParam && parameter.isListContainer) {
if (getBooleanValue(parameter, CodegenConstants.IS_BODY_PARAM_EXT_NAME)
&& getBooleanValue(parameter, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
// items of array bodyParams are being nested an extra level too deep for some reason
parameter.items = parameter.items.items;
setParameterExampleValue(parameter);
@@ -239,8 +265,8 @@ public class ApexClientCodegen extends AbstractJavaCodegen {
}
@Override
public void preprocessSwagger(Swagger swagger) {
Info info = swagger.getInfo();
public void preprocessOpenAPI(OpenAPI openAPI) {
Info info = openAPI.getInfo();
String calloutLabel = info.getTitle();
additionalProperties.put("calloutLabel", calloutLabel);
String sanitized = sanitizeName(calloutLabel);
@@ -258,40 +284,18 @@ public class ApexClientCodegen extends AbstractJavaCodegen {
}
@Override
public CodegenOperation fromOperation(String path,
String httpMethod,
Operation operation,
Map<String, Model> definitions,
Swagger swagger) {
Boolean hasFormParams = false;
for (Parameter p : operation.getParameters()) {
if ("formData".equals(p.getIn())) {
hasFormParams = true;
break;
}
}
// only support serialization into JSON and urlencoded forms for now
operation.setConsumes(
Collections.singletonList(hasFormParams
? "application/x-www-form-urlencoded"
: "application/json"));
// only support deserialization from JSON for now
operation.setProduces(Collections.singletonList("application/json"));
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Schema> definitions, OpenAPI openAPI) {
CodegenOperation op = super.fromOperation(
path, httpMethod, operation, definitions, swagger);
path, httpMethod, operation, definitions, openAPI);
if (op.getHasExamples()) {
// prepare examples for Apex test classes
Property responseProperty = findMethodResponse(operation.getResponses()).getSchema();
String deserializedExample = toExampleValue(responseProperty);
ApiResponse responseProperty = findMethodResponse(operation.getResponses());
String deserializedExample = toExampleValue(getSchemaFromResponse(responseProperty));
for (Map<String, String> example : op.examples) {
example.put("example", escapeText(example.get("example")));
example.put("deserializedExample", deserializedExample);
}
}
return op;
}
@@ -356,91 +360,98 @@ public class ApexClientCodegen extends AbstractJavaCodegen {
}
@Override
public String toExampleValue(Property p) {
if (p == null) {
return "";
public String toExampleValue(Schema propertySchema) {
if (propertySchema == null) {
return StringUtils.EMPTY;
}
Object obj = p.getExample();
String example = obj == null ? "" : obj.toString();
if (p instanceof ArrayProperty) {
example = "new " + getTypeDeclaration(p) + "{" + toExampleValue(
((ArrayProperty) p).getItems()) + "}";
} else if (p instanceof BooleanProperty) {
Object obj = propertySchema.getExample();
String example = obj == null ? StringUtils.EMPTY : obj.toString();
if (propertySchema instanceof ArraySchema) {
example = String.format("new %s {%s}", getTypeDeclaration(propertySchema), toExampleValue(((ArraySchema) propertySchema).getItems()));
} else if (propertySchema instanceof BooleanSchema) {
example = String.valueOf(!"false".equals(example));
} else if (p instanceof ByteArrayProperty) {
} else if (propertySchema instanceof ByteArraySchema) {
if (example.isEmpty()) {
example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu";
}
((ByteArrayProperty) p).setExample(example);
example = "EncodingUtil.base64Decode('" + example + "')";
} else if (p instanceof DateProperty) {
if (example.matches("^\\d{4}(-\\d{2}){2}")) {
example = example.substring(0, 10).replaceAll("-0?", ", ");
} else if (example.isEmpty()) {
example = "2000, 1, 23";
propertySchema.setExample(example);
example = String.format("EncodingUtil.base64Decode('%s')", example);
} else if (propertySchema instanceof DateSchema) {
if (propertySchema.getExample() != null) {
example = DateFormatUtils.format((Date) propertySchema.getExample(), DateFormatUtils.ISO_DATE_FORMAT.getPattern());
if (example.matches("^\\d{4}(-\\d{2}){2}")) {
example = example.substring(0, 10).replaceAll("-0?", ", ");
} else if (example.isEmpty()) {
example = "2000, 1, 23";
} else {
LOGGER.warn(String.format("The example provided for property '%s' is not a valid RFC3339 date. Defaulting to '2000-01-23'. [%s]", propertySchema
.getName(), example));
example = "2000, 1, 23";
}
} else {
LOGGER.warn(String.format("The example provided for property '%s' is not a valid RFC3339 date. Defaulting to '2000-01-23'. [%s]", p
.getName(), example));
example = "2000, 1, 23";
}
example = "Date.newInstance(" + example + ")";
} else if (p instanceof DateTimeProperty) {
if (example.matches("^\\d{4}([-T:]\\d{2}){5}.+")) {
example = example.substring(0, 19).replaceAll("[-T:]0?", ", ");
} else if (example.isEmpty()) {
example = "2000, 1, 23, 4, 56, 7";
example = String.format("Date.newInstance(%s)", example);
} else if (propertySchema instanceof DateTimeSchema) {
if (propertySchema.getExample() != null) {
example = DateFormatUtils.format((Date) propertySchema.getExample(), "yyyy-MM-dd'T'HH:mm:ss.SS'Z'");
if (example.matches("^\\d{4}([-T:]\\d{2}){5}.+")) {
example = example.substring(0, 19).replaceAll("[-T:]0?", ", ");
} else if (example.isEmpty()) {
example = "2000, 1, 23, 4, 56, 7";
} else {
LOGGER.warn(String.format("The example provided for property '%s' is not a valid RFC3339 datetime. Defaulting to '2000-01-23T04-56-07Z'. [%s]", propertySchema
.getName(), example));
example = "2000, 1, 23, 4, 56, 7";
}
} else {
LOGGER.warn(String.format("The example provided for property '%s' is not a valid RFC3339 datetime. Defaulting to '2000-01-23T04-56-07Z'. [%s]", p
.getName(), example));
example = "2000, 1, 23, 4, 56, 7";
}
example = "Datetime.newInstanceGmt(" + example + ")";
} else if (p instanceof DecimalProperty) {
example = String.format("Datetime.newInstanceGmt(%s)", example);
} else if (propertySchema instanceof NumberSchema) {
example = example.replaceAll("[^-0-9.]", "");
example = example.isEmpty() ? "1.3579" : example;
} else if (p instanceof FileProperty) {
} else if (propertySchema instanceof FileSchema) {
if (example.isEmpty()) {
example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu";
((FileProperty) p).setExample(example);
propertySchema.setExample(example);
}
example = "EncodingUtil.base64Decode(" + example + ")";
} else if (p instanceof EmailProperty) {
example = String.format("EncodingUtil.base64Decode(%s)", example);
} else if (propertySchema instanceof EmailSchema) {
if (example.isEmpty()) {
example = "example@example.com";
((EmailProperty) p).setExample(example);
((EmailSchema) propertySchema).setExample(example);
}
example = "'" + example + "'";
} else if (p instanceof LongProperty) {
} else if (propertySchema instanceof IntegerSchema && SchemaTypeUtil.INTEGER64_FORMAT.equals(propertySchema.getFormat())) {
example = example.isEmpty() ? "123456789L" : example + "L";
} else if (p instanceof MapProperty) {
example = "new " + getTypeDeclaration(p) + "{'key'=>" + toExampleValue(
((MapProperty) p).getAdditionalProperties()) + "}";
} else if (p instanceof ObjectProperty) {
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
example = String.format("new %s {'key'=>%s}", getTypeDeclaration(propertySchema), toExampleValue((Schema) propertySchema.getAdditionalProperties()));
} else if (propertySchema instanceof ObjectSchema) {
example = example.isEmpty() ? "null" : example;
} else if (p instanceof PasswordProperty) {
} else if (propertySchema instanceof PasswordSchema) {
example = example.isEmpty() ? "password123" : escapeText(example);
((PasswordProperty) p).setExample(example);
example = "'" + example + "'";
} else if (p instanceof RefProperty) {
example = getTypeDeclaration(p) + ".getExample()";
} else if (p instanceof StringProperty) {
StringProperty sp = (StringProperty) p;
List<String> enums = sp.getEnum();
propertySchema.setExample(example);
example = String.format("'%s'", example);
} else if (StringUtils.isNotBlank(propertySchema.get$ref()) ) {
example = getTypeDeclaration(propertySchema) + ".getExample()";
} else if (propertySchema instanceof StringSchema) {
List<String> enums = propertySchema.getEnum();
if (enums != null && example.isEmpty()) {
example = enums.get(0);
sp.setExample(example);
propertySchema.setExample(example);
} else if (example.isEmpty()) {
example = "aeiou";
} else {
example = escapeText(example);
sp.setExample(example);
propertySchema.setExample(example);
}
example = "'" + example + "'";
} else if (p instanceof UUIDProperty) {
} else if (propertySchema instanceof UUIDSchema) {
example = example.isEmpty()
? "'046b6c7f-0b8a-43b9-b35d-6489e6daee91'"
: "'" + escapeText(example) + "'";
} else if (p instanceof BaseIntegerProperty) {
: String.format("'%s'", escapeText(example));
} else if (propertySchema instanceof IntegerSchema) {
example = example.matches("^-?\\d+$") ? example : "123";
}
@@ -452,10 +463,10 @@ public class ApexClientCodegen extends AbstractJavaCodegen {
return camelize(classPrefix + super.toApiName(name));
}
@Override
public void updateCodegenPropertyEnum(CodegenProperty var) {
super.updateCodegenPropertyEnum(var);
if (var.isEnum && var.example != null) {
ModelUtils.updateCodegenPropertyEnum(var);
boolean isEnum = getBooleanValue(var, IS_ENUM_EXT_NAME);
if (isEnum && var.example != null) {
String example = var.example.replace("'", "");
example = toEnumVarName(example, var.datatype);
var.example = toEnumDefaultValue(example, var.datatypeWithEnum);

View File

@@ -1,20 +1,15 @@
package io.swagger.codegen.languages;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.samskivert.mustache.Mustache;
import io.swagger.codegen.*;
import io.swagger.models.*;
import io.swagger.util.Json;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import java.util.Map.Entry;
import java.util.Arrays;
import static java.util.UUID.randomUUID;
@@ -162,21 +157,6 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + "Models";
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
Swagger swagger = (Swagger)objs.get("swagger");
if(swagger != null) {
try {
objs.put("swagger-json", Json.pretty().writeValueAsString(swagger).replace("\r\n", "\n"));
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}
}
return super.postProcessSupportingFileData(objs);
}
@Override
protected void processOperation(CodegenOperation operation) {
super.processOperation(operation);

View File

@@ -5,20 +5,18 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.BodyParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.parameters.SerializableParameter;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import org.apache.commons.lang3.StringEscapeUtils;
import java.util.Arrays;
@@ -27,6 +25,8 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String apiVersion = "1.0.0";
@@ -361,20 +361,18 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
* @return a string value used as the `dataType` field for model templates,
* `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
@Override
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s[%s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s[String, %s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
}
return super.getTypeDeclaration(propertySchema);
}
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
/**
* Optional - swagger type conversion. This is used to map swagger types in
@@ -382,11 +380,11 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
* complex models if there is not a mapping.
*
* @return a string value of the type or complex model for this property
* @see io.swagger.models.properties.Property
* @see io.swagger.v3.oas.models.media.Schema
*/
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String swaggerType = super.getSchemaType(propertySchema);
String type = null;
if(typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
@@ -399,80 +397,6 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
return toModelName(type);
}
/**
* Convert Swagger Parameter object to Codegen Parameter object
*
* @param param Swagger parameter object
* @param imports set of imports for library/package/module
* @return Codegen Parameter object
*/
@Override
public CodegenParameter fromParameter(Parameter param, Set<String> imports) {
CodegenParameter p = super.fromParameter(param, imports);
if(param instanceof BodyParameter) {
Model model = ((BodyParameter)param).getSchema();
}
else if(param instanceof SerializableParameter) {
/**
* Currently it's not possible to specify in the codegen other collection
* formats than 'multi'
*/
SerializableParameter sparam = (SerializableParameter)param;
if( sparam.getCollectionFormat() != null
&& !sparam.getCollectionFormat().isEmpty()) {
String collectionFormat = sparam.getCollectionFormat();
if(sparam.isExclusiveMaximum()!=null && sparam.isExclusiveMaximum()) {
p.vendorExtensions.put("x-codegen-collection-max-items",
sparam.getMaxItems());
}
if(sparam.isExclusiveMinimum()!=null && sparam.isExclusiveMinimum()) {
p.vendorExtensions.put("x-codegen-collection-min-items",
sparam.getMinItems());
}
if( (collectionFormat.equals("multi"))
&& (param.getIn().equals("query")) ) {
/**
* 'multi' is only supported for query parameters
*/
p.vendorExtensions.put("x-codegen-collection-multi", true);
}
else if(collectionFormat.equals("csv")) {
p.vendorExtensions.put("x-codegen-collection-csv", true);
}
else if(collectionFormat.equals("ssv")) {
p.vendorExtensions.put("x-codegen-collection-ssv", true);
}
else if(collectionFormat.equals("tsv")) {
p.vendorExtensions.put("x-codegen-collection-tsv", true);
}
else if(collectionFormat.equals("pipes")) {
p.vendorExtensions.put("x-codegen-collection-pipes", true);
}
else {
/** Unsupported collection format */
}
}
}
return p;
}
/**
* Override with any special text escaping logic
*/
@@ -584,33 +508,25 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public CodegenOperation fromOperation(String path, String httpMethod,
Operation operation,
Map<String, Model> definitions,
Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation,
definitions, swagger);
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Schema> schemas, OpenAPI openAPI) {
CodegenOperation codegenOperation = super.fromOperation(path, httpMethod, operation, schemas, openAPI);
/**
* Check if the operation has a Bash codegen specific description
* for help
*/
if(op.vendorExtensions.containsKey("x-bash-codegen-description")) {
String bash_description
= (String)op.vendorExtensions.get("x-bash-codegen-description");
op.vendorExtensions.put("x-bash-codegen-description",
escapeText(bash_description));
if(codegenOperation.vendorExtensions.containsKey("x-bash-codegen-description")) {
String bashDescription = (String) codegenOperation.vendorExtensions.get("x-bash-codegen-description");
codegenOperation.vendorExtensions.put("x-bash-codegen-description", escapeText(bashDescription));
}
/**
* Check if operation has an 'x-code-samples' vendor extension with
* Shell example
*/
if(op.vendorExtensions.containsKey("x-code-samples")) {
if(codegenOperation.vendorExtensions.containsKey("x-code-samples")) {
List codesamples = (List)op.vendorExtensions.get("x-code-samples");
List codesamples = (List)codegenOperation.vendorExtensions.get("x-code-samples");
for (Object codesample : codesamples) {
if(codesample instanceof ObjectNode) {
@@ -618,7 +534,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
if ((codesample_object.get("lang").asText()).equals("Shell")) {
op.vendorExtensions.put("x-bash-codegen-sample",
codegenOperation.vendorExtensions.put("x-bash-codegen-sample",
escapeUnsafeCharacters(
codesample_object.get("source").asText()));
@@ -626,23 +542,21 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
}
}
}
for (CodegenParameter p : op.bodyParams) {
if(p.dataType != null && definitions.get(p.dataType) != null) {
boolean containsContentType = containsContentType(getConsumesInfo(operation), DEFAULT_CONTENT_TYPE);
for (CodegenParameter p : codegenOperation.bodyParams) {
if(p.dataType != null && schemas.get(p.dataType) != null) {
/**
* If the operation produces Json and has nonempty example
* try to reformat it.
*/
if(operation.getConsumes() != null
&& operation.getConsumes().contains("application/json")
&& definitions.get(p.dataType).getExample() != null) {
if(containsContentType && schemas.get(p.dataType).getExample() != null) {
ObjectMapper mapper = new ObjectMapper();
try {
p.vendorExtensions.put(
"x-codegen-body-example",
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(
definitions.get(p.dataType).getExample()));
schemas.get(p.dataType).getExample()));
}
catch(JsonProcessingException e) {
e.printStackTrace();
@@ -654,45 +568,30 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
*/
p.vendorExtensions.put(
"x-codegen-body-example",
definitions.get(p.dataType).getExample());
schemas.get(p.dataType).getExample());
}
}
}
return op;
return codegenOperation;
}
/**
* Preprocess original properties from the Swagger definition where necessary.
*
* @param swagger [description]
* @param openAPI [description]
*/
@Override
public void preprocessSwagger(Swagger swagger) {
super.preprocessSwagger(swagger);
if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath("");
}
if(swagger.getInfo() != null
&& swagger.getInfo().getVendorExtensions()!=null) {
String bash_codegen_app_description
= (String)swagger.getInfo().getVendorExtensions()
.get("x-bash-codegen-description");
if(bash_codegen_app_description != null) {
bash_codegen_app_description
= escapeText(bash_codegen_app_description);
additionalProperties.put("x-bash-codegen-app-description",
bash_codegen_app_description);
public void preprocessOpenAPI(OpenAPI openAPI) {
super.preprocessOpenAPI(openAPI);
if(openAPI.getInfo() != null && openAPI.getInfo().getExtensions() != null) {
String bashCodegenAppDescription = (String) openAPI.getInfo().getExtensions().get("x-bash-codegen-description");
if(bashCodegenAppDescription != null) {
bashCodegenAppDescription = escapeText(bashCodegenAppDescription);
additionalProperties.put("x-bash-codegen-app-description", bashCodegenAppDescription);
}
}
}
@Override
@@ -751,13 +650,24 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
if (example == null) {
example = "NULL";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
example = "[" + example + "]";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME)) {
example = "{'key': " + example + "}";
}
p.example = example;
}
private boolean containsContentType(Set<String> mediaTypeKeys, String contentType){
if (mediaTypeKeys == null || mediaTypeKeys.isEmpty()) {
return Boolean.FALSE;
}
for (String mediaTypeKey : mediaTypeKeys) {
if(mediaTypeKey.equals(contentType)) {
return Boolean.TRUE;
}
}
return Boolean.FALSE;
}
}

View File

@@ -1,15 +1,29 @@
package io.swagger.codegen.languages;
import com.google.common.collect.ImmutableMap;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.media.Schema;
import com.samskivert.mustache.Mustache;
import io.swagger.codegen.*;
import io.swagger.models.Model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static io.swagger.codegen.CodegenConstants.HAS_ENUMS_EXT_NAME;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
import static org.apache.commons.lang3.StringUtils.isEmpty;
public class CSharpClientCodegen extends AbstractCSharpCodegen {
@@ -502,13 +516,14 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, schema, allDefinitions);
if (allDefinitions != null && codegenModel != null && codegenModel.parent != null) {
final Model parentModel = allDefinitions.get(toModelName(codegenModel.parent));
final Schema parentModel = allDefinitions.get(toModelName(codegenModel.parent));
if (parentModel != null) {
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel);
if (codegenModel.hasEnums) {
boolean hasEnums = getBooleanValue(codegenModel, HAS_ENUMS_EXT_NAME);
if (hasEnums) {
codegenModel = this.reconcileInlineEnums(codegenModel, parentCodegenModel);
}
@@ -528,8 +543,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
// helper list of parentVars simplifies templating
if (!propertyHash.containsKey(property.name)) {
final CodegenProperty parentVar = property.clone();
parentVar.isInherited = true;
parentVar.hasMore = true;
parentVar.getVendorExtensions().put(CodegenConstants.IS_INHERITED_EXT_NAME, Boolean.TRUE);
parentVar.getVendorExtensions().put(CodegenConstants.HAS_MORE_EXT_NAME, Boolean.TRUE);
last = parentVar;
LOGGER.info("adding parent variable {}", property.name);
codegenModel.parentVars.add(parentVar);
@@ -537,7 +552,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
}
if (last != null) {
last.hasMore = false;
last.getVendorExtensions().put(CodegenConstants.HAS_MORE_EXT_NAME, Boolean.FALSE);
}
}
}
@@ -631,7 +646,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
// Because the child models extend the parents, the enums will be available via the parent.
// Only bother with reconciliation if the parent model has enums.
if (parentCodegenModel.hasEnums) {
boolean hasEnums = getBooleanValue(parentCodegenModel, HAS_ENUMS_EXT_NAME);
if (hasEnums) {
// Get the properties for the parent and child models
final List<CodegenProperty> parentModelCodegenProperties = parentCodegenModel.vars;
@@ -641,13 +657,15 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
boolean removedChildEnum = false;
for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) {
// Look for enums
if (parentModelCodegenPropery.isEnum) {
boolean isEnum = getBooleanValue(parentModelCodegenPropery, IS_ENUM_EXT_NAME);
if (isEnum) {
// Now that we have found an enum in the parent class,
// and search the child class for the same enum.
Iterator<CodegenProperty> iterator = codegenProperties.iterator();
while (iterator.hasNext()) {
CodegenProperty codegenProperty = iterator.next();
if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) {
isEnum = getBooleanValue(codegenProperty, IS_ENUM_EXT_NAME);
if (isEnum && codegenProperty.equals(parentModelCodegenPropery)) {
// We found an enum in the child class that is
// a duplicate of the one in the parent, so remove it.
iterator.remove();
@@ -662,7 +680,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
int count = 0, numVars = codegenProperties.size();
for (CodegenProperty codegenProperty : codegenProperties) {
count += 1;
codegenProperty.hasMore = count < numVars;
codegenProperty.getVendorExtensions().put(CodegenConstants.HAS_MORE_EXT_NAME, count < numVars);
}
codegenModel.vars = codegenProperties;
}

View File

@@ -7,10 +7,10 @@ import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Contact;
import io.swagger.models.Info;
import io.swagger.models.License;
import io.swagger.models.Swagger;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
@@ -71,8 +71,8 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi
}
@Override
public void preprocessSwagger(Swagger swagger) {
super.preprocessSwagger(swagger);
public void preprocessOpenAPI(OpenAPI openAPI) {
super.preprocessOpenAPI(openAPI);
if (additionalProperties.containsKey(PROJECT_NAME)) {
projectName = ((String) additionalProperties.get(PROJECT_NAME));
@@ -87,8 +87,8 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi
baseNamespace = ((String) additionalProperties.get(BASE_NAMESPACE));
}
if (swagger.getInfo() != null) {
Info info = swagger.getInfo();
if (openAPI.getInfo() != null) {
Info info = openAPI.getInfo();
if (projectName == null && info.getTitle() != null) {
// when projectName is not specified, generate it from info.title
projectName = dashize(info.getTitle());

View File

@@ -1,9 +1,15 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import java.util.HashMap;
import java.util.HashSet;
@@ -69,18 +75,15 @@ public class ConfluenceWikiGenerator extends DefaultCodegen implements CodegenCo
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]";
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s[%s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s[String, %s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override

View File

@@ -1,6 +1,7 @@
package io.swagger.codegen.languages;
import static com.google.common.base.Strings.isNullOrEmpty;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
import java.util.Arrays;
import java.util.Collection;
@@ -21,25 +22,21 @@ import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.utils.ModelUtils;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Response;
import io.swagger.models.Swagger;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BaseIntegerProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DecimalProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FileProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.FileSchema;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.apache.commons.lang3.StringUtils;
public class CppRestClientCodegen extends AbstractCppCodegen {
@@ -216,42 +213,38 @@ public class CppRestClientCodegen extends AbstractCppCodegen {
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allSchemas) {
CodegenModel codegenModel = super.fromModel(name, schema, allSchemas);
Set<String> oldImports = codegenModel.imports;
codegenModel.imports = new HashSet<String>();
codegenModel.imports = new HashSet<>();
for (String imp : oldImports) {
String newImp = toModelImport(imp);
if (!newImp.isEmpty()) {
codegenModel.imports.add(newImp);
}
}
return codegenModel;
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation,
Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);
Map<String, Schema> schemas, OpenAPI openAPI) {
final CodegenOperation codegenOperation = super.fromOperation(path, httpMethod, operation, schemas, openAPI);
if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
Response methodResponse = findMethodResponse(operation.getResponses());
if (methodResponse != null) {
if (methodResponse.getSchema() != null) {
CodegenProperty cm = fromProperty("response", methodResponse.getSchema());
op.vendorExtensions.put("x-codegen-response", cm);
if(cm.datatype == "HttpContent")
{
op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
}
ApiResponse methodResponse = findMethodResponse(operation.getResponses());
if (methodResponse == null) {
return codegenOperation;
}
final Schema responseSchema = getSchemaFromResponse(methodResponse);
if (responseSchema != null) {
CodegenProperty cm = fromProperty("response", responseSchema);
codegenOperation.vendorExtensions.put("x-codegen-response", cm);
if (cm.datatype == "HttpContent") {
codegenOperation.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
}
}
}
return op;
return codegenOperation;
}
@Override
@@ -291,62 +284,55 @@ public class CppRestClientCodegen extends AbstractCppCodegen {
* `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
String swaggerType = getSwaggerType(p);
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
public String getTypeDeclaration(Schema propertySchema) {
String schemaType = getSchemaType(propertySchema);
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s<%s>", schemaType, getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s<utility::string_t, %s>", schemaType, getTypeDeclaration(inner));
}
if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<utility::string_t, " + getTypeDeclaration(inner) + ">";
if (propertySchema instanceof StringSchema || propertySchema instanceof DateSchema
|| propertySchema instanceof DateTimeSchema || propertySchema instanceof FileSchema
|| languageSpecificPrimitives.contains(schemaType)) {
return toModelName(schemaType);
}
if (p instanceof StringProperty || p instanceof DateProperty
|| p instanceof DateTimeProperty || p instanceof FileProperty
|| languageSpecificPrimitives.contains(swaggerType)) {
return toModelName(swaggerType);
}
return "std::shared_ptr<" + swaggerType + ">";
return "std::shared_ptr<" + schemaType + ">";
}
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
public String toDefaultValue(Schema propertySchema) {
if (propertySchema instanceof StringSchema) {
return "utility::conversions::to_string_t(\"\")";
} else if (p instanceof BooleanProperty) {
} else if (propertySchema instanceof BooleanSchema) {
return "false";
} else if (p instanceof DateProperty) {
} else if (propertySchema instanceof DateSchema) {
return "utility::datetime()";
} else if (p instanceof DateTimeProperty) {
} else if (propertySchema instanceof DateTimeSchema) {
return "utility::datetime()";
} else if (p instanceof DoubleProperty) {
return "0.0";
} else if (p instanceof FloatProperty) {
return "0.0f";
} else if (p instanceof LongProperty) {
return "0L";
} else if (p instanceof IntegerProperty || p instanceof BaseIntegerProperty) {
return "0";
} else if (p instanceof DecimalProperty) {
return "0.0";
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "std::map<utility::string_t, " + inner + ">()";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
if (!languageSpecificPrimitives.contains(inner)) {
inner = "std::shared_ptr<" + inner + ">";
} else if (propertySchema instanceof NumberSchema) {
if(SchemaTypeUtil.FLOAT_FORMAT.equals(propertySchema.getFormat())) {
return "0.0f";
}
return "std::vector<" + inner + ">()";
} else if (p instanceof RefProperty) {
RefProperty rp = (RefProperty) p;
return "new " + toModelName(rp.getSimpleRef()) + "()";
return "0.0";
} else if (propertySchema instanceof IntegerSchema) {
if(SchemaTypeUtil.INTEGER64_FORMAT.equals(propertySchema.getFormat())) {
return "0L";
}
return "0";
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
String inner = getSchemaType((Schema) propertySchema.getAdditionalProperties());
return String.format("std::map<utility::string_t, %s>()", inner);
} else if (propertySchema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) propertySchema;
String inner = getSchemaType(arraySchema.getItems());
if (!languageSpecificPrimitives.contains(inner)) {
inner = String.format("std::shared_ptr<%s>", inner);
}
return String.format("std::vector<%s>()", inner);
} else if (StringUtils.isNotBlank(propertySchema.get$ref())) {
return String.format("new %s()", toModelName(propertySchema.get$ref()));
}
return "nullptr";
}
@@ -355,9 +341,9 @@ public class CppRestClientCodegen extends AbstractCppCodegen {
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
boolean isPrimitiveType = parameter.isPrimitiveType == Boolean.TRUE;
boolean isListContainer = parameter.isListContainer == Boolean.TRUE;
boolean isString = parameter.isString == Boolean.TRUE;
boolean isPrimitiveType = getBooleanValue(parameter, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME);
boolean isListContainer = getBooleanValue(parameter, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME);
boolean isString = getBooleanValue(parameter, CodegenConstants.IS_STRING_EXT_NAME);
if (!isPrimitiveType && !isListContainer && !isString && !parameter.dataType.startsWith("std::shared_ptr")) {
parameter.dataType = "std::shared_ptr<" + parameter.dataType + ">";
@@ -370,11 +356,11 @@ public class CppRestClientCodegen extends AbstractCppCodegen {
* into complex models if there is not a mapping.
*
* @return a string value of the type or complex model for this property
* @see io.swagger.models.properties.Property
* @see io.swagger.v3.oas.models.media.Schema
*/
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String swaggerType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
@@ -441,7 +427,7 @@ public class CppRestClientCodegen extends AbstractCppCodegen {
for (final CodegenProperty parentProperty : parent.vars) {
final CodegenProperty duplicatedByParent = childPropertiesByName.get(parentProperty.name);
if (duplicatedByParent != null) {
duplicatedByParent.isInherited = true;
duplicatedByParent.getVendorExtensions().put(CodegenConstants.IS_INHERITED_EXT_NAME, Boolean.TRUE);
}
}
}

View File

@@ -8,10 +8,10 @@ import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Model;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.codegen.utils.ModelUtils;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import java.io.File;
import java.util.ArrayList;
@@ -21,6 +21,9 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String BROWSER_CLIENT = "browserClient";
public static final String PUB_NAME = "pubName";
@@ -275,33 +278,30 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String toDefaultValue(Property p) {
if (p instanceof MapProperty) {
public String toDefaultValue(Schema propertySchema) {
if (propertySchema instanceof MapSchema) {
return "{}";
} else if (p instanceof ArrayProperty) {
} else if (propertySchema instanceof ArraySchema) {
return "[]";
}
return super.toDefaultValue(p);
return super.toDefaultValue(propertySchema);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">";
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s<%s>", getSchemaType(propertySchema), getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s<String, %s>", getSchemaType(propertySchema), getTypeDeclaration(inner));
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String swaggerType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
@@ -328,7 +328,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
boolean succes = buildEnumFromVendorExtension(cm) ||
buildEnumFromValues(cm);
for (CodegenProperty var : cm.vars) {
updateCodegenPropertyEnum(var);
ModelUtils.updateCodegenPropertyEnum(var);
}
}
return objs;
@@ -340,14 +340,15 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
* @return {@code true} if the enum was built
*/
private boolean buildEnumFromValues(CodegenModel cm) {
if (!cm.isEnum || cm.allowableValues == null) {
boolean isEnum = getBooleanValue(cm, IS_ENUM_EXT_NAME);
if (!isEnum || cm.allowableValues == null) {
return false;
}
Map<String, Object> allowableValues = cm.allowableValues;
List<Object> values = (List<Object>) allowableValues.get("values");
List<Map<String, String>> enumVars =
new ArrayList<Map<String, String>>();
String commonPrefix = findCommonPrefixOfVars(values);
String commonPrefix = ModelUtils.findCommonPrefixOfVars(values);
int truncateIdx = commonPrefix.length();
for (Object value : values) {
Map<String, String> enumVar = new HashMap<String, String>();
@@ -374,7 +375,8 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
* @return {@code true} if the enum was built
*/
private boolean buildEnumFromVendorExtension(CodegenModel cm) {
if (!cm.isEnum || cm.allowableValues == null ||
boolean isEnum = getBooleanValue(cm, IS_ENUM_EXT_NAME);
if (!isEnum || cm.allowableValues == null ||
!useEnumExtension ||
!cm.vendorExtensions.containsKey("x-enum-values")) {
return false;

View File

@@ -2,11 +2,34 @@ package io.swagger.codegen.languages;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.models.Info;
import io.swagger.models.Model;
import io.swagger.models.Swagger;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BinarySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.ByteArraySchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.EmailSchema;
import io.swagger.v3.oas.models.media.FileSchema;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import io.swagger.v3.oas.models.media.ObjectSchema;
import io.swagger.v3.oas.models.media.PasswordSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.media.UUIDSchema;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
@@ -15,6 +38,8 @@ import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String apiVersion = "1.0.0";
protected String moduleName;
@@ -209,8 +234,8 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
}
@Override
public void preprocessSwagger(Swagger swagger) {
Info info = swagger.getInfo();
public void preprocessOpenAPI(OpenAPI openAPI) {
Info info = openAPI.getInfo();
if (moduleName == null) {
if (info.getTitle() != null) {
// default to the appName (from title field)
@@ -263,11 +288,12 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
eco.setPathTemplateNames(pathTemplateNames);
// detect multipart form types
if (eco.hasConsumes == Boolean.TRUE) {
boolean hasConsumes = getBooleanValue(eco, CodegenConstants.HAS_CONSUMES_EXT_NAME);
if (hasConsumes == Boolean.TRUE) {
Map<String, String> firstType = eco.consumes.get(0);
if (firstType != null) {
if ("multipart/form-data".equals(firstType.get("mediaType"))) {
eco.isMultipart = Boolean.TRUE;
eco.getVendorExtensions().put(CodegenConstants.IS_MULTIPART_EXT_NAME, Boolean.TRUE);
}
}
}
@@ -279,8 +305,8 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel cm = super.fromModel(name, model, allDefinitions);
public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allSchemas) {
CodegenModel cm = super.fromModel(name, schema, allSchemas);
return new ExtendedCodegenModel(cm);
}
@@ -416,7 +442,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
* @return a string value used as the `dataType` field for model templates, `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
public String getTypeDeclaration(Schema propertySchema) {
// SubClasses of AbstractProperty
//
// ArrayProperty
@@ -440,56 +466,40 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
// BooleanProperty
// RefProperty
// FileProperty
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
if (propertySchema instanceof ArraySchema) {
ArraySchema ap = (ArraySchema) propertySchema;
Schema inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return "%{optional(String.t) => " + getTypeDeclaration(inner) + "}";
} else if (p instanceof PasswordProperty) {
} else if (propertySchema instanceof PasswordSchema
|| propertySchema instanceof EmailSchema
|| propertySchema instanceof StringSchema
|| propertySchema instanceof UUIDSchema
|| propertySchema instanceof FileSchema
) {
return "String.t";
} else if (p instanceof EmailProperty) {
return "String.t";
} else if (p instanceof ByteArrayProperty) {
} else if (propertySchema instanceof ByteArraySchema
|| propertySchema instanceof BinarySchema) {
return "binary()";
} else if (p instanceof StringProperty) {
return "String.t";
} else if (p instanceof DateProperty) {
} else if (propertySchema instanceof DateSchema) {
return "Date.t";
} else if (p instanceof UUIDProperty) {
return "String.t";
} else if (p instanceof DateTimeProperty) {
} else if (propertySchema instanceof DateTimeSchema) {
return "DateTime.t";
} else if (p instanceof ObjectProperty) {
} else if (propertySchema instanceof ObjectSchema) {
// How to map it?
return super.getTypeDeclaration(p);
} else if (p instanceof IntegerProperty) {
return "integer()";
} else if (p instanceof LongProperty) {
return "integer()";
} else if (p instanceof BaseIntegerProperty) {
return "integer()";
} else if (p instanceof DoubleProperty) {
return super.getTypeDeclaration(propertySchema);
} else if (propertySchema instanceof IntegerSchema) {
} else if (propertySchema instanceof NumberSchema) {
return "float()";
} else if (p instanceof FloatProperty) {
return "float()";
} else if (p instanceof DecimalProperty) {
return "float()";
} else if (p instanceof AbstractNumericProperty) {
return "number()";
} else if (p instanceof BinaryProperty) {
return "binary()";
} else if (p instanceof BooleanProperty) {
} else if (propertySchema instanceof BooleanSchema) {
return "boolean()";
} else if (p instanceof RefProperty) {
} else if (StringUtils.isNotBlank(propertySchema.get$ref())) {
// How to map it?
return super.getTypeDeclaration(p);
} else if (p instanceof FileProperty) {
return "String.t";
return super.getTypeDeclaration(propertySchema);
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
/**
@@ -497,11 +507,11 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
* either language specific types via `typeMapping` or into complex models if there is not a mapping.
*
* @return a string value of the type or complex model for this property
* @see io.swagger.models.properties.Property
* @see io.swagger.v3.oas.models.media.Schema
*/
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String swaggerType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
@@ -521,26 +531,9 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
// Copy all fields of CodegenOperation
this.responseHeaders.addAll(o.responseHeaders);
this.hasAuthMethods = o.hasAuthMethods;
this.hasConsumes = o.hasConsumes;
this.hasProduces = o.hasProduces;
this.hasParams = o.hasParams;
this.hasOptionalParams = o.hasOptionalParams;
this.returnTypeIsPrimitive = o.returnTypeIsPrimitive;
this.returnSimpleType = o.returnSimpleType;
this.subresourceOperation = o.subresourceOperation;
this.isMapContainer = o.isMapContainer;
this.isListContainer = o.isListContainer;
this.isMultipart = o.isMultipart;
this.hasMore = o.hasMore;
this.isResponseBinary = o.isResponseBinary;
this.hasReference = o.hasReference;
this.isRestfulIndex = o.isRestfulIndex;
this.isRestfulShow = o.isRestfulShow;
this.isRestfulCreate = o.isRestfulCreate;
this.isRestfulUpdate = o.isRestfulUpdate;
this.isRestfulDestroy = o.isRestfulDestroy;
this.isRestful = o.isRestful;
this.path = o.path;
this.operationId = o.operationId;
this.returnType = o.returnType;
@@ -635,24 +628,24 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
private void buildTypespec(CodegenParameter param, StringBuilder sb) {
if (param.dataType == null) {
sb.append("nil");
} else if (param.isListContainer) {
} else if (getBooleanValue(param, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
// list(<subtype>)
sb.append("list(");
if (param.isBodyParam) {
if (getBooleanValue(param, CodegenConstants.IS_BODY_PARAM_EXT_NAME)) {
buildTypespec(param.items.items, sb);
} else {
buildTypespec(param.items, sb);
}
sb.append(")");
} else if (param.isMapContainer) {
} else if (getBooleanValue(param, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME)) {
// %{optional(String.t) => <subtype>}
sb.append("%{optional(String.t) => ");
buildTypespec(param.items, sb);
sb.append("}");
} else if (param.isPrimitiveType) {
} else if (getBooleanValue(param, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME)) {
// like `integer()`, `String.t`
sb.append(param.dataType);
} else if (param.isFile) {
} else if (getBooleanValue(param, CodegenConstants.IS_FILE_EXT_NAME)) {
sb.append("String.t");
} else {
// <module>.Model.<type>.t
@@ -663,15 +656,16 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
}
}
private void buildTypespec(CodegenProperty property, StringBuilder sb) {
if (property.isListContainer) {
if (getBooleanValue(property, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
sb.append("list(");
buildTypespec(property.items, sb);
sb.append(")");
} else if (property.isMapContainer) {
} else if (getBooleanValue(property, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME)) {
sb.append("%{optional(String.t) => ");
buildTypespec(property.items, sb);
sb.append("}");
} else if (property.isPrimitiveType) {
} else if (getBooleanValue(property, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME)) {
sb.append(property.baseType);
sb.append(".t");
} else {
@@ -684,7 +678,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
public String decodedStruct() {
// Let Poison decode the entire response into a generic blob
if (isMapContainer) {
if (getBooleanValue(this, CodegenConstants.IS_MULTIPART_EXT_NAME)) {
return "";
}
// Primitive return type, don't even try to decode
@@ -692,7 +686,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
return "false";
}
StringBuilder sb = new StringBuilder();
if (isListContainer) {
if (getBooleanValue(this, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
sb.append("[");
}
sb.append("%");
@@ -700,7 +694,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
sb.append(".Model.");
sb.append(returnBaseType);
sb.append("{}");
if (isListContainer) {
if (getBooleanValue(this, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
sb.append("]");
}
return sb.toString();
@@ -733,7 +727,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
this.discriminator = cm.discriminator;
this.defaultValue = cm.defaultValue;
this.arrayModelType = cm.arrayModelType;
this.isAlias = cm.isAlias;
// TODO: use vendor extension this.isAlias = cm.isAlias;
this.vars = cm.vars;
this.requiredVars = cm.requiredVars;
this.optionalVars = cm.optionalVars;
@@ -745,17 +739,8 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
this.mandatory = cm.mandatory;
this.allMandatory = cm.allMandatory;
this.imports = cm.imports;
this.hasVars = cm.hasVars;
this.emptyVars = cm.emptyVars;
this.hasMoreModels = cm.hasMoreModels;
this.hasEnums = cm.hasEnums;
this.isEnum = cm.isEnum;
this.hasRequired = cm.hasRequired;
this.hasOptional = cm.hasOptional;
this.isArrayModel = cm.isArrayModel;
this.hasChildren = cm.hasChildren;
this.hasOnlyReadOnly = cm.hasOnlyReadOnly;
this.externalDocs = cm.externalDocs;
this.externalDocumentation = cm.externalDocumentation;
this.vendorExtensions = cm.vendorExtensions;
this.additionalPropertiesType = cm.additionalPropertiesType;
@@ -764,7 +749,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
public boolean hasComplexVars() {
for (CodegenProperty p : vars) {
if (!p.isPrimitiveType) {
if (!getBooleanValue(p, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME)) {
return true;
}
}

View File

@@ -1,6 +1,7 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
@@ -9,19 +10,18 @@ import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Response;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import io.swagger.codegen.languages.helpers.ExtensionHelper;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.responses.ApiResponse;
import java.io.File;
import java.text.Collator;
@@ -36,6 +36,8 @@ import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
private static final String X_ENCODER = "x-encoder";
private static final String X_DECODER = "x-decoder";
@@ -216,7 +218,7 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
if (parent != null) {
if (parent.children == null) {
parent.children = new ArrayList<>();
parent.hasChildren = true;
parent.getVendorExtensions().put(CodegenConstants.HAS_CHILDREN_EXT_NAME, Boolean.TRUE);
}
parent.children.add(cm);
Collections.sort(parent.children, new Comparator<CodegenModel>() {
@@ -231,22 +233,23 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
Map<String, Object> inner = (Map<String, Object>) entry.getValue();
List<Map<String, Object>> models = (List<Map<String, Object>>) inner.get("models");
for (Map<String, Object> mo : models) {
CodegenModel cm = (CodegenModel) mo.get("model");
if (cm.isEnum) {
this.addEncoderAndDecoder(cm.vendorExtensions, cm.classname, false);
cm.vendorExtensions.put(X_UNION_TYPE, cm.classname);
} else if (cm.isAlias) {
this.addEncoderAndDecoder(cm.vendorExtensions, cm.dataType, true);
CodegenModel codegenModel = (CodegenModel) mo.get("model");
if (getBooleanValue(codegenModel, CodegenConstants.IS_ENUM_EXT_NAME)) {
this.addEncoderAndDecoder(codegenModel.vendorExtensions, codegenModel.classname, false);
codegenModel.vendorExtensions.put(X_UNION_TYPE, codegenModel.classname);
} else if (getBooleanValue(codegenModel, CodegenConstants.IS_ALIAS_EXT_NAME)) {
this.addEncoderAndDecoder(codegenModel.vendorExtensions, codegenModel.dataType, true);
}
List<ElmImport> elmImports = new ArrayList<>();
for (CodegenProperty property : cm.allVars) {
for (CodegenProperty property : codegenModel.allVars) {
if (property.complexType != null) {
elmImports.add(createPropertyImport(property));
}
}
if (cm.discriminator != null) {
for (CodegenModel child : cm.children) {
if (codegenModel.discriminator != null) {
for (CodegenModel child : codegenModel.children) {
// add child imports
final ElmImport elmImport = new ElmImport();
final String modulePrefix = customPrimitives.contains(child.classname) ? "" : "Data.";
@@ -259,13 +262,14 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
elmImports.add(elmImport);
// set discriminator value to all children (recursively)
this.setDiscriminatorValue(child, cm.discriminator, this.getDiscriminatorValue(child));
// add all non-discriminator vars
int index = 0;
for (CodegenProperty property : cm.vars) {
if (!cm.discriminator.equals(property.baseName)) {
child.vars.add(index++, property);
if (codegenModel.discriminator != null) {
this.setDiscriminatorValue(child, codegenModel.discriminator.getPropertyName(), this.getDiscriminatorValue(child));
// add all non-discriminator vars
int index = 0;
for (CodegenProperty property : codegenModel.vars) {
if (!codegenModel.discriminator.getPropertyName().equals(property.baseName)) {
child.vars.add(index++, property);
}
}
}
}
@@ -329,24 +333,24 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
Map<String, Set<String>> dependencies = new HashMap<>();
for (CodegenOperation op : ops) {
String path = op.path;
for (CodegenParameter param : op.pathParams) {
final String var = param.isString ? param.paramName : "toString " + param.paramName;
for (CodegenOperation codegenOperation : ops) {
String path = codegenOperation.path;
for (CodegenParameter param : codegenOperation.pathParams) {
final String var = getBooleanValue(param, CodegenConstants.IS_STRING_EXT_NAME) ? param.paramName : "toString " + param.paramName;
path = path.replace("{" + param.paramName + "}", "\" ++ " + var + " ++ \"");
}
op.path = ("\"" + path + "\"").replaceAll(" \\+\\+ \"\"", "");
codegenOperation.path = ("\"" + path + "\"").replaceAll(" \\+\\+ \"\"", "");
if (op.bodyParam != null) {
final String encoder = (String) op.bodyParam.vendorExtensions.get(X_ENCODER);
if (codegenOperation.bodyParam != null) {
final String encoder = (String) codegenOperation.bodyParam.vendorExtensions.get(X_ENCODER);
if (encoder != null) {
if (!dependencies.containsKey(op.bodyParam.dataType)) {
dependencies.put(op.bodyParam.dataType, new TreeSet<String>());
if (!dependencies.containsKey(codegenOperation.bodyParam.dataType)) {
dependencies.put(codegenOperation.bodyParam.dataType, new TreeSet<String>());
}
dependencies.get(op.bodyParam.dataType).add(encoder);
dependencies.get(codegenOperation.bodyParam.dataType).add(encoder);
}
}
for (CodegenResponse resp : op.responses) {
for (CodegenResponse resp : codegenOperation.responses) {
final String decoder = (String) resp.vendorExtensions.get(X_DECODER);
if (decoder != null) {
if (!dependencies.containsKey(resp.dataType)) {
@@ -373,45 +377,33 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
StringProperty sp = (StringProperty) p;
if (sp.getDefault() != null) {
return toOptionalValue("\"" + sp.getDefault().toString() + "\"");
public String toDefaultValue(Schema schema) {
if (schema instanceof StringSchema) {
StringSchema stringSchema = (StringSchema) schema;
if (stringSchema.getDefault() != null) {
return toOptionalValue("\"" + stringSchema.getDefault().toString() + "\"");
}
return toOptionalValue(null);
} else if (p instanceof BooleanProperty) {
BooleanProperty bp = (BooleanProperty) p;
if (bp.getDefault() != null) {
return toOptionalValue(bp.getDefault() ? "True" : "False");
} else if (schema instanceof BooleanSchema) {
BooleanSchema booleanSchema = (BooleanSchema) schema;
if (booleanSchema.getDefault() != null) {
return toOptionalValue(booleanSchema.getDefault() != null && Boolean.TRUE.equals(booleanSchema.getDefault()) ? "True" : "False");
}
return toOptionalValue(null);
} else if (p instanceof DateProperty) {
} else if (schema instanceof DateSchema) {
return toOptionalValue(null);
} else if (p instanceof DateTimeProperty) {
} else if (schema instanceof DateTimeSchema) {
return toOptionalValue(null);
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return toOptionalValue(dp.getDefault().toString());
} else if (schema instanceof NumberSchema) {
NumberSchema numberSchema = (NumberSchema) schema;
if (numberSchema.getDefault() != null) {
return toOptionalValue(numberSchema.getDefault().toString());
}
return toOptionalValue(null);
} else if (p instanceof FloatProperty) {
FloatProperty fp = (FloatProperty) p;
if (fp.getDefault() != null) {
return toOptionalValue(fp.getDefault().toString());
}
return toOptionalValue(null);
} else if (p instanceof IntegerProperty) {
IntegerProperty ip = (IntegerProperty) p;
if (ip.getDefault() != null) {
return toOptionalValue(ip.getDefault().toString());
}
return toOptionalValue(null);
} else if (p instanceof LongProperty) {
LongProperty lp = (LongProperty) p;
if (lp.getDefault() != null) {
return toOptionalValue(lp.getDefault().toString());
} else if (schema instanceof IntegerSchema) {
IntegerSchema integerSchema = (IntegerSchema) schema;
if (integerSchema.getDefault() != null) {
return toOptionalValue(integerSchema.getDefault().toString());
}
return toOptionalValue(null);
} else {
@@ -427,8 +419,8 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema schema) {
String swaggerType = super.getSchemaType(schema);
String type;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
@@ -441,26 +433,28 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
public String getTypeDeclaration(Schema schema) {
if (schema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) schema;
Schema inner = arraySchema.getItems();
return getTypeDeclaration(inner);
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
} else if (schema instanceof MapSchema && hasSchemaProperties(schema)) {
MapSchema mapSchema = (MapSchema) schema;
Schema inner = (Schema) mapSchema.getAdditionalProperties();
return getTypeDeclaration(inner);
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(schema);
}
@Override
public CodegenProperty fromProperty(String name, Property p) {
final CodegenProperty property = super.fromProperty(name, p);
public CodegenProperty fromProperty(String name, Schema schema) {
final CodegenProperty property = super.fromProperty(name, schema);
final boolean isEnum = getBooleanValue(property, CodegenConstants.IS_ENUM_EXT_NAME);
final boolean isPrimitiveType = getBooleanValue(property, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME);
final String dataType = isEnum ? property.baseName : property.datatype;
final String dataType = property.isEnum ? property.baseName : property.datatype;
addEncoderAndDecoder(property.vendorExtensions, dataType, property.isPrimitiveType && !property.isEnum);
if (property.isEnum) {
addEncoderAndDecoder(property.vendorExtensions, dataType, isPrimitiveType && !isEnum);
if (isEnum) {
property.vendorExtensions.put(X_UNION_TYPE, property.datatypeWithEnum);
}
@@ -468,10 +462,10 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public CodegenResponse fromResponse(String responseCode, Response resp) {
public CodegenResponse fromResponse(String responseCode, ApiResponse resp) {
final CodegenResponse response = super.fromResponse(responseCode, resp);
if (response.dataType != null) {
addEncoderAndDecoder(response.vendorExtensions, response.dataType, response.primitiveType);
addEncoderAndDecoder(response.vendorExtensions, response.dataType, getBooleanValue(response, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME));
}
return response;
}
@@ -479,7 +473,8 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public CodegenParameter fromParameter(Parameter param, Set<String> imports) {
final CodegenParameter parameter = super.fromParameter(param, imports);
addEncoderAndDecoder(parameter.vendorExtensions, parameter.dataType, parameter.isPrimitiveType);
final boolean isPrimitiveType = getBooleanValue(parameter, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME);
addEncoderAndDecoder(parameter.vendorExtensions, parameter.dataType, isPrimitiveType);
return parameter;
}

View File

@@ -3,10 +3,6 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.parameters.Parameter;
import java.io.File;
import java.util.*;
@@ -15,11 +11,14 @@ import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig {
static Logger LOGGER = LoggerFactory.getLogger(ErlangClientCodegen.class);
@@ -95,8 +94,8 @@ public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig
}
@Override
public String getTypeDeclaration(Property p) {
String swaggerType = getSwaggerType(p);
public String getTypeDeclaration(Schema propertySchema) {
String swaggerType = getSchemaType(propertySchema);
if (typeMapping.containsKey(swaggerType)) {
return typeMapping.get(swaggerType);
}
@@ -104,8 +103,8 @@ public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String swaggerType = super.getSchemaType(propertySchema);
String type = null;
if(typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
@@ -164,7 +163,7 @@ public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig
String r = new String();
CodegenParameter q = (CodegenParameter) o;
if (q.required) {
if (q.isListContainer) {
if (getBooleanValue(q, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
r += "[{<<\"" + q.baseName + "\">>, X} || X <- " + q.paramName + "]";
} else {
r += "{<<\"" + q.baseName + "\">>, " + q.paramName + "}";
@@ -264,7 +263,7 @@ public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig
// force http method to lower case
o.httpMethod = o.httpMethod.toLowerCase();
if (o.isListContainer) {
if (getBooleanValue(o, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
o.returnType = "[" + o.returnBaseType + "]";
}
@@ -314,7 +313,7 @@ public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig
int l = 0;
for (CodegenParameter o : allParams) {
CodegenParameter q = (CodegenParameter) o;
if (q.required || q.isBodyParam)
if (q.required)
l++;
}
@@ -343,26 +342,9 @@ public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig
// Copy all fields of CodegenOperation
this.responseHeaders.addAll(o.responseHeaders);
this.hasAuthMethods = o.hasAuthMethods;
this.hasConsumes = o.hasConsumes;
this.hasProduces = o.hasProduces;
this.hasParams = o.hasParams;
this.hasOptionalParams = o.hasOptionalParams;
this.returnTypeIsPrimitive = o.returnTypeIsPrimitive;
this.returnSimpleType = o.returnSimpleType;
this.subresourceOperation = o.subresourceOperation;
this.isMapContainer = o.isMapContainer;
this.isListContainer = o.isListContainer;
this.isMultipart = o.isMultipart;
this.hasMore = o.hasMore;
this.isResponseBinary = o.isResponseBinary;
this.hasReference = o.hasReference;
this.isRestfulIndex = o.isRestfulIndex;
this.isRestfulShow = o.isRestfulShow;
this.isRestfulCreate = o.isRestfulCreate;
this.isRestfulUpdate = o.isRestfulUpdate;
this.isRestfulDestroy = o.isRestfulDestroy;
this.isRestful = o.isRestful;
this.path = o.path;
this.operationId = o.operationId;
this.returnType = o.returnType;

View File

@@ -1,25 +1,22 @@
package io.swagger.codegen.languages;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import io.swagger.codegen.*;
import io.swagger.models.*;
import io.swagger.util.Json;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.core.util.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig {
@@ -233,10 +230,10 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
Swagger swagger = (Swagger)objs.get("swagger");
if(swagger != null) {
OpenAPI openAPI = (OpenAPI) objs.get("openapi");
if(openAPI != null) {
try {
objs.put("swagger-json", Json.pretty().writeValueAsString(swagger).replace("\r\n", "\n"));
objs.put("swagger-json", Json.pretty().writeValueAsString(openAPI).replace("\r\n", "\n"));
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}

View File

@@ -1,10 +1,18 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Model;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenSecurity;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import java.io.File;
import java.util.Arrays;
@@ -13,6 +21,8 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class FinchServerCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger";
@@ -196,13 +206,13 @@ public class FinchServerCodegen extends DefaultCodegen implements CodegenConfig
* Convert Swagger Model object to Codegen Model object
*
* @param name the name of the model
* @param model Swagger Model object
* @param allDefinitions a map of all Swagger models from the spec
* @param schema Swagger Model object
* @param allSchemas a map of all Swagger models from the spec
* @return Codegen Model object
*/
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allSchemas) {
CodegenModel codegenModel = super.fromModel(name, schema, allSchemas);
return codegenModel;
}
@@ -236,32 +246,27 @@ public class FinchServerCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]";
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s[%s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s[String, %s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String swaggerType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
if (languageSpecificPrimitives.contains(type))
return toModelName(type);
}
} else {
} else
type = swaggerType;
}
return toModelName(type);
}
@@ -327,15 +332,18 @@ public class FinchServerCodegen extends DefaultCodegen implements CodegenConfig
//Append apikey security to path params and create input parameters for functions
if(op.authMethods != null){
for(CodegenSecurity s : op.authMethods) {
if(s.isApiKey && s.isKeyInHeader){
authParams = colConcat(authParams, "header(\""+ s.keyParamName + "\")");
} else if(s.isApiKey && s.isKeyInQuery){
authParams = colConcat(authParams, "param(\""+ s.keyParamName + "\")");
for(CodegenSecurity codegenSecurity : op.authMethods) {
boolean isApiKey = getBooleanValue(codegenSecurity, CodegenConstants.IS_API_KEY_EXT_NAME);
boolean isKeyInHeader = getBooleanValue(codegenSecurity, CodegenConstants.IS_KEY_IN_HEADER_EXT_NAME);
boolean isKeyInQuery = getBooleanValue(codegenSecurity, CodegenConstants.IS_KEY_IN_QUERY_EXT_NAME);
if(isApiKey && isKeyInHeader){
authParams = colConcat(authParams, "header(\""+ codegenSecurity.keyParamName + "\")");
} else if(isApiKey && isKeyInQuery){
authParams = colConcat(authParams, "param(\""+ codegenSecurity.keyParamName + "\")");
}
if(s.isApiKey) {
typedAuthInputParams = csvConcat(typedAuthInputParams, "authParam"+ s.name + ": String");
authInputParams = csvConcat(authInputParams,"authParam"+ s.name);
if(isApiKey) {
typedAuthInputParams = csvConcat(typedAuthInputParams, "authParam"+ codegenSecurity.name + ": String");
authInputParams = csvConcat(authInputParams,"authParam"+ codegenSecurity.name);
}
}
}
@@ -405,37 +413,39 @@ public class FinchServerCodegen extends DefaultCodegen implements CodegenConfig
String typedInputParams = "";
String pathParams = "";
for (CodegenParameter p : op.allParams) {
for (CodegenParameter parameter : op.allParams) {
// TODO: This hacky, should be converted to mappings if possible to keep it clean.
// This could also be done using template imports
if(p.isBodyParam) {
p.vendorExtensions.put("x-codegen-normalized-path-type", "jsonBody["+ p.dataType + "]");
p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType);
} else if(p.isContainer || p.isListContainer) {
p.vendorExtensions.put("x-codegen-normalized-path-type", toPathParameter(p,"params", false));
p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType.replaceAll("^[^\\[]+", "Seq"));
} else if(p.isQueryParam) {
p.vendorExtensions.put("x-codegen-normalized-path-type", toPathParameter(p, "param",true));
p.vendorExtensions.put("x-codegen-normalized-input-type", toInputParameter(p));
} else if(p.isHeaderParam) {
p.vendorExtensions.put("x-codegen-normalized-path-type", toPathParameter(p,"header", true));
p.vendorExtensions.put("x-codegen-normalized-input-type", toInputParameter(p));
} else if(p.isFile) {
p.vendorExtensions.put("x-codegen-normalized-path-type", "fileUpload(\""+ p.paramName + "\")");
p.vendorExtensions.put("x-codegen-normalized-input-type", "FileUpload");
} else if(p.isPrimitiveType && !p.isPathParam) {
p.vendorExtensions.put("x-codegen-normalized-path-type", p.dataType.toLowerCase());
p.vendorExtensions.put("x-codegen-normalized-input-type", toInputParameter(p));
if(getBooleanValue(parameter, CodegenConstants.IS_BODY_PARAM_EXT_NAME)) {
parameter.vendorExtensions.put("x-codegen-normalized-path-type", "jsonBody["+ parameter.dataType + "]");
parameter.vendorExtensions.put("x-codegen-normalized-input-type", parameter.dataType);
} else if(getBooleanValue(parameter, CodegenConstants.IS_CONTAINER_EXT_NAME)
|| getBooleanValue(parameter, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
parameter.vendorExtensions.put("x-codegen-normalized-path-type", toPathParameter(parameter,"params", false));
parameter.vendorExtensions.put("x-codegen-normalized-input-type", parameter.dataType.replaceAll("^[^\\[]+", "Seq"));
} else if(getBooleanValue(parameter, CodegenConstants.IS_QUERY_PARAM_EXT_NAME)) {
parameter.vendorExtensions.put("x-codegen-normalized-path-type", toPathParameter(parameter, "param",true));
parameter.vendorExtensions.put("x-codegen-normalized-input-type", toInputParameter(parameter));
} else if(getBooleanValue(parameter, CodegenConstants.IS_HEADER_PARAM_EXT_NAME)) {
parameter.vendorExtensions.put("x-codegen-normalized-path-type", toPathParameter(parameter,"header", true));
parameter.vendorExtensions.put("x-codegen-normalized-input-type", toInputParameter(parameter));
} else if(getBooleanValue(parameter, CodegenConstants.IS_FILE_EXT_NAME)) {
parameter.vendorExtensions.put("x-codegen-normalized-path-type", "fileUpload(\""+ parameter.paramName + "\")");
parameter.vendorExtensions.put("x-codegen-normalized-input-type", "FileUpload");
} else if(getBooleanValue(parameter, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME)
&& !getBooleanValue(parameter, CodegenConstants.IS_PATH_PARAM_EXT_NAME)) {
parameter.vendorExtensions.put("x-codegen-normalized-path-type", parameter.dataType.toLowerCase());
parameter.vendorExtensions.put("x-codegen-normalized-input-type", toInputParameter(parameter));
} else {
//Path paremeters are handled in generateScalaPath()
p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType);
parameter.vendorExtensions.put("x-codegen-normalized-input-type", parameter.dataType);
}
if(p.vendorExtensions.get("x-codegen-normalized-path-type") != null){
pathParams = colConcat(pathParams , p.vendorExtensions.get("x-codegen-normalized-path-type").toString());
if(parameter.vendorExtensions.get("x-codegen-normalized-path-type") != null){
pathParams = colConcat(pathParams , parameter.vendorExtensions.get("x-codegen-normalized-path-type").toString());
}
inputParams = csvConcat(inputParams, p.paramName);
typedInputParams = csvConcat(typedInputParams , p.paramName + ": " + p.vendorExtensions.get("x-codegen-normalized-input-type"));
inputParams = csvConcat(inputParams, parameter.paramName);
typedInputParams = csvConcat(typedInputParams , parameter.paramName + ": " + parameter.vendorExtensions.get("x-codegen-normalized-input-type"));
}

View File

@@ -6,17 +6,15 @@ import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
@@ -198,16 +196,16 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty || p instanceof MapProperty) {
return getSwaggerType(p);
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema || propertySchema instanceof MapSchema) {
return getSchemaType(propertySchema);
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String swaggerType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
@@ -221,42 +219,28 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
}
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
public String toDefaultValue(Schema propertySchema) {
if (propertySchema instanceof StringSchema) {
return "null";
} else if (p instanceof BooleanProperty) {
} else if (propertySchema instanceof BooleanSchema) {
return "false";
} else if (p instanceof DateProperty) {
} else if (propertySchema instanceof DateSchema) {
return "null";
} else if (p instanceof DateTimeProperty) {
} else if (propertySchema instanceof DateTimeSchema) {
return "null";
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
} else if (propertySchema instanceof NumberSchema) {
if (propertySchema.getDefault() != null) {
return propertySchema.getDefault().toString();
}
return "0.0";
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
return "0.0";
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
} else if (propertySchema instanceof IntegerSchema) {
if (propertySchema.getDefault() != null) {
return propertySchema.getDefault().toString();
}
return "0";
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
return "0";
} else if (p instanceof MapProperty) {
} else if (propertySchema instanceof MapSchema) {
return "new Dictionary()";
} else if (p instanceof ArrayProperty) {
} else if (propertySchema instanceof ArraySchema) {
return "new Array()";
} else {
return "NaN";

View File

@@ -5,14 +5,28 @@ import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import io.swagger.codegen.*;
import io.swagger.models.HttpMethod;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.*;
import io.swagger.util.Yaml;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.core.util.Yaml;
import java.io.File;
import java.util.*;
@@ -21,6 +35,8 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(FlaskConnexionCodegen.class);
@@ -270,46 +286,40 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[str, " + getTypeDeclaration(inner) + "]";
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s[%s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s[str, %s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String swaggerType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return type;
}
} else {
type = toModelName(swaggerType);
}
return type;
if (languageSpecificPrimitives.contains(type))
return toModelName(type);
} else
type = swaggerType;
return toModelName(type);
}
@Override
public void preprocessSwagger(Swagger swagger) {
public void preprocessOpenAPI(OpenAPI openAPI) {
// need vendor extensions for x-swagger-router-controller
Map<String, Path> paths = swagger.getPaths();
Map<String, PathItem> paths = openAPI.getPaths();
if(paths != null) {
for(String pathname : paths.keySet()) {
Path path = paths.get(pathname);
Map<HttpMethod, Operation> operationMap = path.getOperationMap();
PathItem path = paths.get(pathname);
Map<PathItem.HttpMethod, Operation> operationMap = path.readOperationsMap();
if(operationMap != null) {
for(HttpMethod method : operationMap.keySet()) {
for(PathItem.HttpMethod method : operationMap.keySet()) {
Operation operation = operationMap.get(method);
String tag = "default";
if(operation.getTags() != null && operation.getTags().size() > 0) {
@@ -320,11 +330,8 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
operationId = getOrGenerateOperationId(operation, pathname, method.toString());
}
operation.setOperationId(toOperationId(operationId));
if(operation.getVendorExtensions().get("x-swagger-router-controller") == null) {
operation.getVendorExtensions().put(
"x-swagger-router-controller",
controllerPackage + "." + toApiFilename(tag)
);
if(operation.getExtensions() != null && operation.getExtensions().get("x-swagger-router-controller") == null) {
operation.getExtensions().put("x-swagger-router-controller", controllerPackage + "." + toApiFilename(tag));
}
for (Parameter param: operation.getParameters()) {
// sanitize the param name but don't underscore it since it's used for request mapping
@@ -366,7 +373,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
opsByPathEntry.put("path", entry.getKey());
opsByPathEntry.put("operation", entry.getValue());
List<CodegenOperation> operationsForThisPath = Lists.newArrayList(entry.getValue());
operationsForThisPath.get(operationsForThisPath.size() - 1).hasMore = false;
operationsForThisPath.get(operationsForThisPath.size() - 1).getVendorExtensions().put(CodegenConstants.HAS_MORE_EXT_NAME, Boolean.FALSE);
if (opsByPathList.size() < opsByPath.asMap().size()) {
opsByPathEntry.put("hasMore", "true");
}
@@ -377,10 +384,10 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
Swagger swagger = (Swagger)objs.get("swagger");
if(swagger != null) {
OpenAPI openAPI = (OpenAPI) objs.get("swagger");
if(openAPI != null) {
try {
objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger));
objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(openAPI));
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}
@@ -490,50 +497,30 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
/**
* Return the default value of the property
*
* @param p Swagger property object
* @param propertySchema Swagger property object
* @return string presentation of the default value of the property
*/
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
return "'" + dp.getDefault() + "'";
public String toDefaultValue(Schema propertySchema) {
if (propertySchema instanceof StringSchema) {
if (propertySchema.getDefault() != null) {
return String.format("'%s'", propertySchema.getDefault());
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getDefault() != null) {
if (dp.getDefault().toString().equalsIgnoreCase("false"))
} else if (propertySchema instanceof BooleanSchema) {
if (propertySchema.getDefault() != null) {
if (propertySchema.getDefault().toString().equalsIgnoreCase("false")) {
return "False";
else
} else {
return "True";
}
}
} else if (p instanceof DateProperty) {
} else if (propertySchema instanceof DateSchema || propertySchema instanceof DateTimeSchema) {
// TODO
} else if (p instanceof DateTimeProperty) {
// TODO
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
} else {
if (propertySchema.getDefault() != null) {
return propertySchema.getDefault().toString();
}
}
return null;
}
@@ -612,11 +599,11 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf
}
if (example == null) {
example = "None";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
if (Boolean.TRUE.equals(p.isBodyParam)) {
} else if (getBooleanValue(p, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
if (getBooleanValue(p, CodegenConstants.IS_BODY_PARAM_EXT_NAME)) {
example = "[" + example + "]";
}
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME)) {
example = "{'key': " + example + "}";
}

View File

@@ -1,14 +1,13 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.parameters.Parameter;
import java.io.File;
import java.util.*;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
@@ -164,6 +163,170 @@ public class GoClientCodegen extends AbstractGoCodegen {
return toApiName(name);
}
@Override
public String getTypeDeclaration(Schema propertySchema) {
if(propertySchema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) propertySchema;
Schema inner = arraySchema.getItems();
return "[]" + getTypeDeclaration(inner);
}
else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return getSchemaType(propertySchema) + "[string]" + getTypeDeclaration(inner);
}
//return super.getTypeDeclaration(p);
// Not using the supertype invocation, because we want to UpperCamelize
// the type.
String schemaType = getSchemaType(propertySchema);
if (typeMapping.containsKey(schemaType)) {
return typeMapping.get(schemaType);
}
if(typeMapping.containsValue(schemaType)) {
return schemaType;
}
if(languageSpecificPrimitives.contains(schemaType)) {
return schemaType;
}
return toModelName(schemaType);
}
@Override
public String getSchemaType(Schema propertySchema) {
String swaggerType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
} else {
if ("Array".equalsIgnoreCase(swaggerType)) {
return swaggerType.toLowerCase();
}
else if ("Map".equalsIgnoreCase(swaggerType)) {
return swaggerType.toLowerCase();
} else {
type = swaggerType;
}
}
return toModelName(type);
}
@Override
public String toOperationId(String operationId) {
String sanitizedOperationId = sanitizeName(operationId);
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(sanitizedOperationId)) {
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize("call_" + operationId));
sanitizedOperationId = "call_" + sanitizedOperationId;
}
return camelize(sanitizedOperationId);
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
@SuppressWarnings("unchecked")
Map<String, Object> objectMap = (Map<String, Object>) objs.get("operations");
@SuppressWarnings("unchecked")
List<CodegenOperation> operations = (List<CodegenOperation>) objectMap.get("operation");
for (CodegenOperation operation : operations) {
// http method verb conversion (e.g. PUT => Put)
operation.httpMethod = camelize(operation.httpMethod.toLowerCase());
}
// remove model imports to avoid error
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
if (imports == null)
return objs;
Iterator<Map<String, String>> iterator = imports.iterator();
while (iterator.hasNext()) {
String _import = iterator.next().get("import");
if (_import.startsWith(apiPackage()))
iterator.remove();
}
// if their is a return type, import encoding/json
for (CodegenOperation operation : operations) {
if(operation.returnBaseType != null ) {
imports.add(createMapping("import", "encoding/json"));
break; //just need to import once
}
}
// this will only import "fmt" if there are items in pathParams
for (CodegenOperation operation : operations) {
if(operation.pathParams != null && operation.pathParams.size() > 0) {
imports.add(createMapping("import", "fmt"));
break; //just need to import once
}
}
// recursively add import for mapping one type to multiple imports
List<Map<String, String>> recursiveImports = (List<Map<String, String>>) objs.get("imports");
if (recursiveImports == null)
return objs;
ListIterator<Map<String, String>> listIterator = imports.listIterator();
while (listIterator.hasNext()) {
String _import = listIterator.next().get("import");
// if the import package happens to be found in the importMapping (key)
// add the corresponding import package to the list
if (importMapping.containsKey(_import)) {
listIterator.add(createMapping("import", importMapping.get(_import)));
}
}
return objs;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// remove model imports to avoid error
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
final String prefix = modelPackage();
Iterator<Map<String, String>> iterator = imports.iterator();
while (iterator.hasNext()) {
String _import = iterator.next().get("import");
if (_import.startsWith(prefix))
iterator.remove();
}
// recursively add import for mapping one type to multiple imports
List<Map<String, String>> recursiveImports = (List<Map<String, String>>) objs.get("imports");
if (recursiveImports == null)
return objs;
ListIterator<Map<String, String>> listIterator = imports.listIterator();
while (listIterator.hasNext()) {
String _import = listIterator.next().get("import");
// if the import package happens to be found in the importMapping (key)
// add the corresponding import package to the list
if (importMapping.containsKey(_import)) {
listIterator.add(createMapping("import", importMapping.get(_import)));
}
}
return postProcessModelsEnum(objs);
}
@Override
protected boolean needToImport(String type) {
return !defaultIncludes.contains(type)
&& !languageSpecificPrimitives.contains(type);
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
}

View File

@@ -1,13 +1,21 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.parameters.Parameter;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import java.io.File;
import java.util.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
@@ -155,6 +163,165 @@ public class GoServerCodegen extends AbstractGoCodegen {
}
@Override
public String toModelName(String name) {
// camelize the model name
// phone_number => PhoneNumber
return camelize(toModelFilename(name));
}
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(operationId)) {
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId)));
operationId = "call_" + operationId;
}
return camelize(operationId);
}
@Override
public String toModelFilename(String name) {
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + modelNameSuffix;
}
name = sanitizeName(name);
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name));
name = "model_" + name; // e.g. return => ModelReturn (after camelize)
}
return camelize(name);
}
@Override
public String getTypeDeclaration(Schema propertySchema) {
if(propertySchema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) propertySchema;
Schema inner = arraySchema.getItems();
return String.format("[]%s", getTypeDeclaration(inner));
}
else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return getSchemaType(propertySchema) + "[string]" + getTypeDeclaration(inner);
}
String schemaType = getSchemaType(propertySchema);
if (typeMapping.containsKey(schemaType)) {
return typeMapping.get(schemaType);
}
if(typeMapping.containsValue(schemaType)) {
return schemaType;
}
if(languageSpecificPrimitives.contains(schemaType)) {
return schemaType;
}
return toModelName(schemaType);
}
@Override
public String getSchemaType(Schema propertySchema) {
String swaggerType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type))
return toModelName(type);
} else
type = swaggerType;
return toModelName(type);
}
@Override
public String toApiFilename(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// e.g. PetApi.go => pet_api.go
return underscore(name);
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
@Override
public String toEnumValue(String value, String datatype) {
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
return value;
} else {
return "\'" + escapeText(value) + "\'";
}
}
@Override
public String toEnumDefaultValue(String value, String datatype) {
return datatype + "_" + value;
}
@Override
public String toEnumVarName(String name, String datatype) {
if (name.length() == 0) {
return "EMPTY";
}
// number
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
String varName = name;
varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_");
varName = varName.replaceAll("\\.", "_DOT_");
return varName;
}
// for symbol, e.g. $, #
if (getSymbolName(name) != null) {
return getSymbolName(name).toUpperCase();
}
// string
String enumName = sanitizeName(underscore(name).toUpperCase());
enumName = enumName.replaceFirst("^_", "");
enumName = enumName.replaceFirst("_$", "");
if (isReservedWord(enumName) || enumName.matches("\\d.*")) { // reserved word or starts with number
return escapeReservedWord(enumName);
} else {
return enumName;
}
}
@Override
public String toEnumName(CodegenProperty property) {
String enumName = underscore(toModelName(property.name)).toUpperCase();
// remove [] for array or map of enum
enumName = enumName.replace("[]", "");
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
public String modelFileFolder() {
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}

View File

@@ -1,22 +1,32 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.properties.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import io.swagger.models.auth.SecuritySchemeDefinition;
import io.swagger.codegen.languages.helpers.ExtensionHelper;
import io.swagger.codegen.utils.ModelUtils;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.core.util.Json;
import org.apache.commons.io.FileUtils;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.SupportingFile;
import io.swagger.util.Yaml;
import io.swagger.v3.core.util.Yaml;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.lang3.StringUtils;
@@ -25,6 +35,9 @@ import org.apache.commons.lang3.tuple.Pair;
import java.util.regex.Matcher;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenConfig {
// source folder where to write the files
@@ -379,9 +392,9 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
}
@Override
public void preprocessSwagger(Swagger swagger) {
public void preprocessOpenAPI(OpenAPI openAPI) {
// From the title, compute a reasonable name for the package and the API
String title = swagger.getInfo().getTitle();
String title = openAPI.getInfo().getTitle();
// Drop any API suffix
if (title == null) {
@@ -442,17 +455,25 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
additionalProperties.put("pathsName", pathsName);
additionalProperties.put("requestType", apiName + "Request");
additionalProperties.put("configType", apiName + "Config");
additionalProperties.put("swaggerVersion", swagger.getSwagger());
additionalProperties.put("openApiVersion", openAPI.getOpenapi());
super.preprocessSwagger(swagger);
//copy input swagger to output folder
try {
String swaggerJson = Json.pretty(openAPI);
FileUtils.writeStringToFile(new File(outputFolder + File.separator + "swagger.json"), swaggerJson);
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e.getCause());
}
super.preprocessOpenAPI(openAPI);
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
Swagger swagger = (Swagger)objs.get("swagger");
if(swagger != null) {
OpenAPI openAPI = (OpenAPI)objs.get("openapi");
if(openAPI != null) {
try {
objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger));
objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(openAPI));
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}
@@ -460,57 +481,55 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
return super.postProcessSupportingFileData(objs);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return "(Map.Map String " + getTypeDeclaration(inner) + ")";
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("[%s]", getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("(Map.Map String %s)", getTypeDeclaration(inner));
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
if (typeMapping.containsKey(swaggerType)) {
return typeMapping.get(swaggerType);
} else if (swaggerType == "object") {
public String getSchemaType(Schema propertySchema) {
String schemaType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(schemaType)) {
return typeMapping.get(schemaType);
} else if (languageSpecificPrimitives.contains(type)) {
return type;
} else if (schemaType.equals("object")) {
return "A.Value";
} else {
return toModelName(swaggerType);
return toModelName(schemaType);
}
}
@Override
public String toInstantiationType(Property p) {
if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
Property additionalProperties2 = ap.getAdditionalProperties();
public String toInstantiationType(Schema propertySchema) {
if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema additionalProperties2 = (Schema) propertySchema.getAdditionalProperties();
String type = additionalProperties2.getType();
if (null == type) {
LOGGER.error("No Type defined for Additional Property " + additionalProperties2 + "\n" //
+ "\tIn Property: " + p);
+ "\tIn Property: " + propertySchema);
}
String inner = getSwaggerType(additionalProperties2);
String inner = getSchemaType(additionalProperties2);
return "(Map.Map Text " + inner + ")";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
} else if (propertySchema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) propertySchema;
String inner = getSchemaType(arraySchema.getItems());
return inner;
} else {
return null;
}
}
@Override
public CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(resourcePath, httpMethod, operation, definitions, swagger);
public CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Schema> schemas, OpenAPI openAPI) {
CodegenOperation op = super.fromOperation(resourcePath, httpMethod, operation, schemas, openAPI);
// prevent aliasing/sharing of operation.vendorExtensions reference
op.vendorExtensions = new LinkedHashMap();
@@ -525,7 +544,9 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
for (CodegenParameter param : op.allParams) {
param.vendorExtensions = new LinkedHashMap(); // prevent aliasing/sharing
param.vendorExtensions.put(X_OPERATION_TYPE, operationType);
param.vendorExtensions.put(X_IS_BODY_OR_FORM_PARAM, param.isBodyParam || param.isFormParam);
boolean isBodyParam = getBooleanValue(param, CodegenConstants.IS_BODY_PARAM_EXT_NAME);
boolean isFormParam = getBooleanValue(param, CodegenConstants.IS_FORM_PARAM_EXT_NAME);
param.vendorExtensions.put(X_IS_BODY_OR_FORM_PARAM, isBodyParam || isFormParam);
if (!StringUtils.isBlank(param.collectionFormat)) {
param.vendorExtensions.put(X_COLLECTION_FORMAT, mapCollectionFormat(param.collectionFormat));
}
@@ -533,17 +554,22 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
op.vendorExtensions.put(X_HAS_OPTIONAL_PARAMS, true);
}
boolean isEnum = getBooleanValue(param, CodegenConstants.IS_ENUM_EXT_NAME);
if (typeMapping.containsKey(param.dataType)
|| param.isMapContainer || param.isListContainer
|| param.isPrimitiveType || param.isFile || param.isEnum) {
|| getBooleanValue(param, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME)
|| getBooleanValue(param, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)
|| getBooleanValue(param, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME)
|| getBooleanValue(param, CodegenConstants.IS_FILE_EXT_NAME)
|| isEnum) {
String dataType = genEnums && param.isEnum ? param.datatypeWithEnum : param.dataType;
String dataType = genEnums && isEnum ? param.datatypeWithEnum : param.dataType;
String paramNameType = toDedupedName(toTypeName("Param", param.paramName), dataType, !param.isEnum);
String paramNameType = toDedupedName(toTypeName("Param", param.paramName), dataType, !isEnum);
param.vendorExtensions.put(X_PARAM_NAME_TYPE, paramNameType);
HashMap<String, Object> props = new HashMap<>();
props.put(X_IS_BODY_PARAM, param.isBodyParam);
props.put(X_IS_BODY_PARAM, getBooleanValue(param, CodegenConstants.IS_BODY_PARAM_EXT_NAME));
addToUniques(X_NEWTYPE, paramNameType, dataType, props);
}
}
@@ -557,14 +583,19 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
return op;
}
@Override
public List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes) {
public List<CodegenSecurity> fromSecurity(Map<String, SecurityScheme> schemes) {
List<CodegenSecurity> secs = super.fromSecurity(schemes);
for(CodegenSecurity sec : secs) {
String prefix = "";
if(sec.isBasic) prefix = "AuthBasic";
if(sec.isApiKey) prefix = "AuthApiKey";
if(sec.isOAuth) prefix = "AuthOAuth";
if(getBooleanValue(sec, CodegenConstants.IS_BASIC_EXT_NAME)) {
prefix = "AuthBasic";
}
if(getBooleanValue(sec, CodegenConstants.IS_API_KEY_EXT_NAME)) {
prefix = "AuthApiKey";
}
if(getBooleanValue(sec, CodegenConstants.IS_OAUTH_EXT_NAME)) {
prefix = "AuthOAuth";
}
sec.name = prefix + toTypeName("",sec.name);
}
return secs;
@@ -616,21 +647,25 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
for (Object o : allModels) {
HashMap<String, Object> h = (HashMap<String, Object>) o;
CodegenModel m = (CodegenModel) h.get("model");
if (modelMimeTypes.containsKey(m.classname)) {
Set<String> mimeTypes = modelMimeTypes.get(m.classname);
m.vendorExtensions.put(X_MIME_TYPES, mimeTypes);
for (Object object : allModels) {
HashMap<String, Object> h = (HashMap<String, Object>) object;
CodegenModel codegenModel = (CodegenModel) h.get("model");
if (modelMimeTypes.containsKey(codegenModel.classname)) {
Set<String> mimeTypes = modelMimeTypes.get(codegenModel.classname);
codegenModel.vendorExtensions.put(X_MIME_TYPES, mimeTypes);
if ((boolean)additionalProperties.get(PROP_GENERATE_FORM_URLENCODED_INSTANCES) && mimeTypes.contains("MimeFormUrlEncoded")) {
Boolean hasMimeFormUrlEncoded = true;
for (CodegenProperty v : m.vars) {
if (!(v.isPrimitiveType || v.isString || v.isDate || v.isDateTime)) {
for (CodegenProperty codegenProperty : codegenModel.vars) {
boolean isPrimitiveType = getBooleanValue(codegenProperty, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME);
boolean isString = getBooleanValue(codegenProperty, CodegenConstants.IS_STRING_EXT_NAME);
boolean isDate = getBooleanValue(codegenProperty, CodegenConstants.IS_DATE_EXT_NAME);
boolean isDateTime = getBooleanValue(codegenProperty, CodegenConstants.IS_DATE_TIME_EXT_NAME);
if (!(isPrimitiveType || isString || isDate || isDateTime)) {
hasMimeFormUrlEncoded = false;
}
}
if (hasMimeFormUrlEncoded) {
m.vendorExtensions.put(X_HAS_MIME_FORM_URL_ENCODED, true);
codegenModel.vendorExtensions.put(X_HAS_MIME_FORM_URL_ENCODED, true);
}
}
}
@@ -640,8 +675,8 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
}
@Override
public CodegenModel fromModel(String name, Model mod, Map<String, Model> allDefinitions) {
CodegenModel model = super.fromModel(name, mod, allDefinitions);
public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allSchemas) {
CodegenModel model = super.fromModel(name, schema, allSchemas);
while (typeNames.contains(model.classname)) {
model.classname = generateNextName(model.classname);
@@ -653,7 +688,6 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
for (CodegenProperty prop : model.vars) {
prop.name = toVarName(prefix, prop.name);
}
return model;
}
@@ -686,43 +720,46 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
return dataType != null && dataType.equals("B.ByteString");
}
private void processReturnType(CodegenOperation op) {
String returnType = op.returnType;
private void processReturnType(CodegenOperation codegenOperation) {
String returnType = codegenOperation.returnType;
if (returnType == null || returnType.equals("null")) {
if(op.hasProduces) {
boolean hasProduces = getBooleanValue(codegenOperation, CodegenConstants.HAS_PRODUCES_EXT_NAME);
if(hasProduces) {
returnType = "res";
op.vendorExtensions.put(X_HAS_UNKNOWN_RETURN, true);
codegenOperation.vendorExtensions.put(X_HAS_UNKNOWN_RETURN, true);
} else {
returnType = "NoContent";
if(!op.vendorExtensions.containsKey(X_INLINE_ACCEPT)) {
SetNoContent(op, X_INLINE_ACCEPT);
if(!codegenOperation.vendorExtensions.containsKey(X_INLINE_ACCEPT)) {
SetNoContent(codegenOperation, X_INLINE_ACCEPT);
}
}
}
if (returnType.indexOf(" ") >= 0) {
returnType = "(" + returnType + ")";
}
op.vendorExtensions.put(X_RETURN_TYPE, returnType);
codegenOperation.vendorExtensions.put(X_RETURN_TYPE, returnType);
}
private void processProducesConsumes(CodegenOperation op) {
if (!(Boolean) op.vendorExtensions.get(X_HAS_BODY_OR_FORM_PARAM)) {
SetNoContent(op, X_INLINE_CONTENT_TYPE);
private void processProducesConsumes(CodegenOperation codegenOperation) {
if (!(Boolean) codegenOperation.vendorExtensions.get(X_HAS_BODY_OR_FORM_PARAM)) {
SetNoContent(codegenOperation, X_INLINE_CONTENT_TYPE);
}
if (op.hasConsumes) {
for (Map<String, String> m : op.consumes) {
processMediaType(op, m);
processInlineConsumesContentType(op, m);
boolean hasConsumes = getBooleanValue(codegenOperation, CodegenConstants.HAS_CONSUMES_EXT_NAME);
if (hasConsumes) {
for (Map<String, String> m : codegenOperation.consumes) {
processMediaType(codegenOperation, m);
processInlineConsumesContentType(codegenOperation, m);
}
if (isMultipartOperation(op.consumes)) {
op.isMultipart = Boolean.TRUE;
if (isMultipartOperation(codegenOperation.consumes)) {
codegenOperation.getVendorExtensions().put(CodegenConstants.IS_MULTIPART_EXT_NAME, Boolean.TRUE);
}
}
if (op.hasProduces) {
for (Map<String, String> m : op.produces) {
processMediaType(op,m);
processInlineProducesContentType(op, m);
boolean hasProduces = getBooleanValue(codegenOperation, CodegenConstants.HAS_PRODUCES_EXT_NAME);
if (hasProduces) {
for (Map<String, String> m : codegenOperation.produces) {
processMediaType(codegenOperation,m);
processInlineProducesContentType(codegenOperation, m);
}
}
}
@@ -733,7 +770,8 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
&& op.consumes.size() == 1) {
op.vendorExtensions.put(X_INLINE_CONTENT_TYPE, m);
for (CodegenParameter param : op.allParams) {
if (param.isBodyParam && param.required) {
boolean isBodyParam = getBooleanValue(param, CodegenConstants.IS_BODY_PARAM_EXT_NAME);
if (isBodyParam && param.required) {
param.vendorExtensions.put(X_INLINE_CONTENT_TYPE, m);
}
}
@@ -847,7 +885,13 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
unknownMimeTypes.add(m);
}
for (CodegenParameter param : op.allParams) {
if (param.isBodyParam || param.isFormParam && (!param.isPrimitiveType && !param.isListContainer && !param.isMapContainer)) {
boolean isBodyParam = getBooleanValue(param, CodegenConstants.IS_BODY_PARAM_EXT_NAME);
boolean isFormParam = getBooleanValue(param, CodegenConstants.IS_FORM_PARAM_EXT_NAME);
boolean isPrimitiveType = getBooleanValue(param, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME);
boolean isListContainer = getBooleanValue(param, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME);
boolean isMapContainer = getBooleanValue(param, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME);
if (isBodyParam || isFormParam && (!isPrimitiveType && !isListContainer && !isMapContainer)) {
Set<String> mimeTypes = modelMimeTypes.containsKey(param.dataType) ? modelMimeTypes.get(param.dataType) : new HashSet();
mimeTypes.add(mimeType);
modelMimeTypes.put(param.dataType, mimeTypes);
@@ -1012,22 +1056,24 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
}
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
return "\"" + escapeText(dp.getDefault()) + "\"";
public String toDefaultValue(Schema propertySchema) {
if (propertySchema instanceof StringSchema) {
if (propertySchema.getDefault() != null) {
return String.format("\"%s\"", escapeText(propertySchema.getDefault().toString()));
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getDefault() != null) {
if (dp.getDefault().toString().equalsIgnoreCase("false"))
} else if (propertySchema instanceof BooleanSchema) {
if (propertySchema.getDefault() != null) {
if (propertySchema.getDefault().toString().equalsIgnoreCase("false")) {
return "False";
else
} else {
return "True";
}
}
} else if (propertySchema.getDefault() != null) {
if (propertySchema.getDefault() != null) {
return propertySchema.getDefault().toString();
}
}
return null;
}
@@ -1037,8 +1083,12 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
cm.isEnum = genEnums && cm.isEnum;
if(cm.isAlias) {
final boolean isEnum = getBooleanValue(cm, IS_ENUM_EXT_NAME);
cm.getVendorExtensions().put(IS_ENUM_EXT_NAME, genEnums && isEnum);
boolean isAlias = ExtensionHelper.getBooleanValue(cm, CodegenConstants.IS_ALIAS_EXT_NAME);
if(isAlias) {
cm.vendorExtensions.put(X_DATA_TYPE, cm.dataType);
}
for (CodegenProperty var : cm.vars) {
@@ -1059,7 +1109,8 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
if (cm.isEnum && cm.allowableValues != null) {
final boolean isEnum = getBooleanValue(cm, IS_ENUM_EXT_NAME);
if (isEnum && cm.allowableValues != null) {
updateAllowableValuesNames(cm.classname, cm.allowableValues);
addEnumToUniques(cm.classname, cm.dataType, cm.allowableValues.values().toString(), cm.allowableValues, cm.description);
}
@@ -1071,7 +1122,9 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
@Override
protected void updateDataTypeWithEnumForMap(CodegenProperty property) {
CodegenProperty baseItem = property.items;
while (baseItem != null && (Boolean.TRUE.equals(baseItem.isMapContainer) || Boolean.TRUE.equals(baseItem.isListContainer))) {
boolean isMapContainer = getBooleanValue(property, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME);
boolean isListContainer = getBooleanValue(property, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME);
while (baseItem != null && (isMapContainer || isListContainer)) {
baseItem = baseItem.items;
}
if (baseItem != null) {
@@ -1089,8 +1142,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
@Override
public String toEnumName(CodegenProperty var) {
if (!genEnums) return super.toEnumName(var);
if (var.items != null && var.items.isEnum) {
if (var.items != null && getBooleanValue(var.items, IS_ENUM_EXT_NAME)) {
return toEnumName(var.items);
}
String paramNameType = "E'" + toTypeName("", var.name);
@@ -1109,9 +1161,8 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
return paramNameType;
}
@Override
public void updateCodegenPropertyEnum(CodegenProperty var) {
super.updateCodegenPropertyEnum(var);
ModelUtils.updateCodegenPropertyEnum(var);
if (!genEnums) return;
updateCodegenPropertyEnumValues(var, var.datatypeWithEnum);
}
@@ -1121,7 +1172,8 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
updateCodegenPropertyEnumValues(var.items, var.items.datatypeWithEnum);
return;
}
if(var.isEnum && var.allowableValues != null) {
boolean isEnum = getBooleanValue(var, IS_ENUM_EXT_NAME);
if(isEnum && var.allowableValues != null) {
updateAllowableValuesNames(paramNameType, var.allowableValues);
}
}

View File

@@ -1,16 +1,33 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.ModelImpl;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.*;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class HaskellServantCodegen extends DefaultCodegen implements CodegenConfig {
// source folder where to write the files
@@ -192,9 +209,9 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
}
@Override
public void preprocessSwagger(Swagger swagger) {
public void preprocessOpenAPI(OpenAPI openAPI) {
// From the title, compute a reasonable name for the package and the API
String title = swagger.getInfo().getTitle();
String title = openAPI.getInfo().getTitle();
// Drop any API suffix
if(title == null) {
@@ -233,7 +250,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
additionalProperties.put("package", cabalName);
// Due to the way servant resolves types, we need a high context stack limit
additionalProperties.put("contextStackLimit", swagger.getPaths().size() * 2 + 300);
additionalProperties.put("contextStackLimit", openAPI.getPaths().size() * 2 + 300);
List<Map<String, Object>> replacements = new ArrayList<>();
Object[] replacementChars = specialCharReplacements.keySet().toArray();
@@ -247,7 +264,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
}
additionalProperties.put("specialCharReplacements", replacements);
super.preprocessSwagger(swagger);
super.preprocessOpenAPI(openAPI);
}
@@ -258,17 +275,15 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
* @return a string value used as the `dataType` field for model templates, `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return "Map.Map String " + getTypeDeclaration(inner);
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("[%s]", getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("Map.Map String ", getTypeDeclaration(inner));
}
return fixModelChars(super.getTypeDeclaration(p));
return fixModelChars(super.getTypeDeclaration(propertySchema));
}
/**
@@ -276,11 +291,11 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
* either language specific types via `typeMapping` or into complex models if there is not a mapping.
*
* @return a string value of the type or complex model for this property
* @see io.swagger.models.properties.Property
* @see io.swagger.v3.oas.models.media.Schema
*/
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema schema) {
String swaggerType = super.getSchemaType(schema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
@@ -297,20 +312,19 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
}
@Override
public String toInstantiationType(Property p) {
if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
Property additionalProperties2 = ap.getAdditionalProperties();
public String toInstantiationType(Schema propertySchema) {
if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema additionalProperties2 = (Schema) propertySchema.getAdditionalProperties();
String type = additionalProperties2.getType();
if (null == type) {
LOGGER.error("No Type defined for Additional Property " + additionalProperties2 + "\n" //
+ "\tIn Property: " + p);
+ "\tIn Property: " + propertySchema);
}
String inner = getSwaggerType(additionalProperties2);
String inner = getSchemaType(additionalProperties2);
return "(Map.Map Text " + inner + ")";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
} else if (propertySchema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) propertySchema;
String inner = getSchemaType(arraySchema.getItems());
// Return only the inner type; the wrapping with QueryList is done
// somewhere else, where we have access to the collection format.
return inner;
@@ -390,8 +404,8 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
@Override
public CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(resourcePath, httpMethod, operation, definitions, swagger);
public CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Schema> schemas, OpenAPI openAPI) {
CodegenOperation op = super.fromOperation(resourcePath, httpMethod, operation, schemas, openAPI);
List<String> path = pathToServantRoute(op.path, op.pathParams);
List<String> type = pathToClientType(op.path, op.pathParams);
@@ -399,7 +413,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
// Query parameters appended to routes
for (CodegenParameter param : op.queryParams) {
String paramType = param.dataType;
if (param.isListContainer) {
if (getBooleanValue(param, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
paramType = makeQueryListType(paramType, param.collectionFormat);
}
path.add("QueryParam \"" + param.baseName + "\" " + paramType);
@@ -430,7 +444,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
path.add("Header \"" + param.baseName + "\" " + param.dataType);
String paramType = param.dataType;
if (param.isListContainer) {
if (getBooleanValue(param, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
paramType = makeQueryListType(paramType, param.collectionFormat);
}
type.add("Maybe " + paramType);
@@ -499,8 +513,8 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
// Override fromModel to create the appropriate model namings
@Override
public CodegenModel fromModel(String name, Model mod, Map<String, Model> allDefinitions) {
CodegenModel model = super.fromModel(name, mod, allDefinitions);
public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allSchemas) {
CodegenModel model = super.fromModel(name, schema, allSchemas);
// Clean up the class name to remove invalid characters
model.classname = fixModelChars(model.classname);
@@ -517,11 +531,8 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
// Create newtypes for things with non-object types
String dataOrNewtype = "data";
// check if it's a ModelImpl before casting
if (!(mod instanceof ModelImpl)) {
return model;
}
String modelType = ((ModelImpl) mod).getType();
String modelType = schema.getType();
if(modelType != "object" && typeMapping.containsKey(modelType)) {
String newtype = typeMapping.get(modelType);
model.vendorExtensions.put("x-customNewtype", newtype);

View File

@@ -1,12 +1,19 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import io.swagger.models.properties.*;
import java.util.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class JMeterCodegen extends DefaultCodegen implements CodegenConfig {
@@ -83,7 +90,7 @@ public class JMeterCodegen extends DefaultCodegen implements CodegenConfig {
/*
* Reserved words. Override this with reserved words specific to your language
*/
reservedWords = new HashSet<String> (
reservedWords = new HashSet<String>(
Arrays.asList(
"sample1", // replace with static values
"sample2")
@@ -99,14 +106,15 @@ public class JMeterCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public void preprocessSwagger(Swagger swagger) {
if (swagger != null && swagger.getPaths() != null) {
for (String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if (path.getOperations() != null) {
for (Operation operation : path.getOperations()) {
public void preprocessOpenAPI(OpenAPI openAPI) {
if (openAPI != null && openAPI.getPaths() != null) {
for (String pathname : openAPI.getPaths().keySet()) {
PathItem path = openAPI.getPaths().get(pathname);
List<Operation> operations = path.readOperations();
if (operations != null && !operations.isEmpty()) {
for (Operation operation : operations) {
String pathWithDollars = pathname.replaceAll("\\{", "\\$\\{");
operation.setVendorExtension("x-path", pathWithDollars);
operation.addExtension("x-path", pathWithDollars);
}
}
}
@@ -152,18 +160,15 @@ public class JMeterCodegen extends DefaultCodegen implements CodegenConfig {
* @return a string value used as the `dataType` field for model templates, `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s[%s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s[String, %s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
}
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
/**
@@ -171,19 +176,20 @@ public class JMeterCodegen extends DefaultCodegen implements CodegenConfig {
* either language specific types via `typeMapping` or into complex models if there is not a mapping.
*
* @return a string value of the type or complex model for this property
* @see io.swagger.models.properties.Property
* @see io.swagger.v3.oas.models.media.Schema
*/
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String schemaType = super.getSchemaType(propertySchema);
String type = null;
if(typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type))
if (typeMapping.containsKey(schemaType)) {
type = typeMapping.get(schemaType);
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
} else {
type = schemaType;
}
else
type = swaggerType;
return toModelName(type);
}

View File

@@ -5,6 +5,7 @@ import java.io.File;
import java.util.List;
import java.util.Map;
import io.swagger.v3.oas.models.Operation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -18,7 +19,6 @@ import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.codegen.languages.features.GzipTestFeatures;
import io.swagger.codegen.languages.features.LoggingTestFeatures;
import io.swagger.codegen.languages.features.UseGenericResponseFeatures;
import io.swagger.models.Operation;
public class JavaCXFClientCodegen extends AbstractJavaCodegen
implements BeanValidationFeatures, UseGenericResponseFeatures, GzipTestFeatures, LoggingTestFeatures {

View File

@@ -1,10 +1,10 @@
package io.swagger.codegen.languages;
import java.io.File;
import java.util.List;
import java.util.Map;
import io.swagger.v3.oas.models.Operation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -17,7 +17,6 @@ import io.swagger.codegen.languages.features.CXFServerFeatures;
import io.swagger.codegen.languages.features.GzipTestFeatures;
import io.swagger.codegen.languages.features.LoggingTestFeatures;
import io.swagger.codegen.languages.features.UseGenericResponseFeatures;
import io.swagger.models.Operation;
public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
implements CXFServerFeatures, GzipTestFeatures, LoggingTestFeatures, UseGenericResponseFeatures

View File

@@ -1,7 +1,10 @@
package io.swagger.codegen.languages;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
import static java.util.Collections.sort;
import com.github.jknack.handlebars.internal.path.ThisPath;
import com.google.common.collect.LinkedListMultimap;
import io.swagger.codegen.*;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
@@ -17,6 +20,10 @@ import java.io.File;
import java.util.*;
import java.util.regex.Pattern;
/**
* new version of this class can be found on: https://github.com/swagger-api/swagger-codegen-templates
*/
@Deprecated
public class JavaClientCodegen extends AbstractJavaCodegen
implements BeanValidationFeatures, PerformBeanValidationFeatures,
GzipFeatures
@@ -111,6 +118,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
@Override
public void processOpts() {
super.processOpts();
embeddedTemplateDir = templateDir = "v2/Java";
if (additionalProperties.containsKey(USE_RX_JAVA) && additionalProperties.containsKey(USE_RX_JAVA2)) {
LOGGER.warn("You specified both RxJava versions 1 and 2 but they are mutually exclusive. Defaulting to v2.");
@@ -241,6 +249,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
setJava8Mode(true);
additionalProperties.put("java8", "true");
additionalProperties.put("jackson", "true");
apiTemplateFiles.put("apiImpl.mustache", "Impl.java");
apiTemplateFiles.put("rxApiImpl.mustache", ".java");
supportingFiles.remove(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml"));
@@ -314,10 +323,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
if (operation.hasConsumes == Boolean.TRUE) {
boolean hasConsumes = getBooleanValue(operation, CodegenConstants.HAS_CONSUMES_EXT_NAME);
if (hasConsumes) {
if (isMultipartType(operation.consumes)) {
operation.isMultipart = Boolean.TRUE;
operation.getVendorExtensions().put(CodegenConstants.IS_MULTIPART_EXT_NAME, Boolean.TRUE);
}
else {
operation.prioritizedContentTypes = prioritizeContentTypes(operation.consumes);
@@ -335,10 +345,12 @@ public class JavaClientCodegen extends AbstractJavaCodegen
sort(operation.allParams, new Comparator<CodegenParameter>() {
@Override
public int compare(CodegenParameter one, CodegenParameter another) {
if (one.isPathParam && another.isQueryParam) {
if (getBooleanValue(one, CodegenConstants.IS_PATH_PARAM_EXT_NAME)
&& getBooleanValue(another, CodegenConstants.IS_QUERY_PARAM_EXT_NAME)) {
return -1;
}
if (one.isQueryParam && another.isPathParam){
if (getBooleanValue(one, CodegenConstants.IS_QUERY_PARAM_EXT_NAME)
&& getBooleanValue(another, CodegenConstants.IS_PATH_PARAM_EXT_NAME)){
return 1;
}
@@ -348,7 +360,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
Iterator<CodegenParameter> iterator = operation.allParams.iterator();
while (iterator.hasNext()){
CodegenParameter param = iterator.next();
param.hasMore = iterator.hasNext();
param.getVendorExtensions().put(CodegenConstants.HAS_MORE_EXT_NAME, iterator.hasNext());
}
}
}
@@ -442,7 +454,8 @@ public class JavaClientCodegen extends AbstractJavaCodegen
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
if(!BooleanUtils.toBoolean(model.isEnum)) {
boolean isEnum = getBooleanValue(model, IS_ENUM_EXT_NAME);
if(!BooleanUtils.toBoolean(isEnum)) {
//final String lib = getLibrary();
//Needed imports for Jackson based libraries
if(additionalProperties.containsKey("jackson")) {
@@ -496,7 +509,8 @@ public class JavaClientCodegen extends AbstractJavaCodegen
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
boolean isEnum = getBooleanValue(cm, IS_ENUM_EXT_NAME);
if (Boolean.TRUE.equals(isEnum) && cm.allowableValues != null) {
cm.imports.add(importMapping.get("SerializedName"));
Map<String, String> item = new HashMap<String, String>();
item.put("import", importMapping.get("SerializedName"));

View File

@@ -6,9 +6,9 @@ import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.util.Yaml;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.core.util.Yaml;
import org.apache.commons.lang3.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -18,6 +18,14 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static io.swagger.codegen.CodegenConstants.HAS_ENUMS_EXT_NAME;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
/**
* new version of this class can be found on: https://github.com/swagger-api/swagger-codegen-templates
*/
@Deprecated
public class JavaInflectorServerCodegen extends AbstractJavaCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(JavaInflectorServerCodegen.class);
@@ -29,7 +37,7 @@ public class JavaInflectorServerCodegen extends AbstractJavaCodegen {
sourceFolder = "src/gen/java";
apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaInflector";
embeddedTemplateDir = templateDir = "v2/JavaInflector";
invokerPackage = "io.swagger.controllers";
artifactId = "swagger-inflector-server";
dateLibrary = "legacy"; //TODO: add joda support
@@ -72,9 +80,9 @@ public class JavaInflectorServerCodegen extends AbstractJavaCodegen {
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));
writeOptional(outputFolder, new SupportingFile("web.mustache", "src/main/webapp/WEB-INF", "web.xml"));
writeOptional(outputFolder, new SupportingFile("inflector.mustache", "", "inflector.yaml"));
supportingFiles.add(new SupportingFile("swagger.mustache",
"src/main/swagger",
"swagger.yaml")
supportingFiles.add(new SupportingFile("openapi3.mustache",
"src/main/resources",
"openapi3.yaml")
);
supportingFiles.add(new SupportingFile("StringUtil.mustache",
(sourceFolder + '/' + invokerPackage).replace(".", "/"), "StringUtil.java"));
@@ -148,10 +156,11 @@ public class JavaInflectorServerCodegen extends AbstractJavaCodegen {
super.postProcessModelProperty(model, property);
//Add imports for Jackson
if(!BooleanUtils.toBoolean(model.isEnum)) {
boolean isEnum = getBooleanValue(model, IS_ENUM_EXT_NAME);
if(!BooleanUtils.toBoolean(isEnum)) {
model.imports.add("JsonProperty");
if(BooleanUtils.toBoolean(model.hasEnums)) {
boolean hasEnums = getBooleanValue(model, HAS_ENUMS_EXT_NAME);
if(BooleanUtils.toBoolean(hasEnums)) {
model.imports.add("JsonValue");
}
}
@@ -168,7 +177,8 @@ public class JavaInflectorServerCodegen extends AbstractJavaCodegen {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
boolean isEnum = getBooleanValue(cm, IS_ENUM_EXT_NAME);
if (Boolean.TRUE.equals(isEnum) && cm.allowableValues != null) {
cm.imports.add(importMapping.get("JsonValue"));
Map<String, String> item = new HashMap<String, String>();
item.put("import", importMapping.get("JsonValue"));
@@ -199,10 +209,10 @@ public class JavaInflectorServerCodegen extends AbstractJavaCodegen {
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
Swagger swagger = (Swagger)objs.get("swagger");
if(swagger != null) {
OpenAPI openAPI = (OpenAPI) objs.get("openAPI");
if(openAPI != null) {
try {
objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger));
objs.put("openapi3-yaml", Yaml.mapper().writeValueAsString(openAPI));
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}

View File

@@ -7,6 +7,8 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import org.apache.commons.io.FileUtils;
import io.swagger.codegen.CliOption;
@@ -15,9 +17,7 @@ import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.util.Json;
import io.swagger.v3.core.util.Json;
public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen
{
@@ -150,15 +150,15 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen
}
@Override
public void preprocessSwagger(Swagger swagger) {
public void preprocessOpenAPI(OpenAPI openAPI) {
//copy input swagger to output folder
try {
String swaggerJson = Json.pretty(swagger);
String swaggerJson = Json.pretty(openAPI);
FileUtils.writeStringToFile(new File(outputFolder + File.separator + "swagger.json"), swaggerJson);
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e.getCause());
}
super.preprocessSwagger(swagger);
super.preprocessOpenAPI(openAPI);
}
@Override

View File

@@ -1,14 +1,21 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.models.Operation;
import java.util.*;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.Operation;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import static io.swagger.codegen.CodegenConstants.HAS_ENUMS_EXT_NAME;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
protected static final String LIBRARY_JERSEY1 = "jersey1";
@@ -72,10 +79,11 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
}
//Add imports for Jackson
if(!BooleanUtils.toBoolean(model.isEnum)) {
boolean isEnum = getBooleanValue(model, IS_ENUM_EXT_NAME);
if(!BooleanUtils.toBoolean(isEnum)) {
model.imports.add("JsonProperty");
if(BooleanUtils.toBoolean(model.hasEnums)) {
boolean hasEnums = getBooleanValue(model, HAS_ENUMS_EXT_NAME);
if(BooleanUtils.toBoolean(hasEnums)) {
model.imports.add("JsonValue");
}
}
@@ -131,7 +139,8 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
boolean isEnum = getBooleanValue(cm, IS_ENUM_EXT_NAME);
if (Boolean.TRUE.equals(isEnum) && cm.allowableValues != null) {
cm.imports.add(importMapping.get("JsonValue"));
Map<String, String> item = new HashMap<String, String>();
item.put("import", importMapping.get("JsonValue"));

View File

@@ -1,13 +1,24 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Operation;
import java.util.*;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.Operation;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static io.swagger.codegen.CodegenConstants.HAS_ENUMS_EXT_NAME;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class JavaMSF4JServerCodegen extends AbstractJavaJAXRSServerCodegen {
protected static final String LIBRARY_JERSEY1 = "jersey1";
@@ -55,10 +66,11 @@ public class JavaMSF4JServerCodegen extends AbstractJavaJAXRSServerCodegen {
}
//Add imports for Jackson
if(!BooleanUtils.toBoolean(model.isEnum)) {
boolean isEnum = getBooleanValue(model, IS_ENUM_EXT_NAME);
if(!BooleanUtils.toBoolean(isEnum)) {
model.imports.add("JsonProperty");
if(BooleanUtils.toBoolean(model.hasEnums)) {
boolean hasEnums = getBooleanValue(model, HAS_ENUMS_EXT_NAME);
if(BooleanUtils.toBoolean(hasEnums)) {
model.imports.add("JsonValue");
}
}
@@ -110,7 +122,8 @@ public class JavaMSF4JServerCodegen extends AbstractJavaJAXRSServerCodegen {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
boolean isEnum = getBooleanValue(cm, IS_ENUM_EXT_NAME);
if (Boolean.TRUE.equals(isEnum) && cm.allowableValues != null) {
cm.imports.add(importMapping.get("JsonValue"));
Map<String, String> item = new HashMap<String, String>();
item.put("import", importMapping.get("JsonValue"));

View File

@@ -6,6 +6,7 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConstants;
@@ -16,12 +17,13 @@ import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import io.swagger.models.Tag;
import io.swagger.models.parameters.FormParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.codegen.utils.URLPathUtil;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.tags.Tag;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
/**
* Created by prokarma on 04/09/17.
@@ -94,9 +96,10 @@ public class JavaPKMSTServerCodegen extends AbstractJavaCodegen {
private static String getAccept(Operation operation) {
String accepts = null;
String defaultContentType = "application/json";
if (operation.getProduces() != null && !operation.getProduces().isEmpty()) {
final Set<String> producesInfo = getProducesInfo(operation);
if (producesInfo != null && !producesInfo.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (String produces : operation.getProduces()) {
for (String produces : producesInfo) {
if (defaultContentType.equalsIgnoreCase(produces)) {
accepts = defaultContentType;
break;
@@ -396,12 +399,13 @@ public class JavaPKMSTServerCodegen extends AbstractJavaCodegen {
final ArrayList<CodegenParameter> copy = new ArrayList<>(allParams);
allParams.clear();
for (CodegenParameter p : copy) {
if (!p.isHeaderParam) {
allParams.add(p);
for (CodegenParameter codegenParameter : copy) {
boolean isHeaderParam = getBooleanValue(codegenParameter, CodegenConstants.IS_HEADER_PARAM_EXT_NAME);
if (!isHeaderParam) {
allParams.add(codegenParameter);
}
}
allParams.get(allParams.size() - 1).hasMore = false;
allParams.get(allParams.size() - 1).getVendorExtensions().put(CodegenConstants.HAS_MORE_EXT_NAME, Boolean.FALSE);
}
/**
@@ -444,11 +448,13 @@ public class JavaPKMSTServerCodegen extends AbstractJavaCodegen {
property.example = null;
}
boolean isEnum = getBooleanValue(model, CodegenConstants.IS_ENUM_EXT_NAME);
// Add imports for Jackson
if (!Boolean.TRUE.equals(model.isEnum)) {
if (!Boolean.TRUE.equals(isEnum)) {
model.imports.add("JsonProperty");
if (Boolean.TRUE.equals(model.hasEnums)) {
boolean hasEnums = getBooleanValue(model, CodegenConstants.HAS_ENUMS_EXT_NAME);
if (Boolean.TRUE.equals(hasEnums)) {
model.imports.add("JsonValue");
}
} else { // enum class
@@ -470,10 +476,11 @@ public class JavaPKMSTServerCodegen extends AbstractJavaCodegen {
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
CodegenModel codegenModel = (CodegenModel) mo.get("model");
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
cm.imports.add(this.importMapping.get("JsonValue"));
boolean isEnum = getBooleanValue(codegenModel, CodegenConstants.IS_ENUM_EXT_NAME);
if (Boolean.TRUE.equals(isEnum) && codegenModel.allowableValues != null) {
codegenModel.imports.add(this.importMapping.get("JsonValue"));
Map<String, String> item = new HashMap<String, String>();
item.put("import", this.importMapping.get("JsonValue"));
imports.add(item);
@@ -485,14 +492,14 @@ public class JavaPKMSTServerCodegen extends AbstractJavaCodegen {
@SuppressWarnings("unchecked")
@Override
public void preprocessSwagger(Swagger swagger) {
super.preprocessSwagger(swagger);
if (swagger == null || swagger.getPaths() == null) {
public void preprocessOpenAPI(OpenAPI openAPI) {
super.preprocessOpenAPI(openAPI);
if (openAPI == null || openAPI.getPaths() == null) {
return;
}
if (swagger.getTags() != null) {
if (openAPI.getTags() != null) {
List<ResourcePath> resourcePaths = new ArrayList<>();
for (Tag tag : swagger.getTags()) {
for (Tag tag : openAPI.getTags()) {
ResourcePath resourcePath = new ResourcePath();
resourcePath.setPath(tag.getName());
resourcePaths.add(resourcePath);
@@ -501,7 +508,7 @@ public class JavaPKMSTServerCodegen extends AbstractJavaCodegen {
}
// get vendor extensions
Map<String, Object> vendorExt = swagger.getInfo().getVendorExtensions();
Map<String, Object> vendorExt = openAPI.getInfo().getExtensions();
if (vendorExt != null && !vendorExt.toString().equals("")) {
if (vendorExt.containsKey("x-codegen")) {
@@ -525,39 +532,40 @@ public class JavaPKMSTServerCodegen extends AbstractJavaCodegen {
}
}
for (String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if (path.getOperations() == null) {
for (String pathname : openAPI.getPaths().keySet()) {
PathItem path = openAPI.getPaths().get(pathname);
List<Operation> operations = path.readOperations();
if (operations == null) {
continue;
}
for (Operation operation : path.getOperations()) {
for (Operation operation : operations) {
boolean hasFormParameters = false;
for (Parameter parameter : operation.getParameters()) {
if (parameter instanceof FormParameter) {
hasFormParameters = true;
}
final Set<String> consumesInfo = getConsumesInfo(operation);
if (consumesInfo != null && !consumesInfo.isEmpty()) {
hasFormParameters = consumesInfo
.stream()
.anyMatch(contentType -> contentType.equalsIgnoreCase("application/x-www-form-urlencoded")
|| contentType.equalsIgnoreCase("multipart/form-data"));
}
// only add content-Type if its no a GET-Method
if (path.getGet() != null || !operation.equals(path.getGet())) {
String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded"
: "application/json";
String contentType = operation.getConsumes() == null || operation.getConsumes().isEmpty()
? defaultContentType : operation.getConsumes().get(0);
operation.setVendorExtension("x-contentType", contentType);
String contentType = consumesInfo == null || consumesInfo.isEmpty()
? defaultContentType : consumesInfo.stream().findFirst().get();
operation.addExtension("x-contentType", contentType);
}
String accepts = getAccept(operation);
operation.setVendorExtension("x-accepts", accepts);
operation.addExtension("x-accepts", accepts);
}
}
if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath("");
}
if (!additionalProperties.containsKey(TITLE)) {
// From the title, compute a reasonable name for the package and the
// API
String title = swagger.getInfo().getTitle();
String title = openAPI.getInfo().getTitle();
// Drop any API suffix
if (title != null) {
@@ -571,7 +579,7 @@ public class JavaPKMSTServerCodegen extends AbstractJavaCodegen {
additionalProperties.put(TITLE, this.title);
}
String host = swagger.getHost();
String host = URLPathUtil.getHost(openAPI);
String port = "8008";
if (host != null) {
String[] parts = host.split(":");
@@ -581,11 +589,12 @@ public class JavaPKMSTServerCodegen extends AbstractJavaCodegen {
}
this.additionalProperties.put("serverPort", port);
if (swagger.getPaths() != null) {
for (String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if (path.getOperations() != null) {
for (Operation operation : path.getOperations()) {
if (openAPI.getPaths() != null) {
for (String pathname : openAPI.getPaths().keySet()) {
PathItem path = openAPI.getPaths().get(pathname);
List<Operation> operations = path.readOperations();
if (operations != null) {
for (Operation operation : operations) {
if (operation.getTags() != null) {
List<Map<String, String>> tags = new ArrayList<Map<String, String>>();
for (String tag : operation.getTags()) {
@@ -601,7 +610,7 @@ public class JavaPKMSTServerCodegen extends AbstractJavaCodegen {
String tag = operation.getTags().get(0);
operation.setTags(Arrays.asList(tag));
}
operation.setVendorExtension("x-tags", tags);
operation.addExtension("x-tags", tags);
}
}
}

View File

@@ -1,11 +1,18 @@
package io.swagger.codegen.languages;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.codegen.*;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.models.Model;
import io.swagger.models.Swagger;
import io.swagger.util.Json;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.core.util.Json;
import java.io.File;
import java.util.List;
@@ -13,6 +20,8 @@ import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class JavaPlayFrameworkCodegen extends AbstractJavaCodegen implements BeanValidationFeatures {
public static final String TITLE = "title";
@@ -202,8 +211,8 @@ public class JavaPlayFrameworkCodegen extends AbstractJavaCodegen implements Bea
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allSchemas) {
CodegenModel codegenModel = super.fromModel(name, schema, allSchemas);
if(codegenModel.description != null) {
codegenModel.imports.remove("ApiModel");
}
@@ -252,13 +261,14 @@ public class JavaPlayFrameworkCodegen extends AbstractJavaCodegen implements Bea
for (CodegenOperation operation : ops) {
for (CodegenParameter param : operation.allParams) {
if (param.isFormParam && param.isFile) {
if (getBooleanValue(param, CodegenConstants.IS_FORM_PARAM_EXT_NAME)
&& getBooleanValue(param, CodegenConstants.IS_FILE_EXT_NAME)) {
param.dataType = "Http.MultipartFormData.FilePart";
}
}
for (CodegenParameter param : operation.formParams) {
if (param.isFile) {
if (getBooleanValue(param, CodegenConstants.IS_FILE_EXT_NAME)) {
param.dataType = "Http.MultipartFormData.FilePart";
}
}
@@ -318,11 +328,11 @@ public class JavaPlayFrameworkCodegen extends AbstractJavaCodegen implements Bea
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
Swagger swagger = (Swagger)objs.get("swagger");
System.out.println("swagger" + swagger.toString());
if(swagger != null) {
OpenAPI openAPI = (OpenAPI) objs.get("openapi");
System.out.println("openapi" + openAPI.toString());
if(openAPI != null) {
try {
objs.put("swagger-json", Json.pretty().writeValueAsString(swagger));
objs.put("swagger-json", Json.pretty().writeValueAsString(openAPI));
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}

View File

@@ -6,18 +6,21 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.swagger.v3.oas.models.Operation;
import org.apache.commons.lang3.BooleanUtils;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.codegen.languages.features.JbossFeature;
import io.swagger.codegen.languages.features.SwaggerFeatures;
import io.swagger.models.Operation;
import static io.swagger.codegen.CodegenConstants.HAS_ENUMS_EXT_NAME;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class JavaResteasyEapServerCodegen extends AbstractJavaJAXRSServerCodegen
implements JbossFeature, BeanValidationFeatures, SwaggerFeatures {
@@ -138,11 +141,12 @@ public class JavaResteasyEapServerCodegen extends AbstractJavaJAXRSServerCodegen
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
boolean isEnum = getBooleanValue(model, IS_ENUM_EXT_NAME);
// Add imports for Jackson
if (!BooleanUtils.toBoolean(model.isEnum)) {
if (!BooleanUtils.toBoolean(isEnum)) {
model.imports.add("JsonProperty");
if (BooleanUtils.toBoolean(model.hasEnums)) {
boolean hasEnums = getBooleanValue(model, HAS_ENUMS_EXT_NAME);
if (BooleanUtils.toBoolean(hasEnums)) {
model.imports.add("JsonValue");
}
}
@@ -159,7 +163,8 @@ public class JavaResteasyEapServerCodegen extends AbstractJavaJAXRSServerCodegen
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
boolean isEnum = getBooleanValue(cm, IS_ENUM_EXT_NAME);
if (Boolean.TRUE.equals(isEnum) && cm.allowableValues != null) {
cm.imports.add(importMapping.get("JsonValue"));
Map<String, String> item = new HashMap<String, String>();
item.put("import", importMapping.get("JsonValue"));

View File

@@ -1,14 +1,23 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.languages.features.JbossFeature;
import io.swagger.models.Operation;
import io.swagger.v3.oas.models.Operation;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static io.swagger.codegen.CodegenConstants.HAS_ENUMS_EXT_NAME;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen implements JbossFeature {
@@ -136,11 +145,12 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen im
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
boolean isEnum = getBooleanValue(model, IS_ENUM_EXT_NAME);
//Add imports for Jackson
if(!BooleanUtils.toBoolean(model.isEnum)) {
if(!BooleanUtils.toBoolean(isEnum)) {
model.imports.add("JsonProperty");
if(BooleanUtils.toBoolean(model.hasEnums)) {
boolean hasEnums = getBooleanValue(model, HAS_ENUMS_EXT_NAME);
if(BooleanUtils.toBoolean(hasEnums)) {
model.imports.add("JsonValue");
}
}
@@ -157,7 +167,8 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen im
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
boolean isEnum = getBooleanValue(cm, IS_ENUM_EXT_NAME);
if (Boolean.TRUE.equals(isEnum) && cm.allowableValues != null) {
cm.imports.add(importMapping.get("JsonValue"));
Map<String, String> item = new HashMap<String, String>();
item.put("import", importMapping.get("JsonValue"));

View File

@@ -6,20 +6,25 @@ import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.HttpMethod;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import io.swagger.util.Json;
import io.swagger.codegen.utils.URLPathUtil;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.core.util.Json;
import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.swagger.codegen.CodegenConstants.HAS_ENUMS_EXT_NAME;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class JavaVertXServerCodegen extends AbstractJavaCodegen {
protected String resourceFolder = "src/main/resources";
@@ -139,10 +144,12 @@ public class JavaVertXServerCodegen extends AbstractJavaCodegen {
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
if (!model.isEnum) {
boolean isEnum = getBooleanValue(model, IS_ENUM_EXT_NAME);
if (!isEnum) {
model.imports.add("JsonInclude");
model.imports.add("JsonProperty");
if (model.hasEnums) {
boolean hasEnums = getBooleanValue(model, HAS_ENUMS_EXT_NAME);
if (hasEnums) {
model.imports.add("JsonValue");
}
}
@@ -172,17 +179,15 @@ public class JavaVertXServerCodegen extends AbstractJavaCodegen {
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation,
Map<String, Model> definitions, Swagger swagger) {
CodegenOperation codegenOperation =
super.fromOperation(path, httpMethod, operation, definitions, swagger);
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Schema> definitions, OpenAPI openAPI) {
CodegenOperation codegenOperation = super.fromOperation(path, httpMethod, operation, definitions, openAPI);
codegenOperation.imports.add("MainApiException");
return codegenOperation;
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allSchemas) {
CodegenModel codegenModel = super.fromModel(name, schema, allSchemas);
codegenModel.imports.remove("ApiModel");
codegenModel.imports.remove("ApiModelProperty");
return codegenModel;
@@ -190,21 +195,26 @@ public class JavaVertXServerCodegen extends AbstractJavaCodegen {
}
@Override
public void preprocessSwagger(Swagger swagger) {
super.preprocessSwagger(swagger);
public void preprocessOpenAPI(OpenAPI openAPI) {
super.preprocessOpenAPI(openAPI);
// add full swagger definition in a mustache parameter
String swaggerDef = Json.pretty(swagger);
String swaggerDef = Json.pretty(openAPI);
this.additionalProperties.put("fullSwagger", swaggerDef);
// add server port from the swagger file, 8080 by default
String host = swagger.getHost();
String port = extractPortFromHost(host);
String port = null;
final URL url = URLPathUtil.getServerURL(openAPI);
if(url != null) {
port = String.valueOf(url.getPort());
} else {
port = "8080";
}
this.additionalProperties.put("serverPort", port);
// retrieve api version from swagger file, 1.0.0-SNAPSHOT by default
if (swagger.getInfo() != null && swagger.getInfo().getVersion() != null) {
artifactVersion = apiVersion = swagger.getInfo().getVersion();
if (openAPI.getInfo() != null && openAPI.getInfo().getVersion() != null) {
artifactVersion = apiVersion = openAPI.getInfo().getVersion();
} else {
artifactVersion = apiVersion;
}
@@ -213,30 +223,29 @@ public class JavaVertXServerCodegen extends AbstractJavaCodegen {
* manage operation & custom serviceId because operationId field is not
* required and may be empty
*/
Map<String, Path> paths = swagger.getPaths();
Map<String, PathItem> paths = openAPI.getPaths();
if (paths != null) {
for (Entry<String, Path> entry : paths.entrySet()) {
for (Entry<String, PathItem> entry : paths.entrySet()) {
manageOperationNames(entry.getValue(), entry.getKey());
}
}
this.additionalProperties.remove("gson");
}
private void manageOperationNames(Path path, String pathname) {
private void manageOperationNames(PathItem path, String pathname) {
String serviceIdTemp;
Map<HttpMethod, Operation> operationMap = path.getOperationMap();
Map<PathItem.HttpMethod, Operation> operationMap = path.readOperationsMap();
if (operationMap != null) {
for (Entry<HttpMethod, Operation> entry : operationMap.entrySet()) {
for (Entry<PathItem.HttpMethod, Operation> entry : operationMap.entrySet()) {
serviceIdTemp = computeServiceId(pathname, entry);
entry.getValue().setVendorExtension("x-serviceid", serviceIdTemp);
entry.getValue().setVendorExtension("x-serviceid-varname",
serviceIdTemp.toUpperCase() + "_SERVICE_ID");
entry.getValue().addExtension("x-serviceid", serviceIdTemp);
entry.getValue().addExtension("x-serviceid-varname", serviceIdTemp.toUpperCase() + "_SERVICE_ID");
}
}
}
private String computeServiceId(String pathname, Entry<HttpMethod, Operation> entry) {
private String computeServiceId(String pathname, Entry<PathItem.HttpMethod, Operation> entry) {
String operationId = entry.getValue().getOperationId();
return (operationId != null) ? operationId
: entry.getKey().name()

View File

@@ -1,7 +1,6 @@
package io.swagger.codegen.languages;
import com.google.common.base.Strings;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
@@ -10,28 +9,19 @@ import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.models.ArrayModel;
import io.swagger.models.Info;
import io.swagger.models.License;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -44,6 +34,10 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static io.swagger.codegen.CodegenConstants.HAS_ENUMS_EXT_NAME;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class JavascriptClientCodegen extends DefaultCodegen implements CodegenConfig {
@SuppressWarnings("hiding")
private static final Logger LOGGER = LoggerFactory.getLogger(JavascriptClientCodegen.class);
@@ -273,11 +267,11 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
}
@Override
public void preprocessSwagger(Swagger swagger) {
super.preprocessSwagger(swagger);
public void preprocessOpenAPI(OpenAPI openAPI) {
super.preprocessOpenAPI(openAPI);
if (swagger.getInfo() != null) {
Info info = swagger.getInfo();
if (openAPI.getInfo() != null) {
Info info = openAPI.getInfo();
if (StringUtils.isBlank(projectName) && info.getTitle() != null) {
// when projectName is not specified, generate it from info.title
projectName = sanitizeName(dashize(info.getTitle()));
@@ -568,67 +562,42 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return "{String: " + getTypeDeclaration(inner) + "}";
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) propertySchema;
Schema inner = arraySchema.getItems();
return String.format("[%s]", getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("{String: " + getTypeDeclaration(inner) + "}");
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
return "'" + dp.getDefault() + "'";
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof DateProperty) {
// TODO
} else if (p instanceof DateTimeProperty) {
// TODO
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
public String toDefaultValue(Schema propertySchema) {
if (propertySchema instanceof StringSchema) {
if (propertySchema.getDefault() != null) {
return String.format("'%s'", propertySchema.getDefault());
}
}
if (propertySchema instanceof DateSchema || propertySchema instanceof DateTimeSchema) {
// TODO
return null;
}
if (propertySchema.getDefault() != null) {
return propertySchema.getDefault().toString();
}
return null;
}
@Override
public String toDefaultValueWithParam(String name, Property p) {
String type = normalizeType(getTypeDeclaration(p));
if (p instanceof RefProperty) {
return " = " + type + ".constructFromObject(data['" + name + "']);";
public String toDefaultValueWithParam(String name, Schema propertySchema) {
String type = normalizeType(getTypeDeclaration(propertySchema));
if (StringUtils.isNotBlank(propertySchema.get$ref())) {
return String.format(" = %s.constructFromObject(data['%s']);", type, name);
} else {
return " = ApiClient.convertToType(data['" + name + "'], " + type + ");";
return String.format(" = ApiClient.convertToType(data['%s'], %s);", name, type);
}
}
@@ -681,9 +650,9 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
if (example == null) {
example = "null";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
example = "[" + example + "]";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME)) {
example = "{key: " + example + "}";
}
@@ -701,19 +670,19 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String schemaType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (typeMapping.containsKey(schemaType)) {
type = typeMapping.get(schemaType);
if (!needToImport(type)) {
return type;
}
} else {
type = swaggerType;
type = schemaType;
}
if (null == type) {
LOGGER.error("No Type defined for Property " + p);
LOGGER.error("No Type defined for Property " + propertySchema);
}
return toModelName(type);
}
@@ -738,8 +707,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Schema> schemas, OpenAPI openAPI) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, schemas, openAPI);
if (op.returnType != null) {
op.returnType = normalizeType(op.returnType);
}
@@ -776,27 +745,25 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
if (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) {
final Model parentModel = allDefinitions.get(codegenModel.parentSchema);
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel, allDefinitions);
public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allSchemas) {
CodegenModel codegenModel = super.fromModel(name, schema, allSchemas);
boolean hasEnums = getBooleanValue(codegenModel, HAS_ENUMS_EXT_NAME);
if (allSchemas != null && codegenModel != null && codegenModel.parent != null && hasEnums) {
final Schema parentModel = allSchemas.get(codegenModel.parentSchema);
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel, allSchemas);
codegenModel = JavascriptClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel);
}
if (model instanceof ArrayModel) {
ArrayModel am = (ArrayModel) model;
if (am.getItems() != null) {
if (schema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) schema;
if (arraySchema.getItems() != null) {
codegenModel.vendorExtensions.put("x-isArray", true);
codegenModel.vendorExtensions.put("x-itemType", getSwaggerType(am.getItems()));
}
} else if (model instanceof ModelImpl) {
ModelImpl mm = (ModelImpl)model;
if (mm.getAdditionalProperties() != null) {
codegenModel.vendorExtensions.put("x-isMap", true);
codegenModel.vendorExtensions.put("x-itemType", getSwaggerType(mm.getAdditionalProperties()));
codegenModel.vendorExtensions.put("x-itemType", getSchemaType(arraySchema.getItems()));
}
}
if (schema.getAdditionalProperties() != null && hasSchemaProperties(schema)) {
codegenModel.vendorExtensions.put("x-isMap", true);
codegenModel.vendorExtensions.put("x-itemType", getSchemaType((Schema) schema.getAdditionalProperties()));
}
return codegenModel;
}
@@ -823,14 +790,15 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
}
private String getJSDocType(CodegenModel cm, CodegenProperty cp) {
if (Boolean.TRUE.equals(cp.isContainer)) {
if (getBooleanValue(cp, CodegenConstants.IS_CONTAINER_EXT_NAME)) {
if (cp.containerType.equals("array"))
return "Array.<" + getJSDocType(cm, cp.items) + ">";
else if (cp.containerType.equals("map"))
return "Object.<String, " + getJSDocType(cm, cp.items) + ">";
}
String dataType = trimBrackets(cp.datatypeWithEnum);
if (cp.isEnum) {
boolean isEnum = getBooleanValue(cp, IS_ENUM_EXT_NAME);
if (isEnum) {
dataType = cm.classname + '.' + dataType;
}
if (isModelledType(cp))
@@ -840,16 +808,17 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
private boolean isModelledType(CodegenProperty cp) {
// N.B. enums count as modelled types, file is not modelled (SuperAgent uses some 3rd party library).
return cp.isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.datatype : cp.baseType);
boolean isEnum = getBooleanValue(cp, IS_ENUM_EXT_NAME);
return isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.datatype : cp.baseType);
}
private String getJSDocType(CodegenParameter cp) {
String dataType = trimBrackets(cp.dataType);
if (isModelledType(cp))
dataType = getModelledType(dataType);
if (Boolean.TRUE.equals(cp.isListContainer)) {
if (getBooleanValue(cp, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
return "Array.<" + dataType + ">";
} else if (Boolean.TRUE.equals(cp.isMapContainer)) {
} else if (getBooleanValue(cp, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME)) {
return "Object.<String, " + dataType + ">";
}
return dataType;
@@ -857,7 +826,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
private boolean isModelledType(CodegenParameter cp) {
// N.B. enums count as modelled types, file is not modelled (SuperAgent uses some 3rd party library).
return cp.isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.dataType : cp.baseType);
return getBooleanValue(cp, CodegenConstants.IS_ENUM_EXT_NAME) || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.dataType : cp.baseType);
}
private String getJSDocType(CodegenOperation co) {
@@ -865,9 +834,9 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
if (returnType != null) {
if (isModelledType(co))
returnType = getModelledType(returnType);
if (Boolean.TRUE.equals(co.isListContainer)) {
if (getBooleanValue(co, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
return "Array.<" + returnType + ">";
} else if (Boolean.TRUE.equals(co.isMapContainer)) {
} else if (getBooleanValue(co, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME)) {
return "Object.<String, " + returnType + ">";
}
}
@@ -984,7 +953,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
// Because the child models extend the parents, the enums will be available via the parent.
// Only bother with reconciliation if the parent model has enums.
if (parentCodegenModel.hasEnums) {
boolean hasEnums = getBooleanValue(parentCodegenModel, HAS_ENUMS_EXT_NAME);
if (hasEnums) {
// Get the properties for the parent and child models
final List<CodegenProperty> parentModelCodegenProperties = parentCodegenModel.vars;
@@ -994,13 +964,15 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
boolean removedChildEnum = false;
for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) {
// Look for enums
if (parentModelCodegenPropery.isEnum) {
boolean isEnum = getBooleanValue(parentModelCodegenPropery, IS_ENUM_EXT_NAME);
if (isEnum) {
// Now that we have found an enum in the parent class,
// and search the child class for the same enum.
Iterator<CodegenProperty> iterator = codegenProperties.iterator();
while (iterator.hasNext()) {
CodegenProperty codegenProperty = iterator.next();
if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) {
isEnum = getBooleanValue(codegenProperty, IS_ENUM_EXT_NAME);
if (isEnum && codegenProperty.equals(parentModelCodegenPropery)) {
// We found an enum in the child class that is
// a duplicate of the one in the parent, so remove it.
iterator.remove();
@@ -1015,7 +987,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
int count = 0, numVars = codegenProperties.size();
for(CodegenProperty codegenProperty : codegenProperties) {
count += 1;
codegenProperty.hasMore = (count < numVars) ? true : false;
codegenProperty.getVendorExtensions().put(CodegenConstants.HAS_MORE_EXT_NAME, (count < numVars));
}
codegenModel.vars = codegenProperties;
}

View File

@@ -1,16 +1,27 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.models.Swagger;
import java.util.TreeSet;
import java.util.*;
import java.io.File;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.lang3.StringUtils;
import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String USE_ES6 = "useEs6";
@@ -93,8 +104,8 @@ public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implem
}
@Override
public void preprocessSwagger(Swagger swagger) {
super.preprocessSwagger(swagger);
public void preprocessOpenAPI(OpenAPI openAPI) {
super.preprocessOpenAPI(openAPI);
if (useEs6) {
embeddedTemplateDir = templateDir = "Javascript-Closure-Angular/es6";
@@ -200,39 +211,35 @@ public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implem
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<!" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return "Object<!string, "+ getTypeDeclaration(inner) + ">";
} else if (p instanceof FileProperty) {
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s<!%s>", getSchemaType(propertySchema), getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("Object<!string, %s>", getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema) {
return "Object";
}
String type = super.getTypeDeclaration(p);
if (type.equals("boolean") ||
type.equals("Date") ||
type.equals("number") ||
type.equals("string")) {
String type = super.getTypeDeclaration(propertySchema);
if (type.equals("boolean") || type.equals("Date") || type.equals("number") || type.equals("string")) {
return type;
}
return apiPackage + "." + type;
}
return String.format("%s.%s", apiPackage, type);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String schemaType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (typeMapping.containsKey(schemaType)) {
type = typeMapping.get(schemaType);
if (languageSpecificPrimitives.contains(type)) {
return type;
}
} else
type = swaggerType;
} else {
type = schemaType;
}
return type;
}
@@ -246,7 +253,8 @@ public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implem
cm.imports = new TreeSet(cm.imports);
for (CodegenProperty var : cm.vars) {
// handle default value for enum, e.g. available => StatusEnum.available
if (var.isEnum && var.defaultValue != null && !"null".equals(var.defaultValue)) {
boolean isEnum = getBooleanValue(var, IS_ENUM_EXT_NAME);
if (isEnum && var.defaultValue != null && !"null".equals(var.defaultValue)) {
var.defaultValue = var.datatypeWithEnum + "." + var.defaultValue;
}
}

View File

@@ -1,9 +1,14 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -379,21 +384,20 @@ public class KotlinClientCodegen extends DefaultCodegen implements CodegenConfig
/**
* returns the swagger type for the property
*
* @param p Swagger property object
* @param propertySchema Schema property object
* @return string presentation of the type
**/
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type;
// This maps, for example, long -> kotlin.Long based on hashes in this type's constructor
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
public String getSchemaType(Schema propertySchema) {
String schemaType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(schemaType)) {
type = typeMapping.get(schemaType);
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
} else {
type = swaggerType;
type = schemaType;
}
return toModelName(type);
}
@@ -401,23 +405,20 @@ public class KotlinClientCodegen extends DefaultCodegen implements CodegenConfig
/**
* Output the type declaration of the property
*
* @param p Swagger Property object
* @param propertySchema Schema Property object
* @return a string presentation of the property type
*/
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
// Maps will be keyed only by primitive Kotlin string
return getSwaggerType(p) + "<kotlin.String, " + getTypeDeclaration(inner) + ">";
@Override
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s<%s>", getSchemaType(propertySchema), getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s<kotlin.String, %s>", getSchemaType(propertySchema), getTypeDeclaration(inner));
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
/**

View File

@@ -1,19 +1,30 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.parameters.Parameter;
import java.io.File;
import java.util.*;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig {
static Logger LOGGER = LoggerFactory.getLogger(LuaClientCodegen.class);
@@ -311,47 +322,45 @@ public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getTypeDeclaration(inner);
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
public String getTypeDeclaration(Schema schema) {
if(schema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) schema;
Schema inner = arraySchema.getItems();
return getTypeDeclaration(inner);
} else if (schema instanceof MapSchema && hasSchemaProperties(schema)) {
return getTypeDeclaration((Schema) schema.getAdditionalProperties());
}
// Not using the supertype invocation, because we want to UpperCamelize
// the type.
String swaggerType = getSwaggerType(p);
if (typeMapping.containsKey(swaggerType)) {
return typeMapping.get(swaggerType);
// Not using the supertype invocation, because we want to UpperCamelize the type.
String schemaType = getSchemaType(schema);
if (typeMapping.containsKey(schemaType)) {
return typeMapping.get(schemaType);
}
if (typeMapping.containsValue(swaggerType)) {
return swaggerType;
if (typeMapping.containsValue(schemaType)) {
return schemaType;
}
if (languageSpecificPrimitives.contains(swaggerType)) {
return swaggerType;
if (languageSpecificPrimitives.contains(schemaType)) {
return schemaType;
}
return toModelName(swaggerType);
return toModelName(schemaType);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String schemaType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type))
return (type);
if (typeMapping.containsKey(schemaType)) {
type = typeMapping.get(schemaType);
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
} else {
type = swaggerType;
type = schemaType;
}
return type;
return toModelName(type);
}
@Override

View File

@@ -1,14 +1,14 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import java.util.*;
import java.io.File;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class LumenServerCodegen extends AbstractPhpCodegen
{

View File

@@ -7,17 +7,16 @@ import static java.util.Arrays.asList;
import static java.util.UUID.randomUUID;
import static org.apache.commons.lang3.StringUtils.capitalize;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.utils.ModelUtils;
import io.swagger.models.Swagger;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
@@ -27,6 +26,11 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import io.swagger.codegen.utils.URLPathUtil;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -48,8 +52,8 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen {
private static final String PACKAGE_CONTEXT = "packageContext";
private static final String ASYNC_SERVER = "asyncServer";
private static final Map<String, Predicate<Property>> propertyToSwaggerTypeMapping =
createPropertyToSwaggerTypeMapping();
private static final Map<String, Predicate<Schema>> propertyToSwaggerTypeMapping =
createPropertyToSchemaTypeMapping();
private String packageGuid = "{" + randomUUID().toString().toUpperCase() + "}";
@@ -248,7 +252,7 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen {
log.debug("Processing parents: " + parentModels);
for (final String parent : parentModels) {
final CodegenModel parentModel = ModelUtils.getModelByName(parent, models);
parentModel.hasChildren = true;
parentModel.getVendorExtensions().put(CodegenConstants.HAS_CHILDREN_EXT_NAME, Boolean.TRUE);
final Collection<CodegenModel> childrenModels = childrenByParent.get(parent);
for (final CodegenModel child : childrenModels) {
processParentPropertiesInChildModel(parentModel, child);
@@ -267,12 +271,12 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen {
if (duplicatedByParent != null) {
log.info(String.format("Property: '%s' in '%s' model is inherited from '%s'" ,
property.name, child.classname, parent.classname));
duplicatedByParent.isInherited = true;
duplicatedByParent.getVendorExtensions().put(CodegenConstants.IS_INHERITED_EXT_NAME, Boolean.TRUE);
final CodegenProperty parentVar = duplicatedByParent.clone();
parentVar.hasMore = false;
parentVar.getVendorExtensions().put(CodegenConstants.HAS_MORE_EXT_NAME, Boolean.FALSE);
child.parentVars.add(parentVar);
if (previousParentVar != null) {
previousParentVar.hasMore = true;
previousParentVar.getVendorExtensions().put(CodegenConstants.HAS_MORE_EXT_NAME, Boolean.TRUE);
}
previousParentVar = parentVar;
}
@@ -352,11 +356,16 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen {
}
@Override
public void preprocessSwagger(final Swagger swagger) {
public void preprocessOpenAPI(final OpenAPI openAPI) {
URL url = URLPathUtil.getServerURL(openAPI);
String path = "/";
if(url != null) {
path = url.getPath();
}
final String packageContextOption = (String) additionalProperties.get(PACKAGE_CONTEXT);
additionalProperties.put("packageContext", packageContextOption == null ? sanitizeName(swagger.getBasePath()) : packageContextOption);
additionalProperties.put("packageContext", packageContextOption == null ? sanitizeName(path) : packageContextOption);
final Object basePathOption = additionalProperties.get(USE_BASE_PATH);
additionalProperties.put("baseContext", basePathOption == null ? swagger.getBasePath() : "/");
additionalProperties.put("baseContext", basePathOption == null ? path : "/");
}
@Override
@@ -365,26 +374,30 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen {
}
@Override
public String getSwaggerType(final Property property) {
for (Entry<String, Predicate<Property>> entry : propertyToSwaggerTypeMapping.entrySet()) {
public String getSchemaType(final Schema property) {
for (Entry<String, Predicate<Schema>> entry : propertyToSwaggerTypeMapping.entrySet()) {
if (entry.getValue().apply(property)) {
return entry.getKey();
}
}
return super.getSwaggerType(property);
return super.getSchemaType(property);
}
private static Map<String, Predicate<Property>> createPropertyToSwaggerTypeMapping() {
final ImmutableMap.Builder<String, Predicate<Property>> mapping = ImmutableMap.builder();
private static Map<String, Predicate<Schema>> createPropertyToSchemaTypeMapping() {
final ImmutableMap.Builder<String, Predicate<Schema>> mapping = ImmutableMap.builder();
mapping.put("time", timeProperty());
return mapping.build();
}
private static Predicate<Property> timeProperty() {
return new Predicate<Property>() {
private static Predicate<Schema> timeProperty() {
return new Predicate<Schema>() {
@Override
public boolean apply(Property property) {
return property instanceof StringProperty && "time".equalsIgnoreCase(property.getFormat());
public boolean apply(Schema property) {
return property instanceof StringSchema && "time".equalsIgnoreCase(property.getFormat());
}
public boolean test(Schema schema) {
return this.apply(schema);
}
};
}

View File

@@ -8,16 +8,36 @@ import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import io.swagger.codegen.*;
import io.swagger.models.*;
import io.swagger.util.Yaml;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.utils.URLPathUtil;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.Paths;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.core.util.Yaml;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
@@ -265,7 +285,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
opsByPathEntry.put("path", entry.getKey());
opsByPathEntry.put("operation", entry.getValue());
List<CodegenOperation> operationsForThisPath = Lists.newArrayList(entry.getValue());
operationsForThisPath.get(operationsForThisPath.size() - 1).hasMore = false;
operationsForThisPath.get(operationsForThisPath.size() - 1).getVendorExtensions().put(CodegenConstants.HAS_MORE_EXT_NAME, Boolean.FALSE);
if (opsByPathList.size() < opsByPath.asMap().size()) {
opsByPathEntry.put("hasMore", "true");
}
@@ -315,19 +335,20 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
}
@Override
public void preprocessSwagger(Swagger swagger) {
String host = swagger.getHost();
public void preprocessOpenAPI(OpenAPI openAPI) {
URL url = URLPathUtil.getServerURL(openAPI);
String host = URLPathUtil.LOCAL_HOST;
String port = "8080";
if (host != null) {
String[] parts = host.split(":");
if (parts.length > 1) {
port = parts[1];
}
String basePath = null;
if (url != null) {
port = String.valueOf(url.getPort());
host = url.getHost();
basePath = url.getPath();
}
this.additionalProperties.put("serverPort", port);
if (swagger.getInfo() != null) {
Info info = swagger.getInfo();
if (openAPI.getInfo() != null) {
Info info = openAPI.getInfo();
if (info.getTitle() != null) {
// when info.title is defined, use it for projectName
// used in package.json
@@ -348,7 +369,6 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
LOGGER.warn("Host " + host + " seems not matching with cloudfunctions.net URL.");
}
if (!additionalProperties.containsKey(EXPORTED_NAME)) {
String basePath = swagger.getBasePath();
if (basePath == null || basePath.equals("/")) {
LOGGER.warn("Cannot find the exported name properly. Using 'openapi' as the exported name");
basePath = "/openapi";
@@ -358,13 +378,13 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
}
// need vendor extensions for x-swagger-router-controller
Map<String, Path> paths = swagger.getPaths();
Paths paths = openAPI.getPaths();
if(paths != null) {
for(String pathname : paths.keySet()) {
Path path = paths.get(pathname);
Map<HttpMethod, Operation> operationMap = path.getOperationMap();
PathItem path = paths.get(pathname);
Map<PathItem.HttpMethod, Operation> operationMap = path.readOperationsMap();
if(operationMap != null) {
for(HttpMethod method : operationMap.keySet()) {
for(PathItem.HttpMethod method : operationMap.keySet()) {
Operation operation = operationMap.get(method);
String tag = "default";
if(operation.getTags() != null && operation.getTags().size() > 0) {
@@ -373,8 +393,8 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
if(operation.getOperationId() == null) {
operation.setOperationId(getOrGenerateOperationId(operation, pathname, method.toString()));
}
if(operation.getVendorExtensions().get("x-swagger-router-controller") == null) {
operation.getVendorExtensions().put("x-swagger-router-controller", sanitizeTag(tag));
if(operation.getExtensions() != null && operation.getExtensions().get("x-swagger-router-controller") == null) {
operation.getExtensions().put("x-swagger-router-controller", sanitizeTag(tag));
}
}
}
@@ -384,8 +404,8 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
Swagger swagger = (Swagger)objs.get("swagger");
if(swagger != null) {
OpenAPI openAPI = (OpenAPI) objs.get("openapi");
if(openAPI != null) {
try {
SimpleModule module = new SimpleModule();
module.addSerializer(Double.class, new JsonSerializer<Double>() {
@@ -395,7 +415,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
jgen.writeNumber(new BigDecimal(val));
}
});
objs.put("swagger-yaml", Yaml.mapper().registerModule(module).writeValueAsString(swagger));
objs.put("swagger-yaml", Yaml.mapper().registerModule(module).writeValueAsString(openAPI));
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}

View File

@@ -1,9 +1,23 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.ArrayModel;
import io.swagger.models.Model;
import io.swagger.models.properties.*;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.util.Arrays;
@@ -13,7 +27,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String CLASS_PREFIX = "classPrefix";
@@ -285,10 +299,10 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String toInstantiationType(Property p) {
if (p instanceof MapProperty) {
public String toInstantiationType(Schema schema) {
if (schema instanceof MapSchema) {
return instantiationTypes.get("map");
} else if (p instanceof ArrayProperty) {
} else if (schema instanceof ArraySchema) {
return instantiationTypes.get("array");
} else {
return null;
@@ -305,8 +319,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String swaggerType = super.getSchemaType(propertySchema);
String type = null;
if (swaggerType == null) {
@@ -326,10 +340,10 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
public String getTypeDeclaration(Schema schema) {
if (schema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) schema;
Schema inner = arraySchema.getItems();
String innerTypeDeclaration = getTypeDeclaration(inner);
if (innerTypeDeclaration.endsWith("*")) {
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
@@ -337,21 +351,20 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
// In this condition, type of property p is array of primitive,
// return container type with pointer, e.g. `NSArray*<NSString*>*'
if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*";
return String.format("%s<%s>", getSchemaType(schema), innerTypeDeclaration);
}
// In this condition, type of property p is array of model,
// return container type combine inner type with pointer, e.g. `NSArray<SWGTag>*'
else {
for (String sd : advancedMapingTypes) {
if(innerTypeDeclaration.startsWith(sd)) {
return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*";
return String.format("%s<%s>", getSchemaType(schema), innerTypeDeclaration);
}
}
return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*";
return String.format("%s<%s>", getSchemaType(schema), innerTypeDeclaration);
}
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
} else if (schema instanceof MapSchema && hasSchemaProperties(schema)) {
Schema inner = (Schema) schema.getAdditionalProperties();
String innerTypeDeclaration = getTypeDeclaration(inner);
@@ -359,17 +372,17 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
}
if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + "*>*";
return String.format("%s<NSString*, %s*>*", getSchemaType(schema), innerTypeDeclaration);
} else {
for (String s : advancedMapingTypes) {
if(innerTypeDeclaration.startsWith(s)) {
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + "*>*";
return String.format("%s<NSString*, %s*>*", getSchemaType(schema), innerTypeDeclaration);
}
}
return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*";
return String.format("%s<%s>", getSchemaType(schema), innerTypeDeclaration);
}
} else {
String swaggerType = getSwaggerType(p);
String swaggerType = getSchemaType(schema);
// In this condition, type of p is objective-c primitive type, e.g. `NSSNumber',
// return type of p with pointer, e.g. `NSNumber*'
if (languageSpecificPrimitives.contains(swaggerType) &&
@@ -632,47 +645,30 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
/**
* Return the default value of the property
*
* @param p Swagger property object
* @param propertySchema Swagger property object
* @return string presentation of the default value of the property
*/
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
return "@\"" + dp.getDefault() + "\"";
public String toDefaultValue(Schema propertySchema) {
if (propertySchema instanceof StringSchema) {
if (propertySchema.getDefault() != null) {
return String.format("@\"%s\"", propertySchema.getDefault());
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getDefault() != null) {
if (dp.getDefault().toString().equalsIgnoreCase("false"))
} else if (propertySchema instanceof BooleanSchema) {
if (propertySchema.getDefault() != null) {
if (propertySchema.getDefault().toString().equalsIgnoreCase("false")) {
return "@(NO)";
else
} else {
return "@(YES)";
}
}
} else if (p instanceof DateProperty) {
} else if (propertySchema instanceof DateSchema) {
// TODO
} else if (p instanceof DateTimeProperty) {
} else if (propertySchema instanceof DateTimeSchema) {
// TODO
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return "@" + dp.getDefault().toString();
}
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) {
return "@" + dp.getDefault().toString();
}
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getDefault() != null) {
return "@" + dp.getDefault().toString();
}
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return "@" + dp.getDefault().toString();
} else {
if (propertySchema.getDefault() != null) {
return String.format("@%s", propertySchema.getDefault());
}
}
@@ -742,9 +738,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
if (example == null) {
example = "NULL";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
example = "@[" + example + "]";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME)) {
example = "@{@\"key\" : " + example + "}";
}

View File

@@ -7,28 +7,21 @@ import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CliOption;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.BinaryProperty;
import io.swagger.models.properties.ByteArrayProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DateProperty;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.regex.Matcher;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import org.apache.commons.lang3.StringUtils;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String MODULE_NAME = "moduleName";
public static final String MODULE_VERSION = "moduleVersion";
@@ -208,30 +201,28 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s[%s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s[String, %s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String schemaType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (typeMapping.containsKey(schemaType)) {
type = typeMapping.get(schemaType);
if (languageSpecificPrimitives.contains(type)) {
return type;
}
} else {
type = swaggerType;
type = schemaType;
}
if (type == null) {
return null;
@@ -240,43 +231,19 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
return "'" + dp.getDefault() + "'";
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof DateProperty) {
// TODO
} else if (p instanceof DateTimeProperty) {
// TODO
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
public String toDefaultValue(Schema schema) {
if(schema instanceof StringSchema) {
if (schema.getDefault() != null) {
return String.format("'%s'", schema.getDefault());
}
}
if (schema instanceof DateSchema || schema instanceof DateTimeSchema) {
// TODO
return null;
}
if (schema.getDefault() != null) {
return schema.getDefault().toString();
}
return null;
}
@@ -408,15 +375,17 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public void setParameterExampleValue(CodegenParameter p) {
if (Boolean.TRUE.equals(p.isString) || Boolean.TRUE.equals(p.isBinary) ||
Boolean.TRUE.equals(p.isByteArray) || Boolean.TRUE.equals(p.isFile)) {
if (getBooleanValue(p, CodegenConstants.IS_STRING_EXT_NAME) || getBooleanValue(p, CodegenConstants.IS_BINARY_EXT_NAME)
|| getBooleanValue(p, CodegenConstants.IS_BYTE_ARRAY_EXT_NAME)
|| getBooleanValue(p, CodegenConstants.IS_FILE_EXT_NAME)) {
p.example = "'" + p.example + "'";
} else if (Boolean.TRUE.equals(p.isBoolean)) {
} else if (getBooleanValue(p, CodegenConstants.IS_BOOLEAN_EXT_NAME)) {
if (Boolean.parseBoolean(p.example))
p.example = "1";
else
p.example = "0";
} else if (Boolean.TRUE.equals(p.isDateTime) || Boolean.TRUE.equals(p.isDate)) {
} else if (getBooleanValue(p, CodegenConstants.IS_DATE_TIME_EXT_NAME)
|| getBooleanValue(p, CodegenConstants.IS_DATE_EXT_NAME)) {
p.example = "DateTime->from_epoch(epoch => str2time('" + p.example + "'))";
}

View File

@@ -9,7 +9,6 @@ import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.*;
import java.io.File;
import java.util.Arrays;
@@ -21,11 +20,19 @@ import java.util.Map;
import java.util.HashSet;
import java.util.regex.Matcher;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
@SuppressWarnings("hiding")
static Logger LOGGER = LoggerFactory.getLogger(PhpClientCodegen.class);
@@ -363,21 +370,18 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getTypeDeclaration(inner) + "[]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
} else if (p instanceof RefProperty) {
String type = super.getTypeDeclaration(p);
return (!languageSpecificPrimitives.contains(type))
? "\\" + modelPackage + "\\" + type : type;
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s[]", getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s[string, %s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
} else if (StringUtils.isNotBlank(propertySchema.get$ref())) {
String type = super.getTypeDeclaration(propertySchema);
return (!languageSpecificPrimitives.contains(type)) ? String.format("\\%s\\%s", modelPackage, type) : type;
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override
@@ -389,18 +393,18 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String schemaType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (typeMapping.containsKey(schemaType)) {
type = typeMapping.get(schemaType);
if (languageSpecificPrimitives.contains(type)) {
return type;
} else if (instantiationTypes.containsKey(type)) {
return type;
}
} else {
type = swaggerType;
type = schemaType;
}
if (type == null) {
return null;
@@ -536,47 +540,23 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
/**
* Return the default value of the property
*
* @param p Swagger property object
* @param schema schema property object
* @return string presentation of the default value of the property
*/
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
return "'" + dp.getDefault() + "'";
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof DateProperty) {
// TODO
} else if (p instanceof DateTimeProperty) {
// TODO
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
public String toDefaultValue(Schema schema) {
if(schema instanceof StringSchema) {
if (schema.getDefault() != null) {
return String.format("'%s'", schema.getDefault());
}
}
if (schema instanceof DateSchema || schema instanceof DateTimeSchema) {
// TODO
return null;
}
if (schema.getDefault() != null) {
return schema.getDefault().toString();
}
return null;
}
@@ -638,9 +618,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
if (example == null) {
example = "NULL";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
example = "array(" + example + ")";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME)) {
example = "array('key' => " + example + ")";
}

View File

@@ -9,6 +9,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
@@ -16,25 +17,23 @@ import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Response;
import io.swagger.models.Swagger;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BaseIntegerProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DecimalProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FileProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.FileSchema;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.apache.commons.lang3.StringUtils;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class PistacheServerCodegen extends AbstractCppCodegen {
protected String implFolder = "impl";
@@ -137,8 +136,8 @@ public class PistacheServerCodegen extends AbstractCppCodegen {
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allSchemas) {
CodegenModel codegenModel = super.fromModel(name, schema, allSchemas);
Set<String> oldImports = codegenModel.imports;
codegenModel.imports = new HashSet<>();
@@ -154,27 +153,28 @@ public class PistacheServerCodegen extends AbstractCppCodegen {
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation,
Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);
Map<String, Schema> schemas, OpenAPI openAPI) {
CodegenOperation codegenOperation = super.fromOperation(path, httpMethod, operation, schemas, openAPI);
if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
Response methodResponse = findMethodResponse(operation.getResponses());
ApiResponse methodResponse = findMethodResponse(operation.getResponses());
if (methodResponse != null) {
if (methodResponse.getSchema() != null) {
CodegenProperty cm = fromProperty("response", methodResponse.getSchema());
op.vendorExtensions.put("x-codegen-response", cm);
Schema schemaResponse = getSchemaFromResponse(methodResponse);
if (schemaResponse != null) {
CodegenProperty cm = fromProperty("response", schemaResponse);
codegenOperation.vendorExtensions.put("x-codegen-response", cm);
if(cm.datatype == "HttpContent") {
op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
codegenOperation.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
}
}
}
}
String pathForPistache = path.replaceAll("\\{(.*?)}", ":$1");
op.vendorExtensions.put("x-codegen-pistache-path", pathForPistache);
codegenOperation.vendorExtensions.put("x-codegen-pistache-path", pathForPistache);
return op;
return codegenOperation;
}
@SuppressWarnings("unchecked")
@@ -194,7 +194,8 @@ public class PistacheServerCodegen extends AbstractCppCodegen {
op.bodyParam.vendorExtensions = new HashMap<>();
}
op.bodyParam.vendorExtensions.put("x-codegen-pistache-isStringOrDate", op.bodyParam.isString || op.bodyParam.isDate);
op.bodyParam.vendorExtensions.put("x-codegen-pistache-isStringOrDate",
getBooleanValue(op.bodyParam, CodegenConstants.IS_STRING_EXT_NAME) ||getBooleanValue(op.bodyParam, CodegenConstants.IS_DATE_EXT_NAME));
}
if(op.consumes != null) {
for (Map<String, String> consume : op.consumes) {
@@ -207,16 +208,22 @@ public class PistacheServerCodegen extends AbstractCppCodegen {
op.httpMethod = op.httpMethod.substring(0, 1).toUpperCase() + op.httpMethod.substring(1).toLowerCase();
for(CodegenParameter param : op.allParams){
if (param.isFormParam) isParsingSupported=false;
if (param.isFile) isParsingSupported=false;
if (param.isCookieParam) isParsingSupported=false;
if (getBooleanValue(param, CodegenConstants.IS_FORM_PARAM_EXT_NAME)) {
isParsingSupported=false;
}
if (getBooleanValue(param, CodegenConstants.IS_FILE_EXT_NAME)) {
isParsingSupported=false;
}
if (getBooleanValue(param, CodegenConstants.IS_COOKIE_PARAM_EXT_NAME)) {
isParsingSupported=false;
}
//TODO: This changes the info about the real type but it is needed to parse the header params
if (param.isHeaderParam) {
if (getBooleanValue(param, CodegenConstants.IS_HEADER_PARAM_EXT_NAME)) {
param.dataType = "Optional<Net::Http::Header::Raw>";
param.baseType = "Optional<Net::Http::Header::Raw>";
} else if(param.isQueryParam){
if(param.isPrimitiveType) {
} else if(getBooleanValue(param, CodegenConstants.IS_QUERY_PARAM_EXT_NAME)){
if(getBooleanValue(param, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME)) {
param.dataType = "Optional<" + param.dataType + ">";
} else {
param.dataType = "Optional<" + param.baseType + ">";
@@ -274,62 +281,55 @@ public class PistacheServerCodegen extends AbstractCppCodegen {
* `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
String swaggerType = getSwaggerType(p);
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
public String getTypeDeclaration(Schema propertySchema) {
String schemaType = getSchemaType(propertySchema);
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s<%s>", schemaType, getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s<std::string, %s>", schemaType, getTypeDeclaration(inner));
}
if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<std::string, " + getTypeDeclaration(inner) + ">";
if (propertySchema instanceof StringSchema || propertySchema instanceof DateSchema
|| propertySchema instanceof DateTimeSchema || propertySchema instanceof FileSchema
|| languageSpecificPrimitives.contains(schemaType)) {
return toModelName(schemaType);
}
if (p instanceof StringProperty || p instanceof DateProperty
|| p instanceof DateTimeProperty || p instanceof FileProperty
|| languageSpecificPrimitives.contains(swaggerType)) {
return toModelName(swaggerType);
}
return "std::shared_ptr<" + swaggerType + ">";
return super.getTypeDeclaration(propertySchema);
}
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
public String toDefaultValue(Schema propertySchema) {
if (propertySchema instanceof StringSchema) {
return "\"\"";
} else if (p instanceof BooleanProperty) {
} else if (propertySchema instanceof BooleanSchema) {
return "false";
} else if (p instanceof DateProperty) {
} else if (propertySchema instanceof DateSchema) {
return "\"\"";
} else if (p instanceof DateTimeProperty) {
} else if (propertySchema instanceof DateTimeSchema) {
return "\"\"";
} else if (p instanceof DoubleProperty) {
} else if (propertySchema instanceof NumberSchema) {
if(SchemaTypeUtil.FLOAT_FORMAT.equals(propertySchema.getFormat())) {
return "0.0f";
}
return "0.0";
} else if (p instanceof FloatProperty) {
return "0.0f";
} else if (p instanceof LongProperty) {
return "0L";
} else if (p instanceof IntegerProperty || p instanceof BaseIntegerProperty) {
} else if (propertySchema instanceof IntegerSchema) {
if(SchemaTypeUtil.INTEGER64_FORMAT.equals(propertySchema.getFormat())) {
return "0L";
}
return "0";
} else if (p instanceof DecimalProperty) {
return "0.0";
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
String inner = getSchemaType((Schema) propertySchema.getAdditionalProperties());
return "std::map<std::string, " + inner + ">()";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
} else if (propertySchema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) propertySchema;
String inner = getSchemaType(arraySchema.getItems());
if (!languageSpecificPrimitives.contains(inner)) {
inner = "std::shared_ptr<" + inner + ">";
}
return "std::vector<" + inner + ">()";
} else if (p instanceof RefProperty) {
RefProperty rp = (RefProperty) p;
return "new " + toModelName(rp.getSimpleRef()) + "()";
} else if (StringUtils.isNotBlank(propertySchema.get$ref())) {
return "new " + toModelName(propertySchema.get$ref()) + "()";
}
return "nullptr";
}
@@ -338,9 +338,9 @@ public class PistacheServerCodegen extends AbstractCppCodegen {
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
boolean isPrimitiveType = parameter.isPrimitiveType == Boolean.TRUE;
boolean isListContainer = parameter.isListContainer == Boolean.TRUE;
boolean isString = parameter.isString == Boolean.TRUE;
boolean isPrimitiveType = getBooleanValue(parameter, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME);
boolean isListContainer = getBooleanValue(parameter, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME);
boolean isString = getBooleanValue(parameter, CodegenConstants.IS_STRING_EXT_NAME);
if (!isPrimitiveType && !isListContainer && !isString && !parameter.dataType.startsWith("std::shared_ptr")) {
parameter.dataType = "std::shared_ptr<" + parameter.dataType + ">";
@@ -374,18 +374,20 @@ public class PistacheServerCodegen extends AbstractCppCodegen {
* into complex models if there is not a mapping.
*
* @return a string value of the type or complex model for this property
* @see io.swagger.models.properties.Property
* @see io.swagger.v3.oas.models.media.Schema
*/
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String schemaType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type))
if (typeMapping.containsKey(schemaType)) {
type = typeMapping.get(schemaType);
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
} else
type = swaggerType;
}
} else {
type = schemaType;
}
return toModelName(type);
}

View File

@@ -1,9 +1,16 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -328,49 +335,43 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo
/**
* returns the swagger type for the property
*
* @param p Swagger property object
* @param propertySchema Schema property object
* @return string presentation of the type
**/
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type;
// This maps, for example, long -> Long based on hashes in this type's constructor
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
public String getSchemaType(Schema propertySchema) {
String schemaType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(schemaType)) {
type = typeMapping.get(schemaType);
if (languageSpecificPrimitives.contains(type)) {
return type;
return toModelName(type);
}
} else {
type = swaggerType;
type = schemaType;
}
// model/object
return toModelName(type);
}
/**
* Output the type declaration of the property
*
* @param p Swagger Property object
* @param propertySchema Swagger Property object
* @return a string presentation of the property type
*/
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) propertySchema;
Schema inner = arraySchema.getItems();
return getTypeDeclaration(inner) + "[]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
// TODO not sure if the following map/hash declaration is correct
return "{String, " + getTypeDeclaration(inner) + "}";
} else if (!languageSpecificPrimitives.contains(getSwaggerType(p))) {
return packageName + ".Model." + super.getTypeDeclaration(p);
return "{String, " + getTypeDeclaration((Schema) propertySchema.getAdditionalProperties()) + "}";
} else if (!languageSpecificPrimitives.contains(getSchemaType(propertySchema))) {
return packageName + ".Model." + super.getTypeDeclaration(propertySchema);
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override

View File

@@ -9,7 +9,6 @@ import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.*;
import java.io.File;
import java.util.ArrayList;
@@ -19,9 +18,16 @@ import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import org.apache.commons.lang3.StringUtils;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String PACKAGE_URL = "packageUrl";
@@ -355,31 +361,28 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "(str, " + getTypeDeclaration(inner) + ")";
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s[%s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s[str, %s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema propertySchema) {
String schemaType = super.getSchemaType(propertySchema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (typeMapping.containsKey(schemaType)) {
type = typeMapping.get(schemaType);
if (languageSpecificPrimitives.contains(type)) {
return type;
}
} else {
type = toModelName(swaggerType);
type = toModelName(schemaType);
}
return type;
}
@@ -570,53 +573,33 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
/**
* Return the default value of the property
*
* @param p Swagger property object
* @param propertySchema Swagger property object
* @return string presentation of the default value of the property
*/
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
StringProperty dp = (StringProperty) p;
if (dp.getDefault() != null) {
if (Pattern.compile("\r\n|\r|\n").matcher(dp.getDefault()).find())
return "'''" + dp.getDefault() + "'''";
public String toDefaultValue(Schema propertySchema) {
if (propertySchema instanceof StringSchema) {
if (propertySchema.getDefault() != null) {
if (Pattern.compile("\r\n|\r|\n").matcher(propertySchema.getDefault().toString()).find())
return "'''" + propertySchema.getDefault() + "'''";
else
return "'" + dp.getDefault() + "'";
return "'" + propertySchema.getDefault() + "'";
}
} else if (p instanceof BooleanProperty) {
BooleanProperty dp = (BooleanProperty) p;
if (dp.getDefault() != null) {
if (dp.getDefault().toString().equalsIgnoreCase("false"))
} else if (propertySchema instanceof BooleanSchema) {
if (propertySchema.getDefault() != null) {
if (propertySchema.getDefault().toString().equalsIgnoreCase("false")) {
return "False";
else
} else {
return "True";
}
}
} else if (p instanceof DateProperty) {
} else if (propertySchema instanceof DateSchema || propertySchema instanceof DateTimeSchema) {
// TODO
} else if (p instanceof DateTimeProperty) {
// TODO
} else if (p instanceof DoubleProperty) {
DoubleProperty dp = (DoubleProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof FloatProperty) {
FloatProperty dp = (FloatProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof IntegerProperty) {
IntegerProperty dp = (IntegerProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString();
}
return null;
}
if (propertySchema.getDefault() != null) {
return propertySchema.getDefault().toString();
}
return null;
}
@@ -676,9 +659,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
if (example == null) {
example = "NULL";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME)) {
example = "[" + example + "]";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
} else if (getBooleanValue(p, CodegenConstants.IS_MAP_CONTAINER_EXT_NAME)) {
example = "{'key': " + example + "}";
}

View File

@@ -1,20 +1,20 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DecimalProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.BaseIntegerProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.util.Arrays;
@@ -268,65 +268,62 @@ public class Qt5CPPGenerator extends AbstractCppCodegen implements CodegenConfig
* @return a string value used as the `dataType` field for model templates, `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
String swaggerType = getSwaggerType(p);
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">*";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<QString, " + getTypeDeclaration(inner) + ">*";
public String getTypeDeclaration(Schema propertySchema) {
String schematype = getSchemaType(propertySchema);
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s<%s>", schematype, getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s<QString, %s>", schematype, getTypeDeclaration(inner));
}
if (foundationClasses.contains(swaggerType)) {
return swaggerType + "*";
} else if (languageSpecificPrimitives.contains(swaggerType)) {
return toModelName(swaggerType);
if (foundationClasses.contains(schematype)) {
return schematype + "*";
} else if (languageSpecificPrimitives.contains(schematype)) {
return toModelName(schematype);
} else {
return swaggerType + "*";
return schematype + "*";
}
}
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
public String toDefaultValue(Schema schema) {
if (schema instanceof StringSchema) {
return "new QString(\"\")";
} else if (p instanceof BooleanProperty) {
} else if (schema instanceof BooleanSchema) {
return "false";
} else if (p instanceof DateProperty) {
} else if (schema instanceof DateSchema) {
return "NULL";
} else if (p instanceof DateTimeProperty) {
} else if (schema instanceof DateTimeSchema) {
return "NULL";
} else if (p instanceof DoubleProperty) {
} else if (schema instanceof NumberSchema) {
if(SchemaTypeUtil.FLOAT_FORMAT.equals(schema.getFormat())) {
return "0.0f";
}
return "0.0";
} else if (p instanceof FloatProperty) {
return "0.0f";
} else if (p instanceof IntegerProperty) {
} else if (schema instanceof IntegerSchema) {
if(SchemaTypeUtil.INTEGER64_FORMAT.equals(schema.getFormat())) {
return "0.0L";
}
return "0";
} else if (p instanceof LongProperty) {
return "0L";
} else if (p instanceof BaseIntegerProperty) {
// catchall for any other format of the swagger specifiction
// integer type not explicitly handled above
return "0";
} else if (p instanceof DecimalProperty) {
return "0.0";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return "new QMap<QString, " + getTypeDeclaration(inner) + ">()";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return "new QList<" + getTypeDeclaration(inner) + ">()";
} else if (schema instanceof MapSchema && hasSchemaProperties(schema)) {
String inner = getSchemaType((Schema) schema.getAdditionalProperties());
if (!languageSpecificPrimitives.contains(inner)) {
inner += "*";
}
return "new QMap<QString, " + inner + ">()";
} else if (schema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) schema;
String inner = getSchemaType(arraySchema.getItems());
if (!languageSpecificPrimitives.contains(inner)) {
inner += "*";
}
return "new QList<" + inner + ">()";
}
// else
if (p instanceof RefProperty) {
RefProperty rp = (RefProperty) p;
return "new " + toModelName(rp.getSimpleRef()) + "()";
if (StringUtils.isNotBlank(schema.get$ref())) {
return "new " + toModelName(schema.get$ref()) + "()";
}
return "NULL";
}
@@ -336,11 +333,11 @@ public class Qt5CPPGenerator extends AbstractCppCodegen implements CodegenConfig
* either language specific types via `typeMapping` or into complex models if there is not a mapping.
*
* @return a string value of the type or complex model for this property
* @see io.swagger.models.properties.Property
* @see io.swagger.v3.oas.models.media.Schema
*/
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema schema) {
String swaggerType = super.getSchemaType(schema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);

View File

@@ -1,19 +1,28 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.parameters.Parameter;
import java.io.File;
import java.util.*;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
public class RClientCodegen extends DefaultCodegen implements CodegenConfig {
static Logger LOGGER = LoggerFactory.getLogger(RClientCodegen.class);
@@ -273,20 +282,18 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getTypeDeclaration(inner);
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
public String getTypeDeclaration(Schema propertySchema) {
if(propertySchema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) propertySchema;
Schema inner = arraySchema.getItems();
return getTypeDeclaration(inner);
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
return getTypeDeclaration((Schema) propertySchema.getAdditionalProperties());
}
// Not using the supertype invocation, because we want to UpperCamelize
// the type.
String swaggerType = getSwaggerType(p);
String swaggerType = getSchemaType(propertySchema);
if (typeMapping.containsKey(swaggerType)) {
return typeMapping.get(swaggerType);
}
@@ -303,13 +310,14 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema schema) {
String swaggerType = super.getSchemaType(schema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type))
if (languageSpecificPrimitives.contains(type)) {
return (type);
}
} else {
type = swaggerType;
}

View File

@@ -8,11 +8,11 @@ import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.Swagger;
import io.swagger.util.Yaml;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.core.util.Yaml;
import java.io.File;
import java.util.Arrays;
@@ -199,21 +199,19 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
public String getTypeDeclaration(Schema propertySchema) {
if (propertySchema instanceof ArraySchema) {
Schema inner = ((ArraySchema) propertySchema).getItems();
return String.format("%s[%s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
} else if (propertySchema instanceof MapSchema && hasSchemaProperties(propertySchema)) {
Schema inner = (Schema) propertySchema.getAdditionalProperties();
return String.format("%s[string, %s]", getSchemaType(propertySchema), getTypeDeclaration(inner));
}
return super.getTypeDeclaration(p);
return super.getTypeDeclaration(propertySchema);
}
@Override
public String toDefaultValue(Property p) {
public String toDefaultValue(Schema schema) {
return "null";
}
@@ -240,8 +238,8 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema schema) {
String swaggerType = super.getSchemaType(schema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
return typeMapping.get(swaggerType);
@@ -315,10 +313,10 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
Swagger swagger = (Swagger)objs.get("swagger");
if(swagger != null) {
OpenAPI openAPI = (OpenAPI) objs.get("openapi");
if(openAPI != null) {
try {
objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger));
objs.put("openapi-yaml", Yaml.mapper().writeValueAsString(openAPI));
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}

View File

@@ -16,22 +16,20 @@ import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Model;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BaseIntegerProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DecimalProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FileProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BooleanSchema;
import io.swagger.v3.oas.models.media.DateSchema;
import io.swagger.v3.oas.models.media.DateTimeSchema;
import io.swagger.v3.oas.models.media.FileSchema;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.apache.commons.lang3.StringUtils;
import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanValue;
public class RestbedCodegen extends AbstractCppCodegen {
@@ -196,8 +194,8 @@ public class RestbedCodegen extends AbstractCppCodegen {
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allSchemas) {
CodegenModel codegenModel = super.fromModel(name, schema, allSchemas);
Set<String> oldImports = codegenModel.imports;
codegenModel.imports = new HashSet<String>();
@@ -282,21 +280,19 @@ public class RestbedCodegen extends AbstractCppCodegen {
* `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
String swaggerType = getSwaggerType(p);
public String getTypeDeclaration(Schema schema) {
String swaggerType = getSchemaType(schema);
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
if (schema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) schema;
Schema inner = arraySchema.getItems();
return getSchemaType(schema) + "<" + getTypeDeclaration(inner) + ">";
}
if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<std::string, " + getTypeDeclaration(inner) + ">";
if (schema instanceof MapSchema && hasSchemaProperties(schema)) {
return getSchemaType(schema) + "<std::string, " + getTypeDeclaration((Schema) schema.getAdditionalProperties()) + ">";
}
if (p instanceof StringProperty || p instanceof DateProperty
|| p instanceof DateTimeProperty || p instanceof FileProperty
if (schema instanceof StringSchema || schema instanceof DateSchema
|| schema instanceof DateTimeSchema || schema instanceof FileSchema
|| languageSpecificPrimitives.contains(swaggerType)) {
return toModelName(swaggerType);
}
@@ -305,39 +301,36 @@ public class RestbedCodegen extends AbstractCppCodegen {
}
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
public String toDefaultValue(Schema schema) {
if (schema instanceof StringSchema) {
return "\"\"";
} else if (p instanceof BooleanProperty) {
} else if (schema instanceof BooleanSchema) {
return "false";
} else if (p instanceof DateProperty) {
} else if (schema instanceof DateSchema) {
return "\"\"";
} else if (p instanceof DateTimeProperty) {
} else if (schema instanceof DateTimeSchema) {
return "\"\"";
} else if (p instanceof DoubleProperty) {
} else if (schema instanceof NumberSchema) {
if(SchemaTypeUtil.FLOAT_FORMAT.equals(schema.getFormat())) {
return "0.0f";
}
return "0.0";
} else if (p instanceof FloatProperty) {
return "0.0f";
} else if (p instanceof LongProperty) {
return "0L";
} else if (p instanceof IntegerProperty || p instanceof BaseIntegerProperty) {
} else if (schema instanceof IntegerSchema) {
if(SchemaTypeUtil.INTEGER64_FORMAT.equals(schema.getFormat())) {
return "0.0L";
}
return "0";
} else if (p instanceof DecimalProperty) {
return "0.0";
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "std::map<std::string, " + inner + ">()";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
} else if (schema instanceof MapSchema) {
return "std::map<std::string, " + schema.getAdditionalProperties() + ">()";
} else if (schema instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) schema;
String inner = getSchemaType(arraySchema.getItems());
if (!languageSpecificPrimitives.contains(inner)) {
inner = "std::shared_ptr<" + inner + ">";
}
return "std::vector<" + inner + ">()";
} else if (p instanceof RefProperty) {
RefProperty rp = (RefProperty) p;
return "new " + toModelName(rp.getSimpleRef()) + "()";
} else if (StringUtils.isNotBlank(schema.get$ref())) {
return "new " + toModelName(schema.get$ref()) + "()";
}
return "nullptr";
}
@@ -346,9 +339,9 @@ public class RestbedCodegen extends AbstractCppCodegen {
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
boolean isPrimitiveType = parameter.isPrimitiveType == Boolean.TRUE;
boolean isListContainer = parameter.isListContainer == Boolean.TRUE;
boolean isString = parameter.isString == Boolean.TRUE;
boolean isPrimitiveType = getBooleanValue(parameter, CodegenConstants.IS_PRIMITIVE_TYPE_EXT_NAME);
boolean isListContainer = getBooleanValue(parameter, CodegenConstants.IS_LIST_CONTAINER_EXT_NAME);
boolean isString = getBooleanValue(parameter, CodegenConstants.IS_STRING_EXT_NAME);
if (!isPrimitiveType && !isListContainer && !isString && !parameter.dataType.startsWith("std::shared_ptr")) {
parameter.dataType = "std::shared_ptr<" + parameter.dataType + ">";
@@ -361,11 +354,11 @@ public class RestbedCodegen extends AbstractCppCodegen {
* into complex models if there is not a mapping.
*
* @return a string value of the type or complex model for this property
* @see io.swagger.models.properties.Property
* @see io.swagger.v3.oas.models.media.Schema
*/
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
public String getSchemaType(Schema schema) {
String swaggerType = super.getSchemaType(schema);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);

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