sync master, update doc

This commit is contained in:
William Cheng 2019-11-04 09:38:22 +08:00
commit 4ca9430474
3045 changed files with 46565 additions and 80169 deletions

View File

@ -134,7 +134,7 @@
]
},
{
"input": "csharp-refactor-petstore.sh",
"input": "csharp-netcore-petstore.sh",
"matches": [
"Client: C-Sharp"
]
@ -218,7 +218,7 @@
]
},
{
"input": "finch-petstore-server.sh",
"input": "scala-finch-petstore-server.sh",
"matches": [
"Server: Scala"
]
@ -260,7 +260,7 @@
]
},
{
"input": "graphql-server-petstore.sh",
"input": "graphql-nodejs-express-server.sh",
"matches": [
"Server: GraphQL"
]
@ -825,13 +825,13 @@
]
},
{
"input": "python-flask-petstore-python2.sh",
"input": "python-server-flask-petstore-python2.sh",
"matches": [
"Server: Python"
]
},
{
"input": "python-flask-petstore.sh",
"input": "python-server-flask-petstore.sh",
"matches": [
"Server: Python"
]
@ -878,12 +878,6 @@
"Client: Rust"
]
},
{
"input": "rust-reqwest-petstore.sh",
"matches": [
"Client: Rust"
]
},
{
"input": "rust-server-petstore.sh",
"matches": [
@ -1311,6 +1305,76 @@
"matches": [
"Announcement"
]
},
{
"input": "[typescript] Generic typescript text",
"matches": [
"Client: TypeScript"
]
},
{
"input": "[typescript] Generic typescript text",
"matches": [
"Client: TypeScript"
]
},
{
"input": "[typescript-angular] Generic typescript text",
"matches": [
"Client: TypeScript"
]
},
{
"input": "[typescript-angularjs] Generic typescript text",
"matches": [
"Client: TypeScript"
]
},
{
"input": "[typescript-aurelia] Generic typescript text",
"matches": [
"Client: TypeScript"
]
},
{
"input": "[typescript-axios] Generic typescript text",
"matches": [
"Client: TypeScript"
]
},
{
"input": "[typescript-fetch] Generic typescript text",
"matches": [
"Client: TypeScript"
]
},
{
"input": "[typescript-inversify] Generic typescript text",
"matches": [
"Client: TypeScript"
]
},
{
"input": "[typescript-jquery] Generic typescript text",
"matches": [
"Client: TypeScript"
]
},
{
"input": "[typescript-node] Generic typescript text",
"matches": [
"Client: TypeScript"
]
},
{
"input": "[typescript-rxjs] Generic typescript text",
"matches": [
"Client: TypeScript"
]
},
{
"input": "Should not auto-label for typescript outside of brackets.",
"matches": []
}
]
}

View File

@ -4,7 +4,7 @@
### PR checklist
- [ ] Read the [contribution guidelines](https://github.com/openapitools/openapi-generator/blob/master/CONTRIBUTING.md).
- [ ] If contributing template-only or documentation-only changes which will change sample output, [build the project](https://github.com/OpenAPITools/openapi-generator#14---build-projects) before .
- [ ] If contributing template-only or documentation-only changes which will change sample output, [build the project](https://github.com/OpenAPITools/openapi-generator#14---build-projects) before.
- [ ] Run the shell script(s) under `./bin/` (or Windows batch scripts under`.\bin\windows`) to update Petstore samples related to your fix. This is important, as CI jobs will verify _all_ generator outputs of your HEAD commit, and these must match the expectations made by your contribution. You only need to run `./bin/{LANG}-petstore.sh`, `./bin/openapi3/{LANG}-petstore.sh` if updating the code or mustache templates for a language (`{LANG}`) (e.g. php, ruby, python, etc).
- [ ] File the PR against the [correct branch](https://github.com/OpenAPITools/openapi-generator/wiki/Git-Branches): `master`, `4.1.x`, `5.0.x`. Default: `master`.
- [ ] Copy the [technical committee](https://github.com/openapitools/openapi-generator/#62---openapi-generator-technical-committee) to review the pull request if your PR is targeting a particular programming language.

View File

@ -138,6 +138,7 @@ labels:
- '\s*?-[gl] swift[34]+\s*?'
- '\s*?-[gl] swift2-deprecated\s*?'
'Client: TypeScript':
- '\s*?\[typescript\]\s*?'
- '\s*?\[typescript-[\-a-z]+\]\s*?'
- '\s*?-[gl] typescript-[\-a-z]+\s*?'
# 'Client: VB/VB.net': # NOTE: Not yet implemented

View File

@ -71,10 +71,10 @@ before_install:
- docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore
- docker ps -a
# Add bats test framework and cURL for Bash script integration tests
#- sudo add-apt-repository ppa:duggan/bats --yes
#- sudo apt-get update -qq
#- sudo apt-get install -qq bats
#- sudo apt-get install -qq curl
- sudo add-apt-repository ppa:duggan/bats --yes
- sudo apt-get update -qq
- sudo apt-get install -qq bats
- sudo apt-get install -qq curl
# install dart
#- sudo apt-get update
#- sudo apt-get install apt-transport-https
@ -94,16 +94,11 @@ before_install:
# - Rely on `kerl` for [pre-compiled versions available](https://docs.travis-ci.com/user/languages/erlang#Choosing-OTP-releases-to-test-against). Rely on installation path chosen by [`travis-erlang-builder`](https://github.com/travis-ci/travis-erlang-builder/blob/e6d016b1a91ca7ecac5a5a46395bde917ea13d36/bin/compile#L18).
# - . ~/otp/18.2.1/activate && erl -version
#- curl -f -L -o ./rebar3 https://s3.amazonaws.com/rebar3/rebar3 && chmod +x ./rebar3 && ./rebar3 version && export PATH="${TRAVIS_BUILD_DIR}:$PATH"
# install valgrind for C++ memory test
- sudo apt-get install valgrind
# install Qt 5.10
# comment out the following due to failure in downloading http://ppa.launchpad.net/beineri/opt-qt-5.10.1-trusty/ubuntu/dists/xenial/main/binary-amd64/Packages
#- sudo add-apt-repository --yes ppa:beineri/opt-qt-5.10.1-trusty
#- sudo apt-get update -qq
#- sudo apt-get install qt510-meta-minimal
#- source /opt/qt510/bin/qt510-env.sh
#- qmake -v
# install C++ tools
- sudo apt install -y --no-install-recommends valgrind cmake build-essential
# install Qt5
- sudo apt install -y --no-install-recommends qt5-default
- cmake --version
# show host table to confirm petstore.swagger.io is mapped to localhost
- cat /etc/hosts
# show java version

View File

@ -24,6 +24,10 @@ elif [ "$NODE_INDEX" = "2" ]; then
# install elm-format
npm install -g elm-format
# clear any changes to the samples
git checkout -- .
# look for outdated samples
./bin/utils/ensure-up-to-date
fi
#elif [ "$NODE_INDEX" = "3" ]; then

View File

@ -15,33 +15,57 @@ public class ApiKeyAuthTest {
public void testApplyToParamsInQuery() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> cookieParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("query", "api_key");
auth.setApiKey("my-api-key");
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
assertEquals(1, queryParams.size());
for (Pair queryParam : queryParams) {
assertEquals("my-api-key", queryParam.getValue());
}
// no changes to header parameters
// no changes to header or cookie parameters
assertEquals(0, headerParams.size());
assertEquals(0, cookieParams.size());
}
@Test
public void testApplyToParamsInHeaderWithPrefix() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> cookieParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN");
auth.setApiKey("my-api-token");
auth.setApiKeyPrefix("Token");
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// no changes to query parameters
// no changes to query or cookie parameters
assertEquals(0, queryParams.size());
assertEquals(0, cookieParams.size());
assertEquals(1, headerParams.size());
assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN"));
}
@Test
public void testApplyToParamsInCookieWithPrefix() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> cookieParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("cookie", "X-API-TOKEN");
auth.setApiKey("my-api-token");
auth.setApiKeyPrefix("Token");
auth.applyToParams(queryParams, headerParams, cookieParams);
// no changes to query or header parameters
assertEquals(0, queryParams.size());
assertEquals(0, headerParams.size());
assertEquals(1, cookieParams.size());
assertEquals("Token my-api-token", cookieParams.get("X-API-TOKEN"));
}
}

View File

@ -22,13 +22,15 @@ public class HttpBasicAuthTest {
public void testApplyToParams() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> cookieParams = new HashMap<String, String>();
auth.setUsername("my-username");
auth.setPassword("my-password");
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// no changes to query parameters
// no changes to query or cookie parameters
assertEquals(0, queryParams.size());
assertEquals(0, cookieParams.size());
assertEquals(1, headerParams.size());
// the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix
String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ=";
@ -36,7 +38,7 @@ public class HttpBasicAuthTest {
// null username should be treated as empty string
auth.setUsername(null);
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// the string below is base64-encoded result of ":my-password" with the "Basic " prefix
expected = "Basic Om15LXBhc3N3b3Jk";
assertEquals(expected, headerParams.get("Authorization"));
@ -44,7 +46,7 @@ public class HttpBasicAuthTest {
// null password should be treated as empty string
auth.setUsername("my-username");
auth.setPassword(null);
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// the string below is base64-encoded result of "my-username:" with the "Basic " prefix
expected = "Basic bXktdXNlcm5hbWU6";
assertEquals(expected, headerParams.get("Authorization"));

View File

@ -15,33 +15,55 @@ public class ApiKeyAuthTest {
public void testApplyToParamsInQuery() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> cookieParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("query", "api_key");
auth.setApiKey("my-api-key");
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
assertEquals(1, queryParams.size());
for (Pair queryParam : queryParams) {
assertEquals("my-api-key", queryParam.getValue());
}
// no changes to header parameters
// no changes to header or cookie parameters
assertEquals(0, headerParams.size());
assertEquals(0, cookieParams.size());
}
@Test
public void testApplyToParamsInHeaderWithPrefix() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> cookieParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN");
auth.setApiKey("my-api-token");
auth.setApiKeyPrefix("Token");
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// no changes to query parameters
assertEquals(0, queryParams.size());
assertEquals(0, cookieParams.size());
assertEquals(1, headerParams.size());
assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN"));
}
@Test
public void testApplyToParamsInCookieWithPrefix() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> cookieParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("cookie", "X-API-TOKEN");
auth.setApiKey("my-api-token");
auth.setApiKeyPrefix("Token");
auth.applyToParams(queryParams, headerParams, cookieParams);
// no changes to query or header parameters
assertEquals(0, queryParams.size());
assertEquals(0, headerParams.size());
assertEquals(1, cookieParams.size());
assertEquals("Token my-api-token", cookieParams.get("X-API-TOKEN"));
}
}

View File

@ -22,10 +22,11 @@ public class HttpBasicAuthTest {
public void testApplyToParams() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> cookieParams = new HashMap<String, String>();
auth.setUsername("my-username");
auth.setPassword("my-password");
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// no changes to query parameters
assertEquals(0, queryParams.size());
@ -36,7 +37,7 @@ public class HttpBasicAuthTest {
// null username should be treated as empty string
auth.setUsername(null);
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// the string below is base64-encoded result of ":my-password" with the "Basic " prefix
expected = "Basic Om15LXBhc3N3b3Jk";
assertEquals(expected, headerParams.get("Authorization"));
@ -44,7 +45,7 @@ public class HttpBasicAuthTest {
// null password should be treated as empty string
auth.setUsername("my-username");
auth.setPassword(null);
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// the string below is base64-encoded result of "my-username:" with the "Basic " prefix
expected = "Basic bXktdXNlcm5hbWU6";
assertEquals(expected, headerParams.get("Authorization"));

View File

@ -61,6 +61,7 @@ public class PetApiTest {
ApiClient oldClient = api.getApiClient();
ApiClient newClient = new ApiClient();
newClient.setVerifyingSsl(true);
newClient.setBasePath("http://example.com");
newClient.setDebugging(true);
@ -145,6 +146,14 @@ public class PetApiTest {
}
} while (result.isEmpty());
assertPetMatches(pet, fetched);
}
@Test
public void testCreateAndGetPetAsyncInvalidID() throws Exception {
Pet pet = createPet();
api.addPet(pet);
// to store returned Pet or error message/exception
final Map<String, Object> result = new HashMap<String, Object>();
// test getting a nonexistent pet
result.clear();
@ -171,8 +180,11 @@ public class PetApiTest {
});
// wait for the asynchronous call to finish (at most 10 seconds)
tryCount = 1;
final int maxTry = 10;
int tryCount = 1;
Pet fetched = null;
ApiException exception = null;
do {
if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds");
Thread.sleep(1000);
@ -413,16 +425,16 @@ public class PetApiTest {
assertEquals(expected.getId(), actual.getId());
assertNotNull(actual.getCategory());
assertEquals(expected.getCategory().getName(),
actual.getCategory().getName());
actual.getCategory().getName());
}
/**
* Assert that the given upload/download progress list satisfies the
* following constraints:
*
* - List is not empty
* - Byte count should be nondecreasing
* - The last element, and only the last element, should have done=true
* <p>
* - List is not empty
* - Byte count should be nondecreasing
* - The last element, and only the last element, should have done=true
*/
private void assertValidProgress(List<Progress> progressList) {
assertFalse(progressList.isEmpty());
@ -433,7 +445,7 @@ public class PetApiTest {
if (prev != null) {
if (prev.done || prev.bytes > progress.bytes) {
fail("Progress list out of order at index " + index
+ ": " + progressList);
+ ": " + progressList);
}
}
prev = progress;
@ -449,9 +461,9 @@ public class PetApiTest {
private final CountDownLatch latch;
private final ConcurrentLinkedQueue<Progress> uploadProgress =
new ConcurrentLinkedQueue<Progress>();
new ConcurrentLinkedQueue<Progress>();
private final ConcurrentLinkedQueue<Progress> downloadProgress =
new ConcurrentLinkedQueue<Progress>();
new ConcurrentLinkedQueue<Progress>();
private boolean done;
private boolean success;

View File

@ -15,46 +15,52 @@ public class ApiKeyAuthTest {
public void testApplyToParamsInQuery() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> cookieParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("query", "api_key");
auth.setApiKey("my-api-key");
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
assertEquals(1, queryParams.size());
for (Pair queryParam : queryParams) {
assertEquals("my-api-key", queryParam.getValue());
}
// no changes to header parameters
// no changes to header or cookie parameters
assertEquals(0, headerParams.size());
assertEquals(0, cookieParams.size());
}
@Test
public void testApplyToParamsInQueryWithNullValue() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> cookieParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("query", "api_key");
auth.setApiKey(null);
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// no changes to parameters
assertEquals(0, queryParams.size());
assertEquals(0, headerParams.size());
assertEquals(0, cookieParams.size());
}
@Test
public void testApplyToParamsInHeaderWithPrefix() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> cookieParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN");
auth.setApiKey("my-api-token");
auth.setApiKeyPrefix("Token");
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// no changes to query parameters
// no changes to query or cookie parameters
assertEquals(0, queryParams.size());
assertEquals(0, cookieParams.size());
assertEquals(1, headerParams.size());
assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN"));
}
@ -63,14 +69,51 @@ public class ApiKeyAuthTest {
public void testApplyToParamsInHeaderWithNullValue() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> cookieParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN");
auth.setApiKey(null);
auth.setApiKeyPrefix("Token");
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// no changes to parameters
assertEquals(0, queryParams.size());
assertEquals(0, cookieParams.size());
assertEquals(0, headerParams.size());
}
@Test
public void testApplyToParamsInCookieWithPrefix() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> cookieParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("cookie", "X-API-TOKEN");
auth.setApiKey("my-api-token");
auth.setApiKeyPrefix("Token");
auth.applyToParams(queryParams, headerParams, cookieParams);
// no changes to query or header parameters
assertEquals(0, queryParams.size());
assertEquals(0, headerParams.size());
assertEquals(1, cookieParams.size());
assertEquals("Token my-api-token", cookieParams.get("X-API-TOKEN"));
}
@Test
public void testApplyToParamsInCookieWithNullValue() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> cookieParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("cookie", "X-API-TOKEN");
auth.setApiKey(null);
auth.setApiKeyPrefix("Token");
auth.applyToParams(queryParams, headerParams, cookieParams);
// no changes to parameters
assertEquals(0, queryParams.size());
assertEquals(0, cookieParams.size());
assertEquals(0, headerParams.size());
}
}

View File

@ -22,13 +22,15 @@ public class HttpBasicAuthTest {
public void testApplyToParams() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> cookieParams = new HashMap<String, String>();
auth.setUsername("my-username");
auth.setPassword("my-password");
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// no changes to query parameters
// no changes to query or cookie parameters
assertEquals(0, queryParams.size());
assertEquals(0, cookieParams.size());
assertEquals(1, headerParams.size());
// the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix
String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ=";
@ -36,7 +38,7 @@ public class HttpBasicAuthTest {
// null username should be treated as empty string
auth.setUsername(null);
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// the string below is base64-encoded result of ":my-password" with the "Basic " prefix
expected = "Basic Om15LXBhc3N3b3Jk";
assertEquals(expected, headerParams.get("Authorization"));
@ -44,7 +46,7 @@ public class HttpBasicAuthTest {
// null password should be treated as empty string
auth.setUsername("my-username");
auth.setPassword(null);
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// the string below is base64-encoded result of "my-username:" with the "Basic " prefix
expected = "Basic bXktdXNlcm5hbWU6";
assertEquals(expected, headerParams.get("Authorization"));
@ -54,7 +56,7 @@ public class HttpBasicAuthTest {
headerParams = new HashMap<String, String>();
auth.setUsername(null);
auth.setPassword(null);
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// no changes to parameters
assertEquals(0, queryParams.size());
assertEquals(0, headerParams.size());

View File

@ -17,31 +17,53 @@ public class ApiKeyAuthTest {
public void testApplyToParamsInQuery() {
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
HttpHeaders headerParams = new HttpHeaders();
MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("query", "api_key");
auth.setApiKey("my-api-key");
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
assertEquals(1, queryParams.size());
assertEquals("my-api-key", queryParams.get("api_key").get(0));
// no changes to header parameters
// no changes to header or cookie parameters
assertEquals(0, headerParams.size());
assertEquals(0, cookieParams.size());
}
@Test
public void testApplyToParamsInHeaderWithPrefix() {
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
HttpHeaders headerParams = new HttpHeaders();
MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN");
auth.setApiKey("my-api-token");
auth.setApiKeyPrefix("Token");
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// no changes to query parameters
// no changes to query or cookie parameters
assertEquals(0, queryParams.size());
assertEquals(0, cookieParams.size());
assertEquals(1, headerParams.size());
assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN").get(0));
}
@Test
public void testApplyToParamsInCookieWithPrefix() {
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
HttpHeaders headerParams = new HttpHeaders();
MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("cookie", "X-API-TOKEN");
auth.setApiKey("my-api-token");
auth.setApiKeyPrefix("Token");
auth.applyToParams(queryParams, headerParams, cookieParams);
// no changes to query or cookie parameters
assertEquals(0, queryParams.size());
assertEquals(0, headerParams.size());
assertEquals(1, cookieParams.size());
assertEquals("Token my-api-token", cookieParams.get("X-API-TOKEN").get(0));
}
}

View File

@ -24,13 +24,15 @@ public class HttpBasicAuthTest {
public void testApplyToParams() {
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
HttpHeaders headerParams = new HttpHeaders();
MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
auth.setUsername("my-username");
auth.setPassword("my-password");
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// no changes to query parameters
// no changes to query or cookie parameters
assertEquals(0, queryParams.size());
assertEquals(0, cookieParams.size());
assertEquals(1, headerParams.size());
// the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix
String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ=";
@ -38,7 +40,7 @@ public class HttpBasicAuthTest {
// null username should be treated as empty string
auth.setUsername(null);
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// the string below is base64-encoded result of ":my-password" with the "Basic " prefix
expected = "Basic Om15LXBhc3N3b3Jk";
assertEquals(expected, headerParams.get("Authorization").get(1));
@ -46,7 +48,7 @@ public class HttpBasicAuthTest {
// null password should be treated as empty string
auth.setUsername("my-username");
auth.setPassword(null);
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
// the string below is base64-encoded result of "my-username:" with the "Basic " prefix
expected = "Basic bXktdXNlcm5hbWU6";
assertEquals(expected, headerParams.get("Authorization").get(2));

View File

@ -2,7 +2,7 @@
<div align="center">
[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`4.2.0-SNAPSHOT`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`4.2.1-SNAPSHOT`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator)
[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=master)](https://app.shippable.com/github/OpenAPITools/openapi-generator)
[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu)
@ -60,7 +60,7 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se
| | Languages/Frameworks |
|-|-|
**API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0), **C++** (cpp-restsdk, Qt5, Tizen), **Clojure**, **Dart (1.x, 2.x)**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client), **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x), **Typescript** (AngularJS, Angular (2.x - 8.x), Aurelia, Axios, Fetch, Inversify, jQuery, Node, Rxjs)
**Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin), **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** ([Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra)
**Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin), **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** ([Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra)
**API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc**
**Configuration files** | [**Apache2**](https://httpd.apache.org/)
**Others** | **GraphQL**, **JMeter**, **MySQL Schema**, **Protocol Buffer**
@ -84,6 +84,7 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se
- [3.2 - Workflow Integration](#32---workflow-integration-maven-gradle-github-cicd)
- [3.3 - Online Generators](#33---online-openapi-generator)
- [3.4 - License Information on Generated Code](#34---license-information-on-generated-code)
- [3.5 - IDE Integration](#35---ide-integration)
- [4 - Companies/Projects using OpenAPI Generator](#4---companiesprojects-using-openapi-generator)
- [5 - Presentations/Videos/Tutorials/Books](#5---presentationsvideostutorialsbooks)
- [6 - About Us](#6---about-us)
@ -101,8 +102,9 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20
OpenAPI Generator Version | Release Date | Notes
---------------------------- | ------------ | -----
5.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.0.0-SNAPSHOT/)| 13.05.2020 | Major release with breaking changes (no fallback)
4.2.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.2.0-SNAPSHOT/)| 09.10.2019 | Minor release (breaking changes with fallbacks)
[4.1.3](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.1.3) (latest stable release) | 04.10.2019 | Patch release (bug fixes, enhancements)
4.3.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.3.0-SNAPSHOT/)| 29.02.2020 | Minor release (breaking changes with fallbacks)
4.2.1 (upcoming patch release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.2.1-SNAPSHOT/)| 15.11.2019 | Patch release
[4.2.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.2.0) (latest stable release) | 31.10.2019 | Minor release (bug fixes, enhancements, breaking chanages with fallbacks)
OpenAPI Spec compatibility: 1.0, 1.1, 1.2, 2.0, 3.0
@ -158,16 +160,16 @@ See the different versions of the [openapi-generator-cli](https://mvnrepository.
<!-- RELEASE_VERSION -->
If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 8 runtime at a minimum):
JAR location: `http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.1.3/openapi-generator-cli-4.1.3.jar`
JAR location: `http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.2.0/openapi-generator-cli-4.2.0.jar`
For **Mac/Linux** users:
```sh
wget http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.1.3/openapi-generator-cli-4.1.3.jar -O openapi-generator-cli.jar
wget http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.2.0/openapi-generator-cli-4.2.0.jar -O openapi-generator-cli.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 openapi-generator-cli.jar http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.1.3/openapi-generator-cli-4.1.3.jar
Invoke-WebRequest -OutFile openapi-generator-cli.jar http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.2.0/openapi-generator-cli-4.2.0.jar
```
After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage.
@ -382,10 +384,10 @@ openapi-generator version
```
<!-- RELEASE_VERSION -->
Or install a particular OpenAPI Generator version (e.g. v4.1.3):
Or install a particular OpenAPI Generator version (e.g. v4.2.0):
```sh
npm install @openapitools/openapi-generator-cli@cli-4.1.3 -g
npm install @openapitools/openapi-generator-cli@cli-4.2.0 -g
```
Or install it as dev-dependency:
@ -409,7 +411,7 @@ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generat
(if you're on Windows, replace the last command with `java -jar modules\openapi-generator-cli\target\openapi-generator-cli.jar generate -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g php -o c:\temp\php_api_client`)
<!-- RELEASE_VERSION -->
You can also download the JAR (latest release) directly from [maven.org](http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.1.3/openapi-generator-cli-4.1.3.jar)
You can also download the JAR (latest release) directly from [maven.org](http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.2.0/openapi-generator-cli-4.2.0.jar)
<!-- /RELEASE_VERSION -->
To get a list of **general** options available, please run `java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar help generate`
@ -537,17 +539,32 @@ The OpenAPI Generator project is intended as a benefit for users of the Open API
* Generated code is intentionally _not_ subject to the parent project license
When code is generated from this project, it shall be considered **AS IS** and owned by the user of the software. There are no warranties--expressed or implied--for generated code. You can do what you wish with it, and once generated, the code is your responsibility and subject to the licensing terms that you deem appropriate.
### [3.5 - IDE Integration](#table-of-contents)
Here is a list of community-conitributed IDE plug-ins that integrate with OpenAPI Generator:
- Eclipse: [Codewind OpenAPI Tools for Eclipse](https://www.eclipse.org/codewind/open-api-tools-for-eclipse.html) by [IBM](https://www.ibm.com)
- IntelliJ IDEA: [OpenAPI Generator](https://plugins.jetbrains.com/plugin/8433-openapi-generator) by [Jim Schubert](https://jimschubert.us/#/)
- IntelliJ IDEA: [Senya Editor](https://plugins.jetbrains.com/plugin/10690-senya-editor) by [senya.io](https://senya.io)
- [RepreZen API Studio](https://www.reprezen.com/)
- Visual Studio: [REST API Client Code Generator](https://marketplace.visualstudio.com/items?itemName=ChristianResmaHelle.ApiClientCodeGenerator) by [Christian Resma Helle](https://christian-helle.blogspot.com/)
- Visual Studio Code: [Codewind OpenAPI Tools](https://marketplace.visualstudio.com/items?itemName=IBM.codewind-openapi-tools) by [IBM](https://marketplace.visualstudio.com/publishers/IBM)
## [4 - Companies/Projects using OpenAPI Generator](#table-of-contents)
Here are some companies/projects (alphabetical order) using OpenAPI Generator in production. To add your company/project to the list, please visit [README.md](README.md) and click on the icon to edit the page.
- [Adaptant Solutions AG](https://www.adaptant.io/)
- [Angular.Schule](https://angular.schule/)
- [Australia and New Zealand Banking Group (ANZ)](http://www.anz.com/)
- [ASKUL](https://www.askul.co.jp)
- [Arduino](https://www.arduino.cc/)
- [b<>com](https://b-com.com/en)
- [Banzai Cloud](https://banzaicloud.com)
- [BIMData.io](https://bimdata.io)
- [Bithost GmbH](https://www.bithost.ch)
- [Bosch Connected Industry](https://www.bosch-connected-industry.com)
- [Boxever](https://www.boxever.com/)
- [California State University, Northridge](https://www.csun.edu)
- [CAM](https://www.cam-inc.co.jp/)
@ -556,31 +573,42 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [Commencis](https://www.commencis.com/)
- [Cupix](https://www.cupix.com/)
- [DB Systel](https://www.dbsystel.de)
- [dwango](https://dwango.co.jp/)
- [Edge Impulse](https://www.edgeimpulse.com/)
- [Element AI](https://www.elementai.com/)
- [Fenergo](https://www.fenergo.com/)
- [FormAPI](https://formapi.io/)
- [Fuse](https://www.fuse.no/)
- [Gantner](https://www.gantner.com)
- [GenFlow](https://github.com/RepreZen/GenFlow)
- [GMO Pepabo](https://pepabo.com/en/)
- [GoDaddy](https://godaddy.com)
- [Here](https://developer.here.com/)
- [IBM](https://www.ibm.com/)
- [JustStar](https://www.juststarinfo.com)
- [Klarna](https://www.klarna.com/)
- [Médiavision](https://www.mediavision.fr/)
- [Metaswitch](https://www.metaswitch.com/)
- [Myworkout](https://myworkout.com)
- [NamSor](https://www.namsor.com/)
- [Openet](https://www.openet.com/)
- [Paxos](https://www.paxos.com)
- [Ponicode](https://ponicode.dev/)
- [Pricefx](https://www.pricefx.com/)
- [Prometheus/Alertmanager](https://github.com/prometheus/alertmanager)
- [Raiffeisen Schweiz Genossenschaft](https://www.raiffeisen.ch)
- [RedHat](https://www.redhat.com)
- [RepreZen API Studio](https://www.reprezen.com/swagger-openapi-code-generation-api-first-microservices-enterprise-development)
- [REST United](https://restunited.com)
- [Stingray](http://www.stingray.com)
- [Suva](https://www.suva.ch/)
- [Telstra](https://dev.telstra.com)
- [TravelTime platform](https://www.traveltimeplatform.com/)
- [TUI InfoTec GmbH](http://www.tui-infotec.com/)
- [unblu inc.](https://www.unblu.com/)
- [Veamly](https://www.veamly.com/)
- [WSO2](https://wso2.com/)
- [Vouchery.io](https://vouchery.io)
- [Xero](https://www.xero.com/)
- [Yelp](https://www.yelp.com/)
- [Zalando](https://www.zalando.com)
@ -643,9 +671,13 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- 2019-09-22 - [RESTful APIs: Tutorial of OpenAPI Specification](https://medium.com/@amirm.lavasani/restful-apis-tutorial-of-openapi-specification-eeada0e3901d) by [Amir Lavasani](https://medium.com/@amirm.lavasani)
- 2019-09-22 - [Redefining SDKs as software diversity kits](https://devrel.net/dev-rel/redefining-sdks-as-software-diversity-kits) by [Sid Maestre (Xero)](https://twitter.com/sidneyallen) at [DevRelCon San Francisco 2019](https://sf2019.devrel.net/)
- 2019-09-23 - [swaggerからOpenApi GeneratorでSpringのコードを自動生成](https://qiita.com/littleFeet/items/492df2ad68a0799a5e5e) by [@littleFeet](https://qiita.com/littleFeet) at [Qiita](https://qiita.com/)
- 2019-09-24 - [Eine Stunde was mit Api First!](https://www.slideshare.net/JanWeinschenker/eine-stunde-was-mit-api-first) by [@janweinschenker](https://twitter.com/janweinschenker) at [Java Forum Nord](https://javaforumnord.de/)
- 2019-10-09 - [openapi-generator で生成した Go クライアントで Bearer 認証をする](https://autopp-tech.hatenablog.com/entry/2019/10/09/222039) by [Akira Tanimura](https://github.com/autopp)
- 2019-10-10 - [Automatic Generation of REST Clients](https://www.meetup.com/fr-FR/Criteo-Labs-Tech-Talks/events/264775768/) by Thomas Peyrard, Senior Software Engineer at Criteo in [Full-Stack Tech Talks (Meetup)](https://www.meetup.com/fr-FR/Criteo-Labs-Tech-Talks/events/264775768/)
- 2019-10-12 - [OpenApi自动生成client](https://blog.csdn.net/wxid2798226/article/details/102527467) by [郑泽洲](https://me.csdn.net/wxid2798226)
- 2019-10-16 - [How to ship APIs faster?](https://medium.com/@accounts_76224/how-to-ship-apis-faster-cabef2f819e4) by [Simon Guilliams @ PoniCode](https://ponicode.dev)
- 2019-10-22 - [OpenAPI + Spring Boot(Kotlin)でファイルダウンロードAPIを作成する](https://qiita.com/boronngo/items/4b78b92526209daeaee9) by [Yuki Furukawa](https://twitter.com/yuki_furukawa5)
- 2019-10-24 - [Microprofile OpenAPI - Code First or Design First?](https://github.com/pe-st/apidocs/blob/master/MicroProfile-OpenAPI-all-slides.pdf) by [Peter [pɛʃə] Steiner](https://twitter.com/pesche) at [eclipsecon Europe 2019](https://www.eclipsecon.org/europe2019/sessions/microprofile-openapi-code-first-or-design-first)
## [6 - About Us](#table-of-contents)
@ -754,6 +786,7 @@ Here is a list of template creators:
* Java Undertow: @stevehu
* Java Play Framework: @JFCote
* Java PKMST: @anshu2185 @sanshuman @rkumar-pk @ninodpillai
* Java Vert.x: @lwlee2608
* JAX-RS RestEasy: @chameleon82
* JAX-RS CXF: @hiveship
* JAX-RS CXF (CDI): @nickcmaynard
@ -837,8 +870,8 @@ If you want to join the committee, please kindly apply by sending an email to te
| GraphQL | @renepardon (2018/12) |
| Groovy | |
| Haskell | |
| Java | @bbdouglas (2017/07) @sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01) @karismann (2019/03) @Zomzog (2019/04) |
| Kotlin | @jimschubert (2017/09) [:heart:](https://www.patreon.com/jimschubert), @dr4ke616 (2018/08) @karismann (2019/03) @Zomzog (2019/04) |
| Java | @bbdouglas (2017/07) @sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01) @karismann (2019/03) @Zomzog (2019/04) @lwlee2608 (2019/10) |
| Kotlin | @jimschubert (2017/09) [:heart:](https://www.patreon.com/jimschubert), @dr4ke616 (2018/08) @karismann (2019/03) @Zomzog (2019/04) @andrewemery (2019/10) |
| Lua | @daurnimator (2017/08) |
| Nim | |
| NodeJS/Javascript | @CodeNinjai (2017/07) @frol (2017/07) @cliffano (2017/07) |
@ -847,7 +880,7 @@ If you want to join the committee, please kindly apply by sending an email to te
| Perl | @wing328 (2017/07) [:heart:](https://www.patreon.com/wing328) @yue9944882 (2019/06) |
| PHP | @jebentier (2017/07), @dkarlovi (2017/07), @mandrean (2017/08), @jfastnacht (2017/09), @ackintosh (2017/09) [:heart:](https://www.patreon.com/ackintosh/overview), @ybelenko (2018/07), @renepardon (2018/12) |
| PowerShell | |
| Python | @taxpon (2017/07) @frol (2017/07) @mbohlool (2017/07) @cbornet (2017/09) @kenjones-cisco (2017/11) @tomplus (2018/10) @Jyhess (2019/01) |
| Python | @taxpon (2017/07) @frol (2017/07) @mbohlool (2017/07) @cbornet (2017/09) @kenjones-cisco (2017/11) @tomplus (2018/10) @Jyhess (2019/01) @slash-arun (2019/11) |
| R | @Ramanth (2019/07) @saigiridhar21 (2019/07) |
| Ruby | @cliffano (2017/07) @zlx (2017/09) @autopp (2019/02) |
| Rust | @frol (2017/07) @farcaller (2017/08) @bjgill (2017/12) @richardwhiuk (2019/07) |

View File

@ -1,5 +1,5 @@
{
"generatorName": "php-slim",
"generatorName": "php-slim-deprecated",
"inputSpec": "modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml",
"outputDir": "samples/server/petstore/php-slim",
"templateDir": "modules/openapi-generator/src/main/resources/php-slim-server"

34
bin/dart-dio-petstore.sh Executable file
View File

@ -0,0 +1,34 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn -B clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
# Generate non-browserClient
ags="generate -t modules/openapi-generator/src/main/resources/dart-dio -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g dart-dio -o samples/client/petstore/dart-dio/ --additional-properties hideGenerationTimestamp=true $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -29,8 +29,8 @@ SPEC="modules/openapi-generator/src/test/resources/2_0/petstore.yaml"
GENERATOR="go-gin-server"
STUB_DIR="samples/server/petstore/go-gin-api-server"
echo "Removing files and folders under $STUB_DIR"
rm -rf $STUB_DIR
echo "Removing auto-generated files and folders under $STUB_DIR"
rm -rf $STUB_DIR/go
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
@ -38,4 +38,3 @@ export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/go-gin-server -i $SPEC -g $GENERATOR -o $STUB_DIR --additional-properties packageName=petstoreserver --additional-properties hideGenerationTimestamp=true $@"
java $JAVA_OPTS -jar $executable $ags
#!/usr/bin/env bash

View File

@ -29,8 +29,8 @@ SPEC="modules/openapi-generator/src/test/resources/2_0/petstore.yaml"
GENERATOR="go-server"
STUB_DIR="samples/server/petstore/go-api-server"
echo "Removing files and folders under $STUB_DIR"
rm -rf $STUB_DIR
echo "Removing auto-generated files and folders under $STUB_DIR"
rm -rf $STUB_DIR/go
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"

View File

@ -0,0 +1,37 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn -B clean package
fi
SPEC="modules/openapi-generator/src/test/resources/3_0/petstore.yaml"
GENERATOR="java-vertx-web"
TEMPLATE="modules/openapi-generator/src/main/resources/JavaVertXWebServer"
STUB_DIR="samples/server/petstore/java-vertx-web/rx"
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -i $SPEC -t $TEMPLATE -g $GENERATOR --artifact-id java-vertx-web-rx-server -o $STUB_DIR --additional-properties hideGenerationTimestamp=true $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/php-slim-server -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g php-slim -o samples/server/petstore/php-slim $@"
ags="generate -t modules/openapi-generator/src/main/resources/php-slim-server -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g php-slim-deprecated -o samples/server/petstore/php-slim $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -0,0 +1,32 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/php-slim4-server -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g php-slim4 -o samples/server/petstore/php-slim4 $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/php-slim-server -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g php-slim -o samples/server/petstore/php-slim $@"
ags="generate -t modules/openapi-generator/src/main/resources/php-slim-server -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g php-slim-deprecated -o samples/server/petstore/php-slim $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -0,0 +1,32 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn -B clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/php-slim4-server -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g php-slim4 -o samples/server/petstore/php-slim4 $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -14,3 +14,4 @@
./bin/typescript-angular-v7-petstore-provided-in-root.sh
./bin/typescript-angular-v7-petstore-provided-in-root-with-npm.sh
./bin/typescript-angular-v8-petstore-provided-in-root-with-npm.sh
./bin/typescript-angular-v8-petstore-provided-in-root-with-prefixed-module-name.sh

View File

@ -0,0 +1,32 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn -B clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g typescript-angular -c bin/typescript-angular-v8-petstore-provided-in-root-with-npm.json -o samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name --additional-properties ngVersion=8.0.0,apiModulePrefix=PetStore $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -39,6 +39,7 @@ declare -a scripts=(
"./bin/php-symfony-petstore.sh"
"./bin/php-lumen-petstore-server.sh"
"./bin/php-slim-server-petstore.sh"
"./bin/php-slim4-server-petstore.sh"
"./bin/php-ze-ph-petstore-server.sh"
"./bin/openapi3/php-petstore.sh"
"./bin/typescript-angularjs-petstore.sh"
@ -60,6 +61,7 @@ declare -a scripts=(
"./bin/go-experimental-petstore.sh"
"./bin/go-petstore.sh"
"./bin/go-petstore-withxml.sh"
"./bin/go-petstore-server.sh"
"./bin/go-gin-petstore-server.sh"
"./bin/groovy-petstore.sh"
"./bin/apex-petstore.sh"

View File

@ -22,7 +22,7 @@ set -o pipefail
for cmd in {mvn,jq,curl}; do
if ! command -v ${cmd} > /dev/null; then
>&2 echo "This script requires '${cmd}' to be installed."
>&2 echo "This script requires '${cmd}' to be installed."
exit 1
fi
done
@ -42,7 +42,18 @@ artifactid=openapi-generator-cli
ver=${OPENAPI_GENERATOR_VERSION:-$(latest.tag $ghrepo)}
jar=${artifactid}-${ver}.jar
DIR=${OPENAPI_GENERATOR_DOWLOAD_CACHE_DIR:-"$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"}
# TODO: Remove OPENAPI_GENERATOR_DOWLOAD_CACHE_DIR for release 5.0
if [ -n "${OPENAPI_GENERATOR_DOWLOAD_CACHE_DIR}" ]; then
>&2 printf "[WARN] Variable OPENAPI_GENERATOR_DOWLOAD_CACHE_DIR is misspelled.\nPlease change to OPENAPI_GENERATOR_DOWNLOAD_CACHE_DIR. This option will be removed in the 5.0 release.\n"
fi
cachedir=${OPENAPI_GENERATOR_DOWNLOAD_CACHE_DIR:-"$OPENAPI_GENERATOR_DOWLOAD_CACHE_DIR"}
DIR=${cachedir:-"$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"}
if [ ! -d "${DIR}" ]; then
mkdir -p "${DIR}"
fi
if [ ! -f ${DIR}/${jar} ]; then
repo="central::default::https://repo1.maven.org/maven2/"

View File

@ -0,0 +1,10 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g dart-dio -o samples\client\petstore\dart-dio --additional-properties hideGenerationTimestamp=true
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -11,7 +11,7 @@ set GENERATOR=go-gin-server
set STUB_DIR=samples\server\petstore\go-gin-api-server
echo Removing files and folders under %STUB_DIR%
del /F /S /Q %STUB_DIR%
del /F /S /Q %STUB_DIR%\go
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i %SPEC% -g %GENERATOR% -o %STUB_DIR% --additional-properties packageName=petstoreserver

View File

@ -11,11 +11,11 @@ set GENERATOR=go-server
set STUB_DIR=samples\server\petstore\go-api-server
echo Removing files and folders under %STUB_DIR%
del /F /S /Q %STUB_DIR%
del /F /S /Q %STUB_DIR%\go
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i %SPEC% -g %GENERATOR% -o %STUB_DIR% --additional-properties packageName=petstoreserver
java %JAVA_OPTS% -jar %executable% %ags%
endlocal
endlocal

View File

@ -5,6 +5,6 @@ If Not Exist %executable% (
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g php-slim -o samples\server\petstore\php-slim
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g php-slim-deprecated -o samples\server\petstore\php-slim
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -0,0 +1,10 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g php-slim4 -o samples\server\petstore\php-slim4
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -5,6 +5,6 @@ If Not Exist %executable% (
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g python-experimental -o samples\client\petstore\python-experimental -DpackageName=petstore_api
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\python-client-experimental\petstore-with-fake-endpoints-models-for-testing.yaml -g python-experimental -o samples\client\petstore\python-experimental --additional-properties packageName=petstore_api
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -12,3 +12,4 @@ call .\bin\windows\typescript-angular-v7-provided-in-root-with-npm.bat
call .\bin\windows\typescript-angular-v7-not-provided-in-root.bat
call .\bin\windows\typescript-angular-v7-not-provided-in-root-with-npm.bat
call .\bin\windows\typescript-angular-v8-provided-in-root-with-npm.bat
call .\bin\windows\typescript-angular-v8-petstore-provided-in-root-with-prefixed-module-name.bat

View File

@ -0,0 +1,10 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g typescript-angular -c bin/typescript-angular-v8-petstore-provided-in-root-with-npm.json -o samples\client\petstore\typescript-angular-v8-provided-in-root\builds\with-prefixed-module-name --additional-properties ngVersion=8.0.0,apiModulePrefix=PetStore
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -5,6 +5,6 @@ If Not Exist %executable% (
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -c bin\typescript-petstore-npm.json -g typescript-jquery -o samples\client\petstore\typescript-jquery\npm
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -c bin\typescript-jquery-petstore-npm.json -g typescript-jquery -o samples\client\petstore\typescript-jquery\npm
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -88,6 +88,7 @@ The following generators are available:
* [java-play-framework](generators/java-play-framework.md)
* [java-undertow-server](generators/java-undertow-server.md)
* [java-vertx](generators/java-vertx.md)
* [java-vertx-web (beta)](generators/java-vertx-web.md)
* [jaxrs-cxf](generators/jaxrs-cxf.md)
* [jaxrs-cxf-cdi](generators/jaxrs-cxf-cdi.md)
* [jaxrs-cxf-extended](generators/jaxrs-cxf-extended.md)
@ -103,7 +104,8 @@ The following generators are available:
* [php-laravel](generators/php-laravel.md)
* [php-lumen](generators/php-lumen.md)
* [php-silex](generators/php-silex.md)
* [php-slim](generators/php-slim.md)
* [php-slim-deprecated (deprecated)](generators/php-slim-deprecated.md)
* [php-slim4](generators/php-slim4.md)
* [php-symfony](generators/php-symfony.md)
* [php-ze-ph](generators/php-ze-ph.md)
* [python-aiohttp](generators/python-aiohttp.md)

View File

@ -10,7 +10,7 @@ sidebar_label: csharp
|sourceFolder|source folder for generated code| |src|
|packageGuid|The GUID that will be associated with the C# project| |null|
|interfacePrefix|Prefix interfaces with a community standard or widely accepted prefix.| |I|
|targetFramework|The target .NET framework version.|<dl><dt>**v3.5**</dt><dd>.NET Framework 3.5 compatible</dd><dt>**v4.0**</dt><dd>.NET Framework 4.0 compatible</dd><dt>**v4.5**</dt><dd>.NET Framework 4.5+ compatible</dd><dt>**v5.0**</dt><dd>.NET Standard 1.3 compatible</dd><dt>**uwp**</dt><dd>Universal Windows Platform (IMPORTANT: this will be decommissioned and replaced by v5.0)</dd><dl>|v4.5|
|targetFramework|The target .NET framework version.|<dl><dt>**v3.5**</dt><dd>.NET Framework 3.5 compatible</dd><dt>**v4.0**</dt><dd>.NET Framework 4.0 compatible</dd><dt>**v4.5**</dt><dd>.NET Framework 4.5+ compatible</dd><dt>**v5.0**</dt><dd>.NET Standard 1.3 compatible (DEPRECATED. Please use `csharp-netcore` generator instead)</dd><dt>**uwp**</dt><dd>Universal Windows Platform (DEPRECATED. Please use `csharp-netcore` generator instead)</dd><dl>|v4.5|
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |PascalCase|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|

View File

@ -11,3 +11,4 @@ sidebar_label: haskell
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|modelPackage|package for generated models| |null|
|apiPackage|package for generated api classes| |null|
|serveStatic|serve will serve files from the directory 'static'.| |true|

View File

@ -0,0 +1,42 @@
---
title: Config Options for java-vertx-web
sidebar_label: java-vertx-web
---
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|modelPackage|package for generated models| |org.openapitools.vertxweb.server.model|
|apiPackage|package for generated api classes| |org.openapitools.vertxweb.server.api|
|invokerPackage|root package for generated code| |org.openapitools.vertxweb.server|
|groupId|groupId in generated pom.xml| |org.openapitools|
|artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-java-vertx-web-server|
|artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0-SNAPSHOT|
|artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator|
|artifactDescription|artifact description in generated pom.xml| |OpenAPI Java|
|scmConnection|SCM connection in generated pom.xml| |scm:git:git@github.com:openapitools/openapi-generator.git|
|scmDeveloperConnection|SCM developer connection in generated pom.xml| |scm:git:git@github.com:openapitools/openapi-generator.git|
|scmUrl|SCM URL in generated pom.xml| |https://github.com/openapitools/openapi-generator|
|developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors|
|developerEmail|developer email in generated pom.xml| |team@openapitools.org|
|developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org|
|developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org|
|licenseName|The name of the license| |Unlicense|
|licenseUrl|The URL of the license| |http://unlicense.org|
|sourceFolder|source folder for generated code| |src/main/java|
|serializableModel|boolean - toggle &quot;implements Serializable&quot; for generated models| |false|
|bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false|
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|
|dateLibrary|Option. Date library to use|<dl><dt>**joda**</dt><dd>Joda (for legacy app only)</dd><dt>**legacy**</dt><dd>Legacy java.util.Date (if you really have a good reason not to use threetenbp</dd><dt>**java8-localdatetime**</dt><dd>Java 8 using LocalDateTime (for legacy app only)</dd><dt>**java8**</dt><dd>Java 8 native JSR310 (preferred for jdk 1.8+) - note: this also sets &quot;java8&quot; to true</dd><dt>**threetenbp**</dt><dd>Backport of JSR310 (preferred for jdk &lt; 1.8)</dd><dl>|java8|
|java8|Option. Use Java8 classes instead of third party equivalents|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd><dl>|false|
|disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false|
|booleanGetterPrefix|Set booleanGetterPrefix| |get|
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|parentArtifactId|parent artifactId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|parentVersion|parent version in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
|snapshotVersion|Uses a SNAPSHOT version.|<dl><dt>**true**</dt><dd>Use a SnapShot Version</dd><dt>**false**</dt><dd>Use a Release Version</dd><dl>|null|

View File

@ -0,0 +1,18 @@
---
title: Config Options for php-slim-deprecated
sidebar_label: php-slim-deprecated
---
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|modelPackage|package for generated models| |null|
|apiPackage|package for generated api classes| |null|
|variableNamingConvention|naming convention of variable name, e.g. camelCase.| |camelCase|
|invokerPackage|The main namespace to use for all classes. e.g. Yay\Pets| |null|
|packageName|The main package name for classes. e.g. GeneratedPetstore| |null|
|srcBasePath|The directory to serve as source root.| |null|
|artifactVersion|The version to use in the composer package version field. e.g. 1.2.3| |null|

View File

@ -0,0 +1,19 @@
---
title: Config Options for php-slim4
sidebar_label: php-slim4
---
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|modelPackage|package for generated models| |null|
|apiPackage|package for generated api classes| |null|
|variableNamingConvention|naming convention of variable name, e.g. camelCase.| |camelCase|
|invokerPackage|The main namespace to use for all classes. e.g. Yay\Pets| |null|
|packageName|The main package name for classes. e.g. GeneratedPetstore| |null|
|srcBasePath|The directory to serve as source root.| |null|
|artifactVersion|The version to use in the composer package version field. e.g. 1.2.3| |null|
|psr7Implementation|Slim 4 provides its own PSR-7 implementation so that it works out of the box. However, you are free to replace Slim&rsquo;s default PSR-7 objects with a third-party implementation. Ref: https://www.slimframework.com/docs/v4/concepts/value-objects.html|<dl><dt>**slim-psr7**</dt><dd>Slim PSR-7 Message implementation</dd><dt>**nyholm-psr7**</dt><dd>Nyholm PSR-7 Message implementation</dd><dt>**guzzle-psr7**</dt><dd>Guzzle PSR-7 Message implementation</dd><dt>**zend-diactoros**</dt><dd>Zend Diactoros PSR-7 Message implementation</dd><dl>|slim-psr7|

View File

@ -19,6 +19,7 @@ sidebar_label: typescript-angular
|taggedUnions|Use discriminators to create tagged unions instead of extending interfaces.| |false|
|providedInRoot|Use this property to provide Injectables in root (it is only valid in angular version greater or equal to 6.0.0).| |false|
|ngVersion|The version of Angular.| |8.0.0|
|apiModulePrefix|The prefix of the generated ApiModule.| |null|
|serviceSuffix|The suffix of the generated service.| |Service|
|serviceFileSuffix|The suffix of the file of the generated service (service&lt;suffix&gt;.ts).| |.service|
|modelSuffix|The suffix of the generated model.| |null|

View File

@ -45,7 +45,7 @@ compileJava.dependsOn tasks.openApiGenerate
[source,group]
----
plugins {
id "org.openapi.generator" version "4.1.1"
id "org.openapi.generator" version "4.2.0"
}
----
@ -61,7 +61,7 @@ buildscript {
// url "https://plugins.gradle.org/m2/"
}
dependencies {
classpath "org.openapitools:openapi-generator-gradle-plugin:4.1.1"
classpath "org.openapitools:openapi-generator-gradle-plugin:4.2.0"
}
}
@ -626,7 +626,7 @@ buildscript {
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath('org.openapitools:openapi-generator-gradle-plugin:4.1.1') {
classpath('org.openapitools:openapi-generator-gradle-plugin:4.2.0') {
exclude group: 'com.google.guava'
}
}

View File

@ -1,5 +1,5 @@
buildscript {
ext.kotlin_version = '1.2.61'
ext.kotlin_version = '1.3.20'
repositories {
mavenLocal()
mavenCentral()
@ -15,7 +15,7 @@ buildscript {
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "gradle.plugin.org.gradle.kotlin:gradle-kotlin-dsl-plugins:1.0-rc-3"
classpath "gradle.plugin.org.gradle.kotlin:gradle-kotlin-dsl-plugins:1.1.3"
classpath "com.gradle.publish:plugin-publish-plugin:0.10.1"
classpath "io.codearte.gradle.nexus:gradle-nexus-staging-plugin:0.20.0"
classpath "de.marcphilipp.gradle:nexus-publish-plugin:0.2.0"

View File

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://downloads.gradle.org/distributions/gradle-4.10.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@ -17,7 +17,7 @@
<properties>
<skipNexusStagingDeployMojo>true</skipNexusStagingDeployMojo>
<gradleVersion>4.10.2</gradleVersion>
<gradleVersion>5.2.1</gradleVersion>
</properties>
<pluginRepositories>

View File

@ -17,5 +17,5 @@ gradle generateGoWithInvalidSpec
The samples can be tested against other versions of the plugin using the `openApiGeneratorVersion` property. For example:
```bash
gradle -PopenApiGeneratorVersion=4.1.1 openApiValidate
gradle -PopenApiGeneratorVersion=4.2.0 openApiValidate
```

View File

@ -18,6 +18,7 @@ package org.openapitools.generator.gradle.plugin.extensions
import org.gradle.api.Project
import org.gradle.kotlin.dsl.listProperty
import org.gradle.kotlin.dsl.mapProperty
import org.gradle.kotlin.dsl.property
/**
@ -66,7 +67,7 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
/**
* Sets specified system properties.
*/
val systemProperties = project.objects.property<Map<String, String>>()
val systemProperties = project.objects.mapProperty<String, String>()
/**
* Path to json configuration file.
@ -108,22 +109,22 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
/**
* Sets instantiation type mappings.
*/
val instantiationTypes = project.objects.property<Map<String, String>>()
val instantiationTypes = project.objects.mapProperty<String, String>()
/**
* Sets mappings between OpenAPI spec types and generated code types.
*/
val typeMappings = project.objects.property<Map<String, String>>()
val typeMappings = project.objects.mapProperty<String, String>()
/**
* Sets additional properties that can be referenced by the mustache templates.
*/
val additionalProperties = project.objects.property<Map<String, String>>()
val additionalProperties = project.objects.mapProperty<String, String>()
/**
* Sets server variable for server URL template substitution, in the format of name=value,name=value.
*/
val serverVariables = project.objects.property<Map<String, String>>()
val serverVariables = project.objects.mapProperty<String, String>()
/**
* Specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: String,boolean,Boolean,Double.
@ -133,7 +134,7 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
/**
* Specifies mappings between a given class and the import that should be used for that class.
*/
val importMappings = project.objects.property<Map<String, String>>()
val importMappings = project.objects.mapProperty<String, String>()
/**
* Root package for generated code.
@ -188,7 +189,7 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
/**
* Specifies how a reserved name should be escaped to. Otherwise, the default _<name> is used.
*/
val reservedWordsMappings = project.objects.property<Map<String, String>>()
val reservedWordsMappings = project.objects.mapProperty<String, String>()
/**
* Specifies an override location for the .openapi-generator-ignore file. Most useful on initial generation.
@ -304,7 +305,7 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
/**
* A map of options specific to a generator.
*/
val configOptions = project.objects.property<Map<String, String>>()
val configOptions = project.objects.mapProperty<String, String>()
init {
applyDefaults()

View File

@ -24,6 +24,7 @@ import org.gradle.api.tasks.TaskAction
import org.gradle.internal.logging.text.StyledTextOutput
import org.gradle.internal.logging.text.StyledTextOutputFactory
import org.gradle.kotlin.dsl.listProperty
import org.gradle.kotlin.dsl.mapProperty
import org.gradle.kotlin.dsl.property
import org.openapitools.codegen.CodegenConstants
import org.openapitools.codegen.DefaultGenerator
@ -90,7 +91,7 @@ open class GenerateTask : DefaultTask() {
* Sets specified system properties.
*/
@get:Internal
val systemProperties = project.objects.property<Map<String, String>>()
val systemProperties = project.objects.mapProperty<String, String>()
/**
* Path to json configuration file.
@ -140,27 +141,27 @@ open class GenerateTask : DefaultTask() {
* Sets instantiation type mappings.
*/
@get:Internal
val instantiationTypes = project.objects.property<Map<String, String>>()
val instantiationTypes = project.objects.mapProperty<String, String>()
/**
* Sets mappings between OpenAPI spec types and generated code types.
*/
@get:Internal
val typeMappings = project.objects.property<Map<String, String>>()
val typeMappings = project.objects.mapProperty<String, String>()
/**
* 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.
*/
@get:Internal
val additionalProperties = project.objects.property<Map<String, String>>()
val additionalProperties = project.objects.mapProperty<String, String>()
/**
* Sets server variable for server URL template substitution, in the format of name=value,name=value.
* You can also have multiple occurrences of this option.
*/
@get:Internal
val serverVariables = project.objects.property<Map<String, String>>()
val serverVariables = project.objects.mapProperty<String, String>()
/**
* Specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: String,boolean,Boolean,Double.
@ -172,7 +173,7 @@ open class GenerateTask : DefaultTask() {
* Specifies mappings between a given class and the import that should be used for that class.
*/
@get:Internal
val importMappings = project.objects.property<Map<String, String>>()
val importMappings = project.objects.mapProperty<String, String>()
/**
* Root package for generated code.
@ -238,7 +239,7 @@ open class GenerateTask : DefaultTask() {
* Specifies how a reserved name should be escaped to.
*/
@get:Internal
val reservedWordsMappings = project.objects.property<Map<String, String>>()
val reservedWordsMappings = project.objects.mapProperty<String, String>()
/**
* Specifies an override location for the .openapi-generator-ignore file. Most useful on initial generation.
@ -372,7 +373,7 @@ open class GenerateTask : DefaultTask() {
* A dynamic map of options specific to a generator.
*/
@get:Internal
val configOptions = project.objects.property<Map<String, String>>()
val configOptions = project.objects.mapProperty<String, String>()
private fun <T : Any?> Property<T>.ifNotEmpty(block: Property<T>.(T) -> Unit) {
if (isPresent) {

View File

@ -12,7 +12,7 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase)
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>4.1.1</version>
<version>4.2.0</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@ -198,8 +198,8 @@
<diffutils-version>1.3.0</diffutils-version>
<guava-version>26.0-jre</guava-version>
<generex-version>1.0.2</generex-version>
<jackson-version>2.9.5</jackson-version>
<jackson-threetenbp-version>2.6.4</jackson-threetenbp-version>
<jackson-version>2.9.10</jackson-version>
<jackson-threetenbp-version>2.9.10</jackson-threetenbp-version>
</properties>
<dependencies>
<dependency>

View File

@ -26,9 +26,9 @@ import java.util.Objects;
public class CodegenParameter {
public boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
isCookieParam, isBodyParam, hasMore, isContainer,
secondaryParam, isCollectionFormatMulti, isPrimitiveType, isModel;
secondaryParam, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode;
public String baseName, paramName, dataType, datatypeWithEnum, dataFormat,
collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName;
collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style;
public String example; // example value (x-example)
public String jsonSchema;
@ -173,6 +173,7 @@ public class CodegenParameter {
output.isFreeFormObject = this.isFreeFormObject;
output.isListContainer = this.isListContainer;
output.isMapContainer = this.isMapContainer;
output.isExplode = this.isExplode;
return output;
}
@ -247,7 +248,8 @@ public class CodegenParameter {
Objects.equals(maxItems, that.maxItems) &&
Objects.equals(minItems, that.minItems) &&
Objects.equals(uniqueItems, that.uniqueItems) &&
Objects.equals(multipleOf, that.multipleOf);
Objects.equals(multipleOf, that.multipleOf) &&
Objects.equals(isExplode, that.isExplode);
}
@Override
@ -316,7 +318,8 @@ public class CodegenParameter {
maxItems,
minItems,
uniqueItems,
multipleOf);
multipleOf,
isExplode);
}
@java.lang.Override
@ -386,6 +389,7 @@ public class CodegenParameter {
", minItems=" + minItems +
", uniqueItems=" + uniqueItems +
", multipleOf=" + multipleOf +
", isExplode=" + isExplode +
'}';
}
}

View File

@ -17,7 +17,6 @@
package org.openapitools.codegen;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.CaseFormat;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache;
@ -1894,7 +1893,7 @@ public class DefaultCodegen implements CodegenConfig {
}
}
if(composed.getRequired() != null) {
if (composed.getRequired() != null) {
required.addAll(composed.getRequired());
}
addVars(m, unaliasPropertySchema(properties), required, unaliasPropertySchema(allProperties), allRequired);
@ -2003,7 +2002,7 @@ public class DefaultCodegen implements CodegenConfig {
addProperties(properties, required, component);
}
if(schema.getRequired() != null) {
if (schema.getRequired() != null) {
required.addAll(schema.getRequired());
}
@ -2509,15 +2508,15 @@ public class DefaultCodegen implements CodegenConfig {
/**
* Set op's returnBaseType, returnType, examples etc.
*
* @param operation endpoint Operation
* @param schemas a map of the schemas in the openapi spec
* @param op endpoint CodegenOperation
* @param operation endpoint Operation
* @param schemas a map of the schemas in the openapi spec
* @param op endpoint CodegenOperation
* @param methodResponse the default ApiResponse for the endpoint
*/
protected void handleMethodResponse(Operation operation,
Map<String, Schema> schemas,
CodegenOperation op,
ApiResponse methodResponse) {
Map<String, Schema> schemas,
CodegenOperation op,
ApiResponse methodResponse) {
Schema responseSchema = ModelUtils.unaliasSchema(this.openAPI, ModelUtils.getSchemaFromResponse(methodResponse));
if (responseSchema != null) {
@ -3099,7 +3098,15 @@ public class DefaultCodegen implements CodegenConfig {
// set default value
codegenParameter.defaultValue = toDefaultValue(parameterSchema);
// TDOO revise collectionFormat
if (parameter.getStyle() != null) {
codegenParameter.style = parameter.getStyle().toString();
}
// the default value is false
// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#user-content-parameterexplode
codegenParameter.isExplode = parameter.getExplode() == null ? false : parameter.getExplode();
// TODO revise collectionFormat
String collectionFormat = null;
if (ModelUtils.isArraySchema(parameterSchema)) { // for array parameter
final ArraySchema arraySchema = (ArraySchema) parameterSchema;
@ -3617,7 +3624,7 @@ public class DefaultCodegen implements CodegenConfig {
co.baseName = tag;
}
private void addParentContainer(CodegenModel model, String name, Schema schema) {
protected void addParentContainer(CodegenModel model, String name, Schema schema) {
final CodegenProperty property = fromProperty(name, schema);
addImport(model, property.complexType);
model.parent = toInstantiationType(schema);
@ -4094,7 +4101,7 @@ public class DefaultCodegen implements CodegenConfig {
*
* @param name string to be sanitize
* @param removeCharRegEx a regex containing all char that will be removed
* @param exceptionList a list of matches which should not be sanitized (i.e expections)
* @param exceptionList a list of matches which should not be sanitized (i.e expections)
* @return sanitized string
*/
@SuppressWarnings("static-method")
@ -4522,8 +4529,8 @@ public class DefaultCodegen implements CodegenConfig {
for (String consume : consumesInfo) {
if (consume != null &&
(consume.toLowerCase(Locale.ROOT).startsWith("application/x-www-form-urlencoded") ||
consume.toLowerCase(Locale.ROOT).startsWith("multipart"))) {
(consume.toLowerCase(Locale.ROOT).startsWith("application/x-www-form-urlencoded") ||
consume.toLowerCase(Locale.ROOT).startsWith("multipart"))) {
return true;
}
}
@ -5015,7 +5022,6 @@ public class DefaultCodegen implements CodegenConfig {
codegenParameter.pattern = codegenProperty.pattern;
if (codegenProperty.complexType != null) {
imports.add(codegenProperty.complexType);
}

View File

@ -109,7 +109,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
"object",
// used as internal variables, can collide with parameter names
"localVarPath", "localVarQueryParams", "localVarCollectionQueryParams",
"localVarHeaderParams", "localVarFormParams", "localVarPostBody",
"localVarHeaderParams", "localVarCookieParams", "localVarFormParams", "localVarPostBody",
"localVarAccepts", "localVarAccept", "localVarContentTypes",
"localVarContentType", "localVarAuthNames", "localReturnType",
"ApiClient", "ApiException", "ApiResponse", "Configuration", "StringUtil",

View File

@ -184,6 +184,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
typeMapping.put("file", "java.io.File");
typeMapping.put("array", "kotlin.Array");
typeMapping.put("list", "kotlin.collections.List");
typeMapping.put("set", "kotlin.collections.Set");
typeMapping.put("map", "kotlin.collections.Map");
typeMapping.put("object", "kotlin.Any");
typeMapping.put("binary", "kotlin.Array<kotlin.Byte>");
@ -697,6 +698,9 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
// TODO: collection type here should be fully qualified namespace to avoid model conflicts
// This supports arrays of arrays.
String arrayType = typeMapping.get("array");
if (Boolean.TRUE.equals(arr.getUniqueItems())) {
arrayType = typeMapping.get("set");
}
StringBuilder instantiationType = new StringBuilder(arrayType);
Schema items = arr.getItems();
String nestedType = getTypeDeclaration(items);

View File

@ -34,6 +34,7 @@ import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
@ -441,12 +442,16 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
String type = null;
if (typeMapping.containsKey(openAPIType)) {
if (ModelUtils.isComposedSchema(p)) {
return openAPIType;
} else if (typeMapping.containsKey(openAPIType)) {
type = typeMapping.get(openAPIType);
if (languageSpecificPrimitives.contains(type))
if (languageSpecificPrimitives.contains(type)) {
return type;
} else
}
} else {
type = openAPIType;
}
return toModelName(type);
}
@ -560,6 +565,20 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
}
}
@Override
protected void addImport(CodegenModel m, String type) {
if (type == null) {
return;
}
String[] parts = type.split("( [|&] )|[<>]");
for (String s : parts) {
if (needToImport(s)) {
m.imports.add(s);
}
}
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// process enum in models
@ -701,11 +720,43 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
@Override
public String toAnyOfName(List<String> names, ComposedSchema composedSchema) {
return String.join(" | ", names);
List<String> types = composedSchema.getAnyOf().stream().map(schema -> {
String schemaType = getSchemaType(schema);
if (ModelUtils.isArraySchema(schema)) {
ArraySchema ap = (ArraySchema) schema;
Schema inner = ap.getItems();
schemaType = schemaType + "<" + getSchemaType(inner) + ">";
}
return schemaType;
}).distinct().collect(Collectors.toList());
return String.join(" | ", types);
}
@Override
public String toOneOfName(List<String> names, ComposedSchema composedSchema) {
return String.join(" | ", names);
List<String> types = composedSchema.getOneOf().stream().map(schema -> {
String schemaType = getSchemaType(schema);
if (ModelUtils.isArraySchema(schema)) {
ArraySchema ap = (ArraySchema) schema;
Schema inner = ap.getItems();
schemaType = schemaType + "<" + getSchemaType(inner) + ">";
}
return schemaType;
}).distinct().collect(Collectors.toList());
return String.join(" | ", types);
}
@Override
public String toAllOfName(List<String> names, ComposedSchema composedSchema) {
List<String> types = composedSchema.getAllOf().stream().map(schema -> {
String schemaType = getSchemaType(schema);
if (ModelUtils.isArraySchema(schema)) {
ArraySchema ap = (ArraySchema) schema;
Schema inner = ap.getItems();
schemaType = schemaType + "<" + getSchemaType(inner) + ">";
}
return schemaType;
}).distinct().collect(Collectors.toList());
return String.join(" & ", types);
}
}

View File

@ -53,6 +53,8 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
protected static int emptyMethodNameCounter = 0;
public static final String CURL_OPTIONS = "curlOptions";
public static final String PROCESS_MARKDOWN = "processMarkdown";
public static final String SCRIPT_NAME = "scriptName";
@ -99,6 +101,26 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
public BashClientCodegen() {
super();
setReservedWordsLowerCase(
Arrays.asList(
"case",
"do",
"done",
"elif",
"else",
"esac",
"fi",
"for",
"function",
"if",
"in",
"select",
"then",
"until",
"while"
)
);
/**
* Set the output folder here
*/
@ -411,9 +433,9 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
/**
* Convert OpenAPI Parameter object to Codegen Parameter object
*
* @param imports set of imports for library/package/module
* @param param OpenAPI parameter object
*
* @return Codegen Parameter object
*/
@Override
@ -749,5 +771,29 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
return camelize(name);
}
@Override
public String toOperationId(String operationId) {
// rename to empty_method_name_1 (e.g.) if method name is empty
if (StringUtils.isEmpty(operationId)) {
operationId = camelize("empty_method_name_" + emptyMethodNameCounter++, true);
LOGGER.warn("Empty method name (operationId) found. Renamed to " + operationId);
return operationId;
}
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(operationId)) {
String newOperationId = underscore("call" + camelize(operationId));
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId);
return newOperationId;
}
// operationId starts with a number
if (operationId.matches("^\\d.*")) {
LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId)));
operationId = "call_" + operationId;
}
return camelize(sanitizeName(operationId), true);
}
}

View File

@ -132,8 +132,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
.put(NET35, ".NET Framework 3.5 compatible")
.put(NET40, ".NET Framework 4.0 compatible")
.put(NET45, ".NET Framework 4.5+ compatible")
.put(NETSTANDARD, ".NET Standard 1.3 compatible")
.put(UWP, "Universal Windows Platform (IMPORTANT: this will be decommissioned and replaced by v5.0)")
.put(NETSTANDARD, ".NET Standard 1.3 compatible (DEPRECATED. Please use `csharp-netcore` generator instead)")
.put(UWP, "Universal Windows Platform (DEPRECATED. Please use `csharp-netcore` generator instead)")
.build();
framework.defaultValue(this.targetFramework);
framework.setEnum(frameworks);
@ -276,6 +276,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
setValidatable(Boolean.FALSE);
setSupportsAsync(Boolean.FALSE);
} else if (NETSTANDARD.equals(this.targetFramework)) {
LOGGER.warn(".NET Standard 1.3 support has been DEPRECATED in this generator. Please use `csharp-netcore` generator instead.");
// TODO: NETSTANDARD here is misrepresenting a PCL v5.0 which supports .NET Framework 4.6+, .NET Core 1.0, and Windows Universal 10.0
additionalProperties.put(MCS_NET_VERSION_KEY, "4.6-api");
if (additionalProperties.containsKey("supportsUWP")) {
@ -293,6 +294,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
//Todo implement it
excludeTests = true;
} else if (UWP.equals(this.targetFramework)) {
LOGGER.warn("UWP support has been DEPRECATED in this generator. Please use `csharp-netcore` generator instead.");
// TODO: NETSTANDARD here is misrepresenting a PCL v5.0 which supports .NET Framework 4.6+, .NET Core 1.0, and Windows Universal 10.0
setTargetFrameworkNuget("uwp");
setSupportsAsync(Boolean.TRUE);
setSupportsUWP(Boolean.TRUE);

View File

@ -81,7 +81,8 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
"is", "library", "new", "null", "operator", "part", "rethrow",
"return", "set", "static", "super", "switch", "sync*", "this",
"throw", "true", "try", "typedef", "var", "void", "while",
"with", "yield", "yield*")
"with", "yield", "yield*", "hide", "interface", "mixin", "on",
"show", "async")
);
languageSpecificPrimitives = new HashSet<String>(
@ -300,6 +301,11 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
name = "model_" + name; // e.g. return => ModelReturn (after camelize)
}
if (name.matches("^\\d.*")) {
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name));
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
}
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);

View File

@ -38,6 +38,7 @@ import java.util.Set;
import io.swagger.v3.oas.models.media.Schema;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class DartDioClientCodegen extends DartClientCodegen {
@ -61,7 +62,6 @@ public class DartDioClientCodegen extends DartClientCodegen {
private static final String SERIALIZATION_JSON = "json";
private boolean nullableFields = true;
private String serialization = SERIALIZATION_JSON;
public DartDioClientCodegen() {
super();
@ -78,8 +78,9 @@ public class DartDioClientCodegen extends DartClientCodegen {
typeMapping.put("file", "Uint8List");
typeMapping.put("binary", "Uint8List");
importMapping.put("BuiltList", "built_collection/built_collection");
importMapping.put("BuiltMap", "built_collection/built_collection");
importMapping.put("BuiltList", "package:built_collection/built_collection.dart");
importMapping.put("BuiltMap", "package:built_collection/built_collection.dart");
importMapping.put("Uint8List", "dart:typed_data");
}
@Override
@ -102,6 +103,32 @@ public class DartDioClientCodegen extends DartClientCodegen {
return super.toDefaultValue(p);
}
@Override
public String escapeReservedWord(String name) {
if (this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@Override
public String toEnumVarName(String name, String datatype) {
if (name.length() == 0) {
return "empty";
}
if ("number".equalsIgnoreCase(datatype) ||
"int".equalsIgnoreCase(datatype)) {
name = "Number" + name;
}
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public void processOpts() {
if (StringUtils.isEmpty(System.getenv("DART_POST_PROCESS_FILE"))) {
@ -182,7 +209,7 @@ public class DartDioClientCodegen extends DartClientCodegen {
modelImports.add(importMapping.get(modelImport));
} else {
if (!modelToIgnore.contains(modelImport.toLowerCase(Locale.ROOT))) {
modelImports.add(pubName + "/model/" + underscore(modelImport));
modelImports.add("package:" + pubName + "/model/" + underscore(modelImport) + ".dart");
}
}
}

View File

@ -19,6 +19,8 @@ package org.openapitools.codegen.languages;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenParameter;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.SupportingFile;
import org.slf4j.Logger;
@ -26,6 +28,8 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class GoServerCodegen extends AbstractGoCodegen {
@ -70,6 +74,15 @@ public class GoServerCodegen extends AbstractGoCodegen {
"controller-api.mustache", // the template to use
".go"); // the extension for each file to write
/*
* Service templates. You can write services for each Api file with the apiTemplateFiles map.
These services are skeletons built to implement the logic of your api using the
expected parameters and response.
*/
apiTemplateFiles.put(
"service.mustache", // the template to use
"_service.go"); // the extension for each file to write
/*
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
@ -142,9 +155,50 @@ public class GoServerCodegen extends AbstractGoCodegen {
supportingFiles.add(new SupportingFile("Dockerfile.mustache", "", "Dockerfile"));
supportingFiles.add(new SupportingFile("routers.mustache", sourceFolder, "routers.go"));
supportingFiles.add(new SupportingFile("logger.mustache", sourceFolder, "logger.go"));
supportingFiles.add(new SupportingFile("api.mustache", sourceFolder, "api.go"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));
}
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
objs = super.postProcessOperationsWithModels(objs, allModels);
@SuppressWarnings("unchecked")
Map<String, Object> objectMap = (Map<String, Object>) objs.get("operations");
@SuppressWarnings("unchecked")
List<CodegenOperation> operations = (List<CodegenOperation>) objectMap.get("operation");
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
if (imports == null)
return objs;
// override imports to only include packages for interface parameters
imports.clear();
boolean addedOptionalImport = false;
boolean addedTimeImport = false;
boolean addedOSImport = false;
boolean addedReflectImport = false;
for (CodegenOperation operation : operations) {
for (CodegenParameter param : operation.allParams) {
// import "os" if the operation uses files
if (!addedOSImport && "*os.File".equals(param.dataType)) {
imports.add(createMapping("import", "os"));
addedOSImport = true;
}
// import "time" if the operation has a required time parameter.
if (param.required) {
if (!addedTimeImport && "time.Time".equals(param.dataType)) {
imports.add(createMapping("import", "time"));
addedTimeImport = true;
}
}
}
}
return objs;
}
@Override
public String apiPackage() {
return sourceFolder;

View File

@ -43,6 +43,10 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
protected String apiVersion = "0.0.1";
private static final Pattern LEADING_UNDERSCORE = Pattern.compile("^_+");
public static final String PROP_SERVE_STATIC = "serveStatic";
public static final String PROP_SERVE_STATIC_DESC = "serve will serve files from the directory 'static'.";
public static final Boolean PROP_SERVE_STATIC_DEFAULT = Boolean.TRUE;
/**
* Configures the type of generator.
*
@ -183,6 +187,15 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC));
cliOptions.add(new CliOption(PROP_SERVE_STATIC, PROP_SERVE_STATIC_DESC).defaultValue(PROP_SERVE_STATIC_DEFAULT.toString()));
}
public void setBooleanProperty(String property, Boolean defaultValue) {
if (additionalProperties.containsKey(property)) {
additionalProperties.put(property, convertPropertyToBoolean(property));
} else {
additionalProperties.put(property, defaultValue);
}
}
@Override
@ -192,6 +205,8 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
if (StringUtils.isEmpty(System.getenv("HASKELL_POST_PROCESS_FILE"))) {
LOGGER.info("Hint: Environment variable HASKELL_POST_PROCESS_FILE not defined so the Haskell code may not be properly formatted. To define it, try 'export HASKELL_POST_PROCESS_FILE=\"$HOME/.local/bin/hfmt -w\"' (Linux/Mac)");
}
setBooleanProperty(PROP_SERVE_STATIC, PROP_SERVE_STATIC_DEFAULT);
}
/**

View File

@ -676,15 +676,17 @@ public class JavaClientCodegen extends AbstractJavaCodegen
var.getVendorExtensions().put("isJacksonOptionalNullable", isOptionalNullable);
}
if (addImports) {
cm.imports.add("JsonNullable");
Map<String, String> itemJsonNullable = new HashMap<String, String>();
itemJsonNullable.put("import", "org.openapitools.jackson.nullable.JsonNullable");
imports.add(itemJsonNullable);
cm.imports.add("NoSuchElementException");
Map<String, String> itemExc = new HashMap<String, String>();
itemExc.put("import", "java.util.NoSuchElementException");
imports.add(itemExc);
Map<String, String> imports2Classnames = new HashMap<String, String>() {{
put("JsonNullable", "org.openapitools.jackson.nullable.JsonNullable");
put("NoSuchElementException", "java.util.NoSuchElementException");
put("JsonIgnore", "com.fasterxml.jackson.annotation.JsonIgnore");
}};
for (Map.Entry<String, String> entry : imports2Classnames.entrySet()) {
cm.imports.add(entry.getKey());
Map<String, String> importsItem = new HashMap<String, String>();
importsItem.put("import", entry.getValue());
imports.add(importsItem);
}
}
}
}

View File

@ -25,6 +25,7 @@ import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static org.openapitools.codegen.utils.StringUtils.camelize;
@ -59,7 +60,7 @@ public class JavaUndertowServerCodegen extends AbstractJavaCodegen {
apiDocTemplateFiles.remove("api_doc.mustache");
if(GlobalSettings.getProperty("swagger.codegen.undertow.apipackage") != null && GlobalSettings.getProperty("openapi.codegen.undertow.apipackage") == null) {
LOGGER.warn("System property 'swagger.codegen.undertow.apipackage' was renamed to 'swagger.codegen.undertow.apipackage'");
LOGGER.warn("System property 'swagger.codegen.undertow.apipackage' was renamed to 'openapi.codegen.undertow.apipackage'");
apiPackage = GlobalSettings.getProperty("swagger.codegen.undertow.apipackage", "org.openapitools.handler");
} else {
apiPackage = GlobalSettings.getProperty("openapi.codegen.undertow.apipackage", "org.openapitools.handler");
@ -100,7 +101,7 @@ public class JavaUndertowServerCodegen extends AbstractJavaCodegen {
// keep the yaml in config folder for framework validation.
supportingFiles.add(new SupportingFile("openapi.mustache", ("src.main.resources.config").replace(".", java.io.File.separator), "openapi.json"));
supportingFiles.add(new SupportingFile("handler.mustache", ("src.main.java.org.openapitools.handler").replace(".", java.io.File.separator), "PathHandlerProvider.java"));
supportingFiles.add(new SupportingFile("handler.mustache", (String.format(Locale.ROOT, "src.main.java.%s", apiPackage)).replace(".", java.io.File.separator), "PathHandlerProvider.java"));
supportingFiles.add(new SupportingFile("service.mustache", ("src.main.resources.META-INF.services").replace(".", java.io.File.separator), "com.networknt.server.HandlerProvider"));
// configuration files

View File

@ -0,0 +1,161 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.media.Schema;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.SupportingFile;
import java.io.File;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class JavaVertXWebServerCodegen extends AbstractJavaCodegen {
protected String resourceFolder = "src/main/resources";
protected String apiVersion = "1.0.0-SNAPSHOT";
public JavaVertXWebServerCodegen() {
super();
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.BETA)
.build();
// set the output folder here
outputFolder = "generated-code" + File.separator + "java-vertx-web";
modelTemplateFiles.clear();
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.clear();
apiTemplateFiles.put("api.mustache", ".java");
apiTemplateFiles.put("apiImpl.mustache", "Impl.java");
apiTemplateFiles.put("apiHandler.mustache", "Handler.java");
embeddedTemplateDir = templateDir = "JavaVertXWebServer";
invokerPackage = "org.openapitools.vertxweb.server";
apiPackage = invokerPackage + ".api";
modelPackage = invokerPackage + ".model";
artifactId = "openapi-java-vertx-web-server";
artifactVersion = apiVersion;
this.setDateLibrary("java8");
// clioOptions default redifinition need to be updated
updateOption(CodegenConstants.ARTIFACT_ID, this.getArtifactId());
updateOption(CodegenConstants.ARTIFACT_VERSION, this.getArtifactVersion());
updateOption(CodegenConstants.API_PACKAGE, apiPackage);
updateOption(CodegenConstants.MODEL_PACKAGE, modelPackage);
updateOption(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
updateOption(this.DATE_LIBRARY, this.getDateLibrary());
// Override type mapping
typeMapping.put("file", "FileUpload");
}
public CodegenType getTag() {
return CodegenType.SERVER;
}
public String getName() {
return "java-vertx-web";
}
public String getHelp() {
return "Generates a Java Vert.x-Web Server (beta).";
}
@Override
public void processOpts() {
super.processOpts();
apiTestTemplateFiles.clear();
importMapping.remove("JsonCreator");
importMapping.remove("com.fasterxml.jackson.annotation.JsonProperty");
importMapping.put("JsonInclude", "com.fasterxml.jackson.annotation.JsonInclude");
importMapping.put("JsonProperty", "com.fasterxml.jackson.annotation.JsonProperty");
importMapping.put("JsonValue", "com.fasterxml.jackson.annotation.JsonValue");
importMapping.put("FileUpload", "io.vertx.ext.web.FileUpload");
modelDocTemplateFiles.clear();
apiDocTemplateFiles.clear();
String sourcePackageFolder = sourceFolder + File.separator + invokerPackage.replace(".", File.separator);
supportingFiles.clear();
supportingFiles.add(new SupportingFile("supportFiles/openapi.mustache", resourceFolder, "openapi.yaml"));
supportingFiles.add(new SupportingFile("supportFiles/HttpServerVerticle.mustache", sourcePackageFolder, "HttpServerVerticle.java"));
supportingFiles.add(new SupportingFile("supportFiles/MainVerticle.mustache", sourcePackageFolder, "MainVerticle.java"));
supportingFiles.add(new SupportingFile("supportFiles/ApiResponse.mustache", sourcePackageFolder, "ApiResponse.java"));
supportingFiles.add(new SupportingFile("supportFiles/ApiException.mustache", sourcePackageFolder, "ApiException.java"));
supportingFiles.add(new SupportingFile("supportFiles/ParameterCast.mustache", sourcePackageFolder, "ParameterCast.java"));
supportingFiles.add(new SupportingFile("supportFiles/pom.mustache", "", "pom.xml"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
if (!model.isEnum) {
model.imports.add("JsonInclude");
model.imports.add("JsonProperty");
if (model.hasEnums) {
model.imports.add("JsonValue");
}
}
}
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
Map<String, Object> newObjs = super.postProcessOperationsWithModels(objs, allModels);
Map<String, Object> operations = (Map<String, Object>) newObjs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
operation.httpMethod = operation.httpMethod.toLowerCase(Locale.ROOT);
if (operation.returnType == null) {
operation.returnType = "Void";
}
}
}
return newObjs;
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
generateYAMLSpecFile(objs);
return super.postProcessSupportingFileData(objs);
}
@Override
public CodegenModel fromModel(String name, Schema model) {
CodegenModel codegenModel = super.fromModel(name, model);
codegenModel.imports.remove("ApiModel");
codegenModel.imports.remove("ApiModelProperty");
return codegenModel;
}
}

View File

@ -19,7 +19,10 @@ package org.openapitools.codegen.languages;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenParameter;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.SupportingFile;
@ -38,6 +41,8 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
public static final String DATE_LIBRARY = "dateLibrary";
public static final String COLLECTION_TYPE = "collectionType";
protected static final String VENDOR_EXTENSION_BASE_NAME_LITERAL = "x-base-name-literal";
protected String dateLibrary = DateLibrary.JAVA8.value;
protected String collectionType = CollectionType.ARRAY.value;
@ -188,29 +193,48 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
// multiplatform default includes
defaultIncludes.add("io.ktor.client.request.forms.InputProvider");
defaultIncludes.add(packageName + ".infrastructure.Base64ByteArray");
defaultIncludes.add(packageName + ".infrastructure.OctetByteArray");
// multiplatform type mapping
typeMapping.put("number", "kotlin.Double");
typeMapping.put("file", "InputProvider");
typeMapping.put("file", "OctetByteArray");
typeMapping.put("binary", "OctetByteArray");
typeMapping.put("ByteArray", "Base64ByteArray");
typeMapping.put("object", "kotlin.String"); // kotlin.Any not serializable
// multiplatform import mapping
importMapping.put("BigDecimal", "kotlin.Double");
importMapping.put("UUID", "kotlin.String");
importMapping.put("URI", "kotlin.String");
importMapping.put("InputProvider", "io.ktor.client.request.forms.InputProvider");
importMapping.put("File", "io.ktor.client.request.forms.InputProvider");
importMapping.put("File", packageName + ".infrastructure.OctetByteArray");
importMapping.put("Timestamp", "kotlin.String");
importMapping.put("LocalDateTime", "kotlin.String");
importMapping.put("LocalDate", "kotlin.String");
importMapping.put("LocalTime", "kotlin.String");
importMapping.put("Base64ByteArray", packageName + ".infrastructure.Base64ByteArray");
importMapping.put("OctetByteArray", packageName + ".infrastructure.OctetByteArray");
// multiplatform specific supporting files
supportingFiles.add(new SupportingFile("infrastructure/Base64ByteArray.kt.mustache", infrastructureFolder, "Base64ByteArray.kt"));
supportingFiles.add(new SupportingFile("infrastructure/Bytes.kt.mustache", infrastructureFolder, "Bytes.kt"));
supportingFiles.add(new SupportingFile("infrastructure/HttpResponse.kt.mustache", infrastructureFolder, "HttpResponse.kt"));
supportingFiles.add(new SupportingFile("infrastructure/OctetByteArray.kt.mustache", infrastructureFolder, "OctetByteArray.kt"));
// multiplatform specific auth
final String authFolder = (sourceFolder + File.separator + packageName + File.separator + "auth").replace(".", "/");
supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.kt.mustache", authFolder, "ApiKeyAuth.kt"));
supportingFiles.add(new SupportingFile("auth/Authentication.kt.mustache", authFolder, "Authentication.kt"));
supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.kt.mustache", authFolder, "HttpBasicAuth.kt"));
supportingFiles.add(new SupportingFile("auth/HttpBearerAuth.kt.mustache", authFolder, "HttpBearerAuth.kt"));
supportingFiles.add(new SupportingFile("auth/OAuth.kt.mustache", authFolder, "OAuth.kt"));
// multiplatform specific testing files
supportingFiles.add(new SupportingFile("commonTest/coroutine.mustache", "src/commonTest/kotlin/util", "Coroutine.kt"));
supportingFiles.add(new SupportingFile("iosTest/coroutine.mustache", "src/iosTest/kotlin/util", "Coroutine.kt"));
supportingFiles.add(new SupportingFile("jvmTest/coroutine.mustache", "src/jvmTest/kotlin/util", "Coroutine.kt"));
supportingFiles.add(new SupportingFile("commonTest/Coroutine.kt.mustache", "src/commonTest/kotlin/util", "Coroutine.kt"));
supportingFiles.add(new SupportingFile("iosTest/Coroutine.kt.mustache", "src/iosTest/kotlin/util", "Coroutine.kt"));
supportingFiles.add(new SupportingFile("jsTest/Coroutine.kt.mustache", "src/jsTest/kotlin/util", "Coroutine.kt"));
supportingFiles.add(new SupportingFile("jvmTest/Coroutine.kt.mustache", "src/jvmTest/kotlin/util", "Coroutine.kt"));
// gradle wrapper supporting files
supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew"));
@ -253,6 +277,31 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
return getLibrary() != null && (getLibrary().contains(JVM_OKHTTP4) || getLibrary().contains(JVM_OKHTTP3));
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
Map<String, Object> objects = super.postProcessModels(objs);
@SuppressWarnings("unchecked") List<Object> models = (List<Object>) objs.get("models");
for (Object model : models) {
@SuppressWarnings("unchecked") Map<String, Object> mo = (Map<String, Object>) model;
CodegenModel cm = (CodegenModel) mo.get("model");
// escape the variable base name for use as a string literal
if (cm.requiredVars != null) {
for (CodegenProperty var : cm.requiredVars) {
var.vendorExtensions.put(VENDOR_EXTENSION_BASE_NAME_LITERAL, var.baseName.replace("$", "\\$"));
}
}
if (cm.optionalVars != null) {
for (CodegenProperty var : cm.optionalVars) {
var.vendorExtensions.put(VENDOR_EXTENSION_BASE_NAME_LITERAL, var.baseName.replace("$", "\\$"));
}
}
}
return objects;
}
@Override
@SuppressWarnings("unchecked")
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
@ -261,11 +310,22 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
// set multipart against all relevant operations
if (operation.hasConsumes == Boolean.TRUE) {
if (isMultipartType(operation.consumes)) {
operation.isMultipart = Boolean.TRUE;
}
}
// modify the data type of binary form parameters to a more friendly type for multiplatform builds
if (MULTIPLATFORM.equals(getLibrary()) && operation.allParams != null) {
for (CodegenParameter param : operation.allParams) {
if (param.dataFormat != null && param.dataFormat.equals("binary")) {
param.baseType = param.dataType = "io.ktor.client.request.forms.InputProvider";
}
}
}
}
}
return operations;

View File

@ -0,0 +1,149 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.*;
public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(PhpSlim4ServerCodegen.class);
public static final String PSR7_IMPLEMENTATION = "psr7Implementation";
protected String psr7Implementation = "slim-psr7";
protected List<Map<String, String>> composerPackages = new ArrayList<Map<String, String>>();
protected List<Map<String, String>> composerDevPackages = new ArrayList<Map<String, String>>();
public PhpSlim4ServerCodegen() {
super();
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.STABLE)
.build();
outputFolder = "generated-code" + File.separator + "slim4";
embeddedTemplateDir = templateDir = "php-slim4-server";
// override cliOptions from AbstractPhpCodegen
updateOption(AbstractPhpCodegen.VARIABLE_NAMING_CONVENTION, "camelCase");
// Slim 4 can use any PSR-7 implementation
// https://www.slimframework.com/docs/v4/concepts/value-objects.html
CliOption psr7Option = new CliOption(PSR7_IMPLEMENTATION,
"Slim 4 provides its own PSR-7 implementation so that it works out of the box. However, you are free to replace Slims default PSR-7 objects with a third-party implementation. Ref: https://www.slimframework.com/docs/v4/concepts/value-objects.html");
psr7Option.addEnum("slim-psr7", "Slim PSR-7 Message implementation")
.addEnum("nyholm-psr7", "Nyholm PSR-7 Message implementation")
.addEnum("guzzle-psr7", "Guzzle PSR-7 Message implementation")
.addEnum("zend-diactoros", "Zend Diactoros PSR-7 Message implementation")
.setDefault("slim-psr7");
cliOptions.add(psr7Option);
}
@Override
public String getName() {
return "php-slim4";
}
@Override
public String getHelp() {
return "Generates a PHP Slim 4 Framework server library.";
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(PSR7_IMPLEMENTATION)) {
this.setPsr7Implementation((String) additionalProperties.get(PSR7_IMPLEMENTATION));
}
// reset implementation flags
additionalProperties.put("isSlimPsr7", Boolean.FALSE);
additionalProperties.put("isNyholmPsr7", Boolean.FALSE);
additionalProperties.put("isGuzzlePsr7", Boolean.FALSE);
additionalProperties.put("isZendDiactoros", Boolean.FALSE);
// set specific PSR-7 implementation flag
switch (getPsr7Implementation()) {
case "slim-psr7":
additionalProperties.put("isSlimPsr7", Boolean.TRUE);
break;
case "nyholm-psr7":
additionalProperties.put("isNyholmPsr7", Boolean.TRUE);
break;
case "guzzle-psr7":
additionalProperties.put("isGuzzlePsr7", Boolean.TRUE);
break;
case "zend-diactoros":
additionalProperties.put("isZendDiactoros", Boolean.TRUE);
break;
default:
LOGGER.warn("\"" + getPsr7Implementation() + "\" is invalid \"psr7Implementation\" codegen option. Default \"slim-psr7\" used instead.");
additionalProperties.put("isSlimPsr7", Boolean.TRUE);
}
// Slim 4 doesn't parse JSON body anymore we need to add suggested middleware
// ref: https://www.slimframework.com/docs/v4/objects/request.html#the-request-body
supportingFiles.add(new SupportingFile("json_body_parser_middleware.mustache", toSrcPath(invokerPackage + "\\Middleware", srcBasePath), "JsonBodyParserMiddleware.php"));
}
/**
* Set PSR-7 implementation package.
* Ref: https://www.slimframework.com/docs/v4/concepts/value-objects.html
*
* @param psr7Implementation PSR-7 implementation package
*/
public void setPsr7Implementation(String psr7Implementation) {
switch (psr7Implementation) {
case "slim-psr7":
case "nyholm-psr7":
case "guzzle-psr7":
case "zend-diactoros":
this.psr7Implementation = psr7Implementation;
break;
default:
this.psr7Implementation = "slim-psr7";
LOGGER.warn("\"" + (String) psr7Implementation + "\" is invalid \"psr7Implementation\" argument. Default \"slim-psr7\" used instead.");
}
}
/**
* Returns PSR-7 implementation package.
*
* @return PSR-7 implementation package
*/
public String getPsr7Implementation() {
return this.psr7Implementation;
}
}

View File

@ -23,6 +23,8 @@ import io.swagger.v3.oas.models.servers.Server;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -46,6 +48,10 @@ public class PhpSlimServerCodegen extends AbstractPhpCodegen {
public PhpSlimServerCodegen() {
super();
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.DEPRECATED)
.build();
// clear import mapping (from default generator) as slim does not use it
// at the moment
importMapping.clear();
@ -85,12 +91,12 @@ public class PhpSlimServerCodegen extends AbstractPhpCodegen {
@Override
public String getName() {
return "php-slim";
return "php-slim-deprecated";
}
@Override
public String getHelp() {
return "Generates a PHP Slim Framework server library.";
return "Generates a PHP Slim Framework server library. IMPORTANT NOTE: this generator (Slim 3.x) is no longer actively maintained so please use 'php-slim4' generator instead.";
}
@Override

View File

@ -50,6 +50,9 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
public PythonClientExperimentalCodegen() {
super();
// this may set datatype right for additional properties
instantiationTypes.put("map", "dict");
apiTemplateFiles.remove("api.mustache");
apiTemplateFiles.put("python-experimental/api.mustache", ".py");
@ -76,6 +79,20 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
supportingFiles.add(new SupportingFile("python-experimental/model_utils.mustache", packagePath(), "model_utils.py"));
Boolean generateSourceCodeOnly = false;
if (additionalProperties.containsKey(CodegenConstants.SOURCECODEONLY_GENERATION)) {
generateSourceCodeOnly = Boolean.valueOf(additionalProperties.get(CodegenConstants.SOURCECODEONLY_GENERATION).toString());
}
if (!generateSourceCodeOnly) {
supportingFiles.remove(new SupportingFile("setup.mustache", "", "setup.py"));
supportingFiles.add(new SupportingFile("python-experimental/setup.mustache", "", "setup.py"));
supportingFiles.remove(new SupportingFile("requirements.mustache", "", "requirements.txt"));
supportingFiles.add(new SupportingFile("python-experimental/requirements.mustache", "", "requirements.txt"));
supportingFiles.remove(new SupportingFile("test-requirements.mustache", "", "test-requirements.txt"));
supportingFiles.add(new SupportingFile("python-experimental/test-requirements.mustache", "", "test-requirements.txt"));
}
// default this to true so the python ModelSimple models will be generated
ModelUtils.setGenerateAliasAsModel(true);
LOGGER.info(CodegenConstants.GENERATE_ALIAS_AS_MODEL + " is hard coded to true in this generator. Alias models will only be generated if they contain validations or enums");
@ -196,10 +213,20 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
}
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
// add regex information to property
postProcessPattern(property.pattern, property.vendorExtensions);
public void addModelImport(Map<String, Object> objs, CodegenModel cm, String otherModelName) {
// adds the absolute path to otherModelName as an import in CodegenModel cm
HashMap referencedModel = (HashMap) objs.get(otherModelName);
if (referencedModel == null) {
// this happens with a model where type=string and format=number which is a non-standard format
return;
}
ArrayList myModel = (ArrayList) referencedModel.get("models");
HashMap modelData = (HashMap) myModel.get(0);
String importPath = (String) modelData.get("importPath");
// only add importPath to parameters if it isn't in importPaths
if (!cm.imports.contains(importPath)) {
cm.imports.add(importPath);
}
}
// override with any special post-processing for all models
@ -213,6 +240,41 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
List<Map<String, Object>> models = (List<Map<String, Object>>) inner.get("models");
for (Map<String, Object> mo : models) {
CodegenModel cm = (CodegenModel) mo.get("model");
// fix the imports that each model has, change them to absolute
// imports
// clear out imports so we will only include full path imports
cm.imports.clear();
CodegenDiscriminator discriminator = cm.discriminator;
if (discriminator != null) {
Set<CodegenDiscriminator.MappedModel> mappedModels = discriminator.getMappedModels();
for (CodegenDiscriminator.MappedModel mappedModel : mappedModels) {
String otherModelName = mappedModel.getModelName();
addModelImport(objs, cm, otherModelName);
}
}
ArrayList<List<CodegenProperty>> listOfLists= new ArrayList<List<CodegenProperty>>();
listOfLists.add(cm.allVars);
listOfLists.add(cm.requiredVars);
listOfLists.add(cm.optionalVars);
listOfLists.add(cm.vars);
for (List<CodegenProperty> varList : listOfLists) {
for (CodegenProperty cp : varList) {
String otherModelName = null;
if (cp.complexType != null) {
otherModelName = cp.complexType;
}
if (cp.mostInnerItems != null) {
if (cp.mostInnerItems.complexType != null) {
otherModelName = cp.mostInnerItems.complexType;
}
}
if (otherModelName != null) {
addModelImport(objs, cm, otherModelName);
}
}
}
Schema modelSchema = ModelUtils.getSchema(this.openAPI, cm.name);
CodegenProperty modelProperty = fromProperty("value", modelSchema);
if (cm.isEnum || cm.isAlias) {
@ -491,11 +553,6 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
}
}
@Override
public void postProcessParameter(CodegenParameter parameter) {
postProcessPattern(parameter.pattern, parameter.vendorExtensions);
}
/**
* Convert OAS Model object to Codegen Model object
*
@ -559,11 +616,7 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
}
}
// return all models which don't need their properties connected to non-object models
if (propertyToModelName.isEmpty()) {
return result;
}
// set regex values, before it was only done on model.vars
// fix all property references to non-object models, make those properties non-primitive and
// set their dataType and complexType to the model name, so documentation will refer to the correct model
ArrayList<List<CodegenProperty>> listOfLists = new ArrayList<List<CodegenProperty>>();
@ -575,6 +628,9 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
listOfLists.add(result.readWriteVars);
for (List<CodegenProperty> cpList : listOfLists) {
for (CodegenProperty cp : cpList) {
// set regex values, before it was only done on model.vars
postProcessModelProperty(result, cp);
// fix references to non-object models
if (!propertyToModelName.containsKey(cp.name)) {
continue;
}
@ -589,4 +645,147 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
return result;
}
/**
* Output the type declaration of the property
*
* @param schema property schema
* @return a string presentation of the property type
*/
public String getSimpleTypeDeclaration(Schema schema) {
String oasType = getSchemaType(schema);
if (typeMapping.containsKey(oasType)) {
return typeMapping.get(oasType);
}
return oasType;
}
public String getTypeString(Schema p, String prefix, String suffix) {
// this is used to set dataType, which defines a python tuple of classes
String fullSuffix = suffix;
if (")".equals(suffix)) {
fullSuffix = "," + suffix;
}
if (ModelUtils.isNullable(p)) {
fullSuffix = ", none_type" + suffix;
}
if (ModelUtils.isFreeFormObject(p) && ModelUtils.getAdditionalProperties(p) == null) {
return prefix + "bool, date, datetime, dict, float, int, list, str" + fullSuffix;
}
if (ModelUtils.isMapSchema(p)) {
Schema inner = ModelUtils.getAdditionalProperties(p);
return prefix + "{str: " + getTypeString(inner, "(", ")") + "}" + fullSuffix;
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return prefix + "[" + getTypeString(inner, "", "") + "]" + fullSuffix;
}
String baseType = getSimpleTypeDeclaration(p);
if (ModelUtils.isFileSchema(p)) {
baseType = "file_type";
}
return prefix + baseType + fullSuffix;
}
/**
* Output the type declaration of a given name
*
* @param p property schema
* @return a string presentation of the type
*/
@Override
public String getTypeDeclaration(Schema p) {
// this is used to set dataType, which defines a python tuple of classes
// in Python we will wrap this in () to make it a tuple but here we
// will omit the parens so the generated documentaion will not include
// them
return getTypeString(p, "", "");
}
@Override
public String toInstantiationType(Schema property) {
if (ModelUtils.isArraySchema(property) || ModelUtils.isMapSchema(property) || property.getAdditionalProperties() != null) {
return getSchemaType(property);
}
return super.toInstantiationType(property);
}
@Override
protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) {
Schema addProps = ModelUtils.getAdditionalProperties(schema);
if (addProps != null && addProps.get$ref() == null) {
// if AdditionalProperties exists and is an inline definition, get its datatype and store it in m.parent
String typeString = getTypeDeclaration(addProps);
codegenModel.additionalPropertiesType = typeString;
} else {
addParentContainer(codegenModel, codegenModel.name, schema);
}
}
@Override
public void setParameterExampleValue(CodegenParameter p) {
// we have a custom version of this function so we can set the file
// type example value
String example;
if (p.defaultValue == null) {
example = p.example;
} else {
p.example = p.defaultValue;
return;
}
String type = p.baseType;
if (type == null) {
type = p.dataType;
}
if ("String".equalsIgnoreCase(type) || "str".equalsIgnoreCase(type)) {
if (example == null) {
example = p.paramName + "_example";
}
example = "'" + escapeText(example) + "'";
} else if ("Integer".equals(type) || "int".equals(type)) {
if (example == null) {
example = "56";
}
} else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) {
if (example == null) {
example = "3.4";
}
} else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) {
if (example == null) {
example = "True";
}
} else if ("file".equalsIgnoreCase(type)) {
if (example == null) {
example = "/path/to/file";
}
example = "open('"+example+"', 'rb')";
} else if ("Date".equalsIgnoreCase(type)) {
if (example == null) {
example = "2013-10-20";
}
example = "'" + escapeText(example) + "'";
} else if ("DateTime".equalsIgnoreCase(type)) {
if (example == null) {
example = "2013-10-20T19:20:30+01:00";
}
example = "'" + escapeText(example) + "'";
} else if (!languageSpecificPrimitives.contains(type)) {
// type is a model class, e.g. User
example = this.packageName + "." + type + "()";
} else {
LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue");
}
if (example == null) {
example = "None";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
example = "[" + example + "]";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
example = "{'key': " + example + "}";
}
p.example = example;
}
}

View File

@ -35,7 +35,6 @@ import java.util.regex.Pattern;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class Swift4Codegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(Swift4Codegen.class);
@ -388,6 +387,9 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("Cartfile.mustache",
"",
"Cartfile"));
supportingFiles.add(new SupportingFile("Package.swift.mustache",
"",
"Package.swift"));
supportingFiles.add(new SupportingFile("APIHelper.mustache",
sourceFolder,
"APIHelper.swift"));

View File

@ -36,14 +36,18 @@ import static org.openapitools.codegen.utils.StringUtils.*;
public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptAngularClientCodegen.class);
private static String CLASS_NAME_PREFIX_PATTERN = "^[a-zA-Z0-9]*$";
private static String CLASS_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9]*$";
private static String FILE_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9.-]*$";
private static final String DEFAULT_IMPORT_PREFIX = "./";
public static final String NPM_REPOSITORY = "npmRepository";
public static final String WITH_INTERFACES = "withInterfaces";
public static final String TAGGED_UNIONS = "taggedUnions";
public static final String NG_VERSION = "ngVersion";
public static final String PROVIDED_IN_ROOT = "providedInRoot";
public static final String API_MODULE_PREFIX = "apiModulePrefix";
public static final String SERVICE_SUFFIX = "serviceSuffix";
public static final String SERVICE_FILE_SUFFIX = "serviceFileSuffix";
public static final String MODEL_SUFFIX = "modelSuffix";
@ -89,6 +93,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
"Use this property to provide Injectables in root (it is only valid in angular version greater or equal to 6.0.0).",
false));
this.cliOptions.add(new CliOption(NG_VERSION, "The version of Angular.").defaultValue(this.ngVersion));
this.cliOptions.add(new CliOption(API_MODULE_PREFIX, "The prefix of the generated ApiModule."));
this.cliOptions.add(new CliOption(SERVICE_SUFFIX, "The suffix of the generated service.").defaultValue(this.serviceSuffix));
this.cliOptions.add(new CliOption(SERVICE_FILE_SUFFIX, "The suffix of the file of the generated service (service<suffix>.ts).").defaultValue(this.serviceFileSuffix));
this.cliOptions.add(new CliOption(MODEL_SUFFIX, "The suffix of the generated model."));
@ -183,6 +188,14 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
if (!ngVersion.atLeast("4.3.0")) {
supportingFiles.add(new SupportingFile("rxjs-operators.mustache", getIndexDirectory(), "rxjs-operators.ts"));
}
if (additionalProperties.containsKey(API_MODULE_PREFIX)) {
String apiModulePrefix = additionalProperties.get(API_MODULE_PREFIX).toString();
validateClassPrefixArgument("ApiModule", apiModulePrefix);
additionalProperties.put("apiModuleClassName", apiModulePrefix + "ApiModule");
} else {
additionalProperties.put("apiModuleClassName", "ApiModule");
}
if (additionalProperties.containsKey(SERVICE_SUFFIX)) {
serviceSuffix = additionalProperties.get(SERVICE_SUFFIX).toString();
validateClassSuffixArgument("Service", serviceSuffix);
@ -319,16 +332,6 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
}
@Override
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
if (isLanguagePrimitive(openAPIType) || isLanguageGenericType(openAPIType)) {
return openAPIType;
}
applyLocalTypeMapping(openAPIType);
return openAPIType;
}
private String applyLocalTypeMapping(String type) {
if (typeMapping.containsKey(type)) {
type = typeMapping.get(type);
@ -336,19 +339,6 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
return type;
}
private boolean isLanguagePrimitive(String type) {
return languageSpecificPrimitives.contains(type);
}
private boolean isLanguageGenericType(String type) {
for (String genericType : languageGenericTypes) {
if (type.startsWith(genericType + "<")) {
return true;
}
}
return false;
}
@Override
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
@ -505,7 +495,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
}
/**
* Parse imports
* Parse imports
*/
private Set<String> parseImports(CodegenModel cm) {
Set<String> newImports = new HashSet<String>();
@ -556,17 +546,26 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
@Override
public String toApiImport(String name) {
if (importMapping.containsKey(name)) {
return importMapping.get(name);
}
return apiPackage() + "/" + toApiFilename(name);
}
@Override
public String toModelFilename(String name) {
return this.convertUsingFileNamingConvention(this.sanitizeName(name)) + modelFileSuffix;
if (importMapping.containsKey(name)) {
return importMapping.get(name);
}
return DEFAULT_IMPORT_PREFIX + this.convertUsingFileNamingConvention(this.sanitizeName(name)) + modelFileSuffix;
}
@Override
public String toModelImport(String name) {
return modelPackage() + "/" + toModelFilename(name);
if (importMapping.containsKey(name)) {
return importMapping.get(name);
}
return modelPackage() + "/" + toModelFilename(name).substring(DEFAULT_IMPORT_PREFIX.length());
}
public String getNpmRepository() {
@ -623,6 +622,21 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
}
}
/**
* Validates that the given string value only contains alpha numeric characters.
* Throws an IllegalArgumentException, if the string contains any other characters.
*
* @param argument The name of the argument being validated. This is only used for displaying an error message.
* @param value The value that is being validated.
*/
private void validateClassPrefixArgument(String argument, String value) {
if (!value.matches(CLASS_NAME_PREFIX_PATTERN)) {
throw new IllegalArgumentException(
String.format(Locale.ROOT, "%s class prefix only allows alphanumeric characters.", argument)
);
}
}
/**
* Validates that the given string value only contains alpha numeric characters.
* Throws an IllegalArgumentException, if the string contains any other characters.
@ -669,4 +683,3 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
}
}

View File

@ -107,7 +107,6 @@ public class TypeScriptAxiosClientCodegen extends AbstractTypeScriptClientCodege
supportingFiles.add(new SupportingFile("baseApi.mustache", "", "base.ts"));
supportingFiles.add(new SupportingFile("api.mustache", "", "api.ts"));
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.ts"));
supportingFiles.add(new SupportingFile("custom.d.mustache", "", "custom.d.ts"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));

View File

@ -90,6 +90,7 @@ public class ModelUtils {
* @return schemas a list of used schemas
*/
public static List<String> getAllUsedSchemas(OpenAPI openAPI) {
Map<String, List<String>> childrenMap = getChildrenMap(openAPI);
List<String> allUsedSchemas = new ArrayList<String>();
visitOpenAPI(openAPI, (s, t) -> {
if (s.get$ref() != null) {
@ -97,6 +98,13 @@ public class ModelUtils {
if (!allUsedSchemas.contains(ref)) {
allUsedSchemas.add(ref);
}
if (childrenMap.containsKey(ref)) {
for (String child : childrenMap.get(ref)) {
if (!allUsedSchemas.contains(child)) {
allUsedSchemas.add(child);
}
}
}
}
});
return allUsedSchemas;
@ -109,6 +117,7 @@ public class ModelUtils {
* @return schemas a list of unused schemas
*/
public static List<String> getUnusedSchemas(OpenAPI openAPI) {
Map<String, List<String>> childrenMap = getChildrenMap(openAPI);
List<String> unusedSchemas = new ArrayList<String>();
Map<String, Schema> schemas = getSchemas(openAPI);
@ -116,7 +125,11 @@ public class ModelUtils {
visitOpenAPI(openAPI, (s, t) -> {
if (s.get$ref() != null) {
unusedSchemas.remove(getSimpleRef(s.get$ref()));
String ref = getSimpleRef(s.get$ref());
unusedSchemas.remove(ref);
if (childrenMap.containsKey(ref)) {
unusedSchemas.removeAll(childrenMap.get(ref));
}
}
});
return unusedSchemas;
@ -859,6 +872,18 @@ public class ModelUtils {
return null;
}
public static Map<String, List<String>> getChildrenMap(OpenAPI openAPI) {
Map<String, Schema> allSchemas = getSchemas(openAPI);
Map<String, List<Entry<String, Schema>>> groupedByParent = allSchemas.entrySet().stream()
.filter(entry -> isComposedSchema(entry.getValue()))
.collect(Collectors.groupingBy(entry -> getParentName((ComposedSchema) entry.getValue(), allSchemas)));
return groupedByParent.entrySet().stream()
.collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue().stream().map(e -> e.getKey()).collect(Collectors.toList())));
}
/**
* Get the interfaces from the schema (composed)
*

View File

@ -29,6 +29,7 @@ import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.file.FileDataBodyPart;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.Response.Status.Family;
import javax.ws.rs.core.MediaType;
@ -60,6 +61,7 @@ import {{invokerPackage}}.auth.OAuth;
{{>generatedAnnotation}}
public class ApiClient {
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private Map<String, String> defaultCookieMap = new HashMap<String, String>();
private String basePath = "{{{basePath}}}";
private boolean debugging = false;
private int connectionTimeout = 0;
@ -239,7 +241,7 @@ public class ApiClient {
/**
* Helper method to set API key value for the first API key authentication.
* @param apiKey API key
* @param apiKey the API key
*/
public void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
@ -250,7 +252,7 @@ public class ApiClient {
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set API key prefix for the first API key authentication.
* @param apiKeyPrefix API key prefix
@ -318,6 +320,18 @@ public class ApiClient {
return this;
}
/**
* Add a default cookie.
*
* @param key The cookie's key
* @param value The cookie's value
* @return API client
*/
public ApiClient addDefaultCookie(String key, String value) {
defaultCookieMap.put(key, value);
return this;
}
/**
* Check that whether debugging is enabled for this API client.
* @return True if debugging is on
@ -652,12 +666,12 @@ public class ApiClient {
return url.toString();
}
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, String> cookieParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
if (body != null && !formParams.isEmpty()) {
throw new ApiException(500, "Cannot have body and form params");
}
updateParamsForAuth(authNames, queryParams, headerParams);
updateParamsForAuth(authNames, queryParams, headerParams, cookieParams);
final String url = buildUrl(path, queryParams, collectionQueryParams);
Builder builder;
@ -676,6 +690,15 @@ public class ApiClient {
}
}
for (Entry<String, String> keyValue : cookieParams.entrySet()) {
builder = builder.cookie(new Cookie(keyValue.getKey(), keyValue.getValue()));
}
for (Map.Entry<String,String> keyValue : defaultCookieMap.entrySet()) {
if (!cookieParams.containsKey(keyValue.getKey())) {
builder = builder.cookie(new Cookie(keyValue.getKey(), keyValue.getValue()));
}
}
ClientResponse response = null;
if ("GET".equals(method)) {
@ -706,6 +729,7 @@ public class ApiClient {
* @param collectionQueryParams The collection query parameters
* @param body The request body object - if it is not binary, otherwise null
* @param headerParams The header parameters
* @param cookieParams The cookie parameters
* @param formParams The form parameters
* @param accept The request's Accept header
* @param contentType The request's Content-Type header
@ -714,9 +738,9 @@ public class ApiClient {
* @return The response body in type of string
* @throws ApiException API exception
*/
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, String> cookieParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
ClientResponse response = getAPIResponse(path, method, queryParams, collectionQueryParams, body, headerParams, formParams, accept, contentType, authNames);
ClientResponse response = getAPIResponse(path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames);
statusCode = response.getStatusInfo().getStatusCode();
responseHeaders = response.getHeaders();
@ -753,12 +777,13 @@ public class ApiClient {
* @param authNames The authentications to apply
* @param queryParams Query parameters
* @param headerParams Header parameters
* @param cookieParams Cookie parameters
*/
private void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) {
private void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams) {
for (String authName : authNames) {
Authentication auth = authentications.get(authName);
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
}
}

View File

@ -5,12 +5,12 @@ import com.fasterxml.jackson.core.JsonTokenId;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.datatype.threetenbp.DateTimeUtils;
import com.fasterxml.jackson.datatype.threetenbp.DecimalUtils;
import com.fasterxml.jackson.datatype.threetenbp.deser.ThreeTenDateTimeDeserializerBase;
import com.fasterxml.jackson.datatype.threetenbp.function.BiFunction;
import com.fasterxml.jackson.datatype.threetenbp.function.Function;
import org.threeten.bp.DateTimeException;
import org.threeten.bp.DateTimeUtils;
import org.threeten.bp.Instant;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZoneId;
@ -205,7 +205,7 @@ public class CustomInstantDeserializer<T extends Temporal>
private ZoneId getZone(DeserializationContext context) {
// Instants are always in UTC, so don't waste compute cycles
return (_valueClass == Instant.class) ? null : DateTimeUtils.timeZoneToZoneId(context.getTimeZone());
return (_valueClass == Instant.class) ? null : DateTimeUtils.toZoneId(context.getTimeZone());
}
private static class FromIntegerArguments {

View File

@ -89,11 +89,14 @@ public class {{{classname}}}Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("{{{basePath}}}");
{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}}
{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
// Configure HTTP basic authorization: {{{name}}}
HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}");
{{{name}}}.setUsername("YOUR USERNAME");
{{{name}}}.setPassword("YOUR PASSWORD");{{/isBasic}}{{#isApiKey}}
{{{name}}}.setPassword("YOUR PASSWORD");{{/isBasicBasic}}{{#isBasicBearer}}
// Configure HTTP bearer authorization: {{{name}}}
HttpBearerAuth {{{name}}} = (HttpBearerAuth) defaultClient.getAuthentication("{{{name}}}");
{{{name}}}.setBearerToken("BEARER TOKEN");{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}}
// Configure API key authorization: {{{name}}}
ApiKeyAuth {{{name}}} = (ApiKeyAuth) defaultClient.getAuthentication("{{{name}}}");
{{{name}}}.setApiKey("YOUR API KEY");

View File

@ -79,6 +79,7 @@ public class {{classname}} {
{{javaUtilPrefix}}List<Pair> localVarQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();
{{javaUtilPrefix}}List<Pair> localVarCollectionQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();
{{javaUtilPrefix}}Map<String, String> localVarHeaderParams = new {{javaUtilPrefix}}HashMap<String, String>();
{{javaUtilPrefix}}Map<String, String> localVarCookieParams = new {{javaUtilPrefix}}HashMap<String, String>();
{{javaUtilPrefix}}Map<String, Object> localVarFormParams = new {{javaUtilPrefix}}HashMap<String, Object>();
{{#queryParams}}
@ -89,6 +90,10 @@ public class {{classname}} {
localVarHeaderParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));
{{/headerParams}}
{{#cookieParams}}if ({{paramName}} != null)
localVarCookieParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));
{{/cookieParams}}
{{#formParams}}if ({{paramName}} != null)
localVarFormParams.put("{{baseName}}", {{paramName}});
{{/formParams}}
@ -107,9 +112,9 @@ public class {{classname}} {
{{#returnType}}
GenericType<{{{returnType}}}> localVarReturnType = new GenericType<{{{returnType}}}>() {};
return apiClient.invokeAPI(localVarPath, "{{httpMethod}}", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
return apiClient.invokeAPI(localVarPath, "{{httpMethod}}", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
{{/returnType}}{{^returnType}}
apiClient.invokeAPI(localVarPath, "{{httpMethod}}", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null);
apiClient.invokeAPI(localVarPath, "{{httpMethod}}", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null);
{{/returnType}}
}
{{/operation}}

View File

@ -36,11 +36,14 @@ public class Example {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("{{{basePath}}}");
{{#hasAuthMethods}}
{{#authMethods}}{{#isBasic}}
{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
// Configure HTTP basic authorization: {{{name}}}
HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}");
{{{name}}}.setUsername("YOUR USERNAME");
{{{name}}}.setPassword("YOUR PASSWORD");{{/isBasic}}{{#isApiKey}}
{{{name}}}.setPassword("YOUR PASSWORD");{{/isBasicBasic}}{{#isBasicBearer}}
// Configure HTTP bearer authorization: {{{name}}}
HttpBearerAuth {{{name}}} = (HttpBearerAuth) defaultClient.getAuthentication("{{{name}}}");
{{{name}}}.setBearerToken("BEARER TOKEN");{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}}
// Configure API key authorization: {{{name}}}
ApiKeyAuth {{{name}}} = (ApiKeyAuth) defaultClient.getAuthentication("{{{name}}}");
{{{name}}}.setApiKey("YOUR API KEY");

View File

@ -45,7 +45,7 @@ public class ApiKeyAuth implements Authentication {
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams) {
if (apiKey == null) {
return;
}
@ -59,6 +59,8 @@ public class ApiKeyAuth implements Authentication {
queryParams.add(new Pair(paramName, value));
} else if ("header".equals(location)) {
headerParams.put(paramName, value);
} else if ("cookie".equals(location)) {
cookieParams.put(paramName, value);
}
}
}

View File

@ -13,6 +13,7 @@ public interface Authentication {
*
* @param queryParams List of query parameters
* @param headerParams Map of header parameters
* @param cookieParams Map of cookie parameters
*/
void applyToParams(List<Pair> queryParams, Map<String, String> headerParams);
void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams);
}

View File

@ -41,7 +41,7 @@ public class HttpBasicAuth implements Authentication {
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams) {
if (username == null && password == null) {
return;
}

View File

@ -35,7 +35,7 @@ public class HttpBearerAuth implements Authentication {
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams) {
if(bearerToken == null) {
return;
}

View File

@ -20,7 +20,7 @@ public class OAuth implements Authentication {
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams) {
if (accessToken != null) {
headerParams.put("Authorization", "Bearer " + accessToken);
}

View File

@ -136,8 +136,8 @@ if(hasProperty('target') && target == 'android') {
ext {
swagger_annotations_version = "1.5.22"
jackson_version = "{{^threetenbp}}2.9.10{{/threetenbp}}{{#threetenbp}}2.6.4{{/threetenbp}}"
jackson_databind_version = "{{^threetenbp}}2.9.10{{/threetenbp}}{{#threetenbp}}2.6.4{{/threetenbp}}"
jackson_version = "2.9.10"
jackson_databind_version = "2.9.10"
jackson_databind_nullable_version = "0.2.0"
jersey_version = "1.19.4"
jodatime_version = "2.9.9"

View File

@ -70,7 +70,7 @@ public class ApiClient {
{{/isBasicBasic}}
{{/isBasic}}
{{#isApiKey}}
auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");
auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}");
{{/isApiKey}}
{{#isOAuth}}
auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");

View File

@ -36,6 +36,8 @@ public class ApiKeyAuth implements RequestInterceptor {
template.query(paramName, apiKey);
} else if ("header".equals(location)) {
template.header(paramName, apiKey);
} else if ("cookie".equals(location)) {
template.header("Cookie", String.format("%s=%s", paramName, apiKey));
}
}
}

View File

@ -121,10 +121,10 @@ if(hasProperty('target') && target == 'android') {
ext {
swagger_annotations_version = "1.5.22"
jackson_version = "2.9.10"
jackson_databind_version = "2.9.10"
jackson_databind_version = "2.9.10.1"
jackson_databind_nullable_version = "0.2.0"
{{#threetenbp}}
threepane_version = "2.6.4"
jackson_threetenbp_version = "2.9.10"
{{/threetenbp}}
feign_version = "{{#useFeign10}}10.2.3{{/useFeign10}}{{^useFeign10}}9.7.0{{/useFeign10}}"
feign_form_version = "2.1.0"
@ -150,7 +150,7 @@ dependencies {
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"
{{/java8}}
{{#threetenbp}}
compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$threepane_version"
compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$jackson_threetenbp_version"
{{/threetenbp}}
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
compile "com.brsanthu:migbase64:2.2"

View File

@ -16,9 +16,9 @@ lazy val root = (project in file(".")).
"io.github.openfeign.form" % "feign-form" % "2.1.0" % "compile",
"com.fasterxml.jackson.core" % "jackson-core" % "2.9.10" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.9.10" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.9.10" % "compile",
"com.fasterxml.jackson.datatype" % "jackson-datatype-{{^java8}}joda{{/java8}}{{#java8}}jsr310{{/java8}}" % "2.9.9" % "compile",
"com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.6.4" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.9.10.1" % "compile",
"com.fasterxml.jackson.datatype" % "jackson-datatype-{{^java8}}joda{{/java8}}{{#java8}}jsr310{{/java8}}" % "2.9.10" % "compile",
"com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.9.10" % "compile",
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile",
"com.brsanthu" % "migbase64" % "2.2" % "compile",
"junit" % "junit" % "4.12" % "test",

View File

@ -316,9 +316,9 @@
<feign-form-version>2.1.0</feign-form-version>
<jackson-version>2.9.10</jackson-version>
<jackson-databind-nullable-version>0.2.0</jackson-databind-nullable-version>
<jackson-databind-version>2.9.10</jackson-databind-version>
<jackson-databind-version>2.9.10.1</jackson-databind-version>
{{#threetenbp}}
<jackson-threetenbp-version>2.6.4</jackson-threetenbp-version>
<jackson-threetenbp-version>2.9.10</jackson-threetenbp-version>
{{/threetenbp}}
<junit-version>4.12</junit-version>
<maven-plugin-version>1.0.0</maven-plugin-version>

View File

@ -128,7 +128,7 @@ ext {
jodatime_version = "2.9.9"
junit_version = "4.12"
{{#threetenbp}}
jackson_threeten_version = "2.6.4"
jackson_threeten_version = "2.9.10"
{{/threetenbp}}
}

View File

@ -16,16 +16,16 @@ lazy val root = (project in file(".")).
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.9.10" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.9.10" % "compile",
{{#withXml}}
"com.fasterxml.jackson.dataformat" % "jackson-dataformat-xml" % "2.9.9" % "compile",
"com.fasterxml.jackson.dataformat" % "jackson-dataformat-xml" % "2.9.10" % "compile",
{{/withXml}}
{{#joda}}
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.9" % "compile",
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.10" % "compile",
{{/joda}}
{{#java8}}
"com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.9.9" % "compile",
"com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.9.10" % "compile",
{{/java8}}
{{#threetenbp}}
"com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.6.4" % "compile",
"com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.9.10" % "compile",
{{/threetenbp}}
"junit" % "junit" % "4.12" % "test",
"com.novocode" % "junit-interface" % "0.10" % "test"

View File

@ -313,7 +313,7 @@
<jodatime-version>2.9.9</jodatime-version>
{{/joda}}
{{#threetenbp}}
<jackson-threetenbp-version>2.6.4</jackson-threetenbp-version>
<jackson-threetenbp-version>2.9.10</jackson-threetenbp-version>
{{/threetenbp}}
<maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version>

View File

@ -62,6 +62,7 @@ import {{invokerPackage}}.auth.OAuth;
{{>generatedAnnotation}}
public class ApiClient {
protected Map<String, String> defaultHeaderMap = new HashMap<String, String>();
protected Map<String, String> defaultCookieMap = new HashMap<String, String>();
protected String basePath = "{{{basePath}}}";
protected boolean debugging = false;
protected int connectionTimeout = 0;
@ -246,6 +247,18 @@ public class ApiClient {
return this;
}
/**
* Add a default cookie.
*
* @param key The cookie's key
* @param value The cookie's value
* @return API client
*/
public ApiClient addDefaultCookie(String key, String value) {
defaultCookieMap.put(key, value);
return this;
}
/**
* Check that whether debugging is enabled for this API client.
* @return True if debugging is switched on
@ -316,7 +329,7 @@ public class ApiClient {
public int getReadTimeout() {
return readTimeout;
}
/**
* Set the read timeout (in milliseconds).
* A value of 0 means no timeout, otherwise values must be between 1 and
@ -662,6 +675,7 @@ public class ApiClient {
* @param queryParams The query parameters
* @param body The request body object
* @param headerParams The header parameters
* @param cookieParams The cookie parameters
* @param formParams The form parameters
* @param accept The request's Accept header
* @param contentType The request's Content-Type header
@ -670,8 +684,8 @@ public class ApiClient {
* @return The response body in type of string
* @throws ApiException API exception
*/
public <T> ApiResponse<T> invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams);
public <T> ApiResponse<T> invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> cookieParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams, cookieParams);
// Not using `.target(this.basePath).path(path)` below,
// to support (constant) query string in `path`, e.g. "/posts?draft=1"
@ -694,6 +708,13 @@ public class ApiClient {
}
}
for (Entry<String, String> entry : cookieParams.entrySet()) {
String value = entry.getValue();
if (value != null) {
invocationBuilder = invocationBuilder.cookie(entry.getKey(), value);
}
}
for (Entry<String, String> entry : defaultHeaderMap.entrySet()) {
String key = entry.getKey();
if (!headerParams.containsKey(key)) {
@ -819,12 +840,13 @@ public class ApiClient {
* @param authNames The authentications to apply
* @param queryParams List of query parameters
* @param headerParams Map of header parameters
* @param cookieParams Map of cookie parameters
*/
protected void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) {
protected void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams) {
for (String authName : authNames) {
Authentication auth = authentications.get(authName);
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
}
}
}

View File

@ -121,6 +121,7 @@ public class {{classname}} {
// query params
{{javaUtilPrefix}}List<Pair> localVarQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();
{{javaUtilPrefix}}Map<String, String> localVarHeaderParams = new {{javaUtilPrefix}}HashMap<String, String>();
{{javaUtilPrefix}}Map<String, String> localVarCookieParams = new {{javaUtilPrefix}}HashMap<String, String>();
{{javaUtilPrefix}}Map<String, Object> localVarFormParams = new {{javaUtilPrefix}}HashMap<String, Object>();
{{#queryParams}}
@ -131,6 +132,10 @@ public class {{classname}} {
localVarHeaderParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));
{{/headerParams}}
{{#cookieParams}}if ({{paramName}} != null)
localVarCookieParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));
{{/cookieParams}}
{{#formParams}}if ({{paramName}} != null)
localVarFormParams.put("{{baseName}}", {{paramName}});
{{/formParams}}
@ -149,9 +154,9 @@ public class {{classname}} {
{{#returnType}}
GenericType<{{{returnType}}}> localVarReturnType = new GenericType<{{{returnType}}}>() {};
return apiClient.invokeAPI(localVarPath, "{{httpMethod}}", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
return apiClient.invokeAPI(localVarPath, "{{httpMethod}}", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
{{/returnType}}{{^returnType}}
return apiClient.invokeAPI(localVarPath, "{{httpMethod}}", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null);
return apiClient.invokeAPI(localVarPath, "{{httpMethod}}", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null);
{{/returnType}}
}
{{/operation}}

View File

@ -132,7 +132,7 @@ ext {
{{/supportJava6}}
junit_version = "4.12"
{{#threetenbp}}
threetenbp_version = "2.6.4"
threetenbp_version = "2.9.10"
{{/threetenbp}}
}

View File

@ -17,13 +17,13 @@ lazy val root = (project in file(".")).
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.9.10" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.9.10" % "compile",
{{#joda}}
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.9" % "compile",
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.10" % "compile",
{{/joda}}
{{#java8}}
"com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.9.9" % "compile",
"com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.9.10" % "compile",
{{/java8}}
{{#threetenbp}}
"com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.6.4" % "compile",
"com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.9.10" % "compile",
{{/threetenbp}}
{{^java8}}
"com.brsanthu" % "migbase64" % "2.2",

View File

@ -364,7 +364,7 @@
<jackson-databind-version>2.9.10</jackson-databind-version>
<jackson-databind-nullable-version>0.2.0</jackson-databind-nullable-version>
{{#threetenbp}}
<threetenbp-version>2.6.4</threetenbp-version>
<threetenbp-version>2.9.10</threetenbp-version>
{{/threetenbp}}
<maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version>

View File

@ -4,6 +4,7 @@ package {{invokerPackage}};
import okhttp3.*;
import okhttp3.internal.http.HttpMethod;
import okhttp3.internal.tls.OkHostnameVerifier;
import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.logging.HttpLoggingInterceptor.Level;
import okio.BufferedSink;
@ -65,6 +66,7 @@ public class ApiClient {
private String basePath = "{{{basePath}}}";
private boolean debugging = false;
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private Map<String, String> defaultCookieMap = new HashMap<String, String>();
private String tempFolderPath = null;
private Map<String, Authentication> authentications;
@ -92,7 +94,7 @@ public class ApiClient {
// Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{^isBasicBasic}}
authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}"));{{/isBasicBasic}}{{/isBasic}}{{#isApiKey}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
@ -442,6 +444,18 @@ public class ApiClient {
return this;
}
/**
* Add a default cookie.
*
* @param key The cookie's key
* @param value The cookie's value
* @return ApiClient
*/
public ApiClient addDefaultCookie(String key, String value) {
defaultCookieMap.put(key, value);
return this;
}
/**
* Check that whether debugging is enabled for this API client.
*
@ -1069,14 +1083,15 @@ public class ApiClient {
* @param collectionQueryParams The collection query parameters
* @param body The request body object
* @param headerParams The header parameters
* @param cookieParams The cookie parameters
* @param formParams The form parameters
* @param authNames The authentications to apply
* @param callback Callback for upload/download progress
* @return The HTTP call
* @throws ApiException If fail to serialize the request body object
*/
public Call buildCall(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ApiCallback callback) throws ApiException {
Request request = buildRequest(path, method, queryParams, collectionQueryParams, body, headerParams, formParams, authNames, callback);
public Call buildCall(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, String> cookieParams, Map<String, Object> formParams, String[] authNames, ApiCallback callback) throws ApiException {
Request request = buildRequest(path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback);
return httpClient.newCall(request);
}
@ -1090,18 +1105,20 @@ public class ApiClient {
* @param collectionQueryParams The collection query parameters
* @param body The request body object
* @param headerParams The header parameters
* @param cookieParams The cookie parameters
* @param formParams The form parameters
* @param authNames The authentications to apply
* @param callback Callback for upload/download progress
* @return The HTTP request
* @throws ApiException If fail to serialize the request body object
*/
public Request buildRequest(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ApiCallback callback) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams);
public Request buildRequest(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, String> cookieParams, Map<String, Object> formParams, String[] authNames, ApiCallback callback) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams, cookieParams);
final String url = buildUrl(path, queryParams, collectionQueryParams);
final Request.Builder reqBuilder = new Request.Builder().url(url);
processHeaderParams(headerParams, reqBuilder);
processCookieParams(cookieParams, reqBuilder);
String contentType = (String) headerParams.get("Content-Type");
// ensuring a default content type
@ -1196,8 +1213,8 @@ public class ApiClient {
/**
* Set header parameters to the request builder, including default headers.
*
* @param headerParams Header parameters in the ofrm of Map
* @param reqBuilder Reqeust.Builder
* @param headerParams Header parameters in the form of Map
* @param reqBuilder Request.Builder
*/
public void processHeaderParams(Map<String, String> headerParams, Request.Builder reqBuilder) {
for (Entry<String, String> param : headerParams.entrySet()) {
@ -1210,20 +1227,38 @@ public class ApiClient {
}
}
/**
* Set cookie parameters to the request builder, including default cookies.
*
* @param cookieParams Cookie parameters in the form of Map
* @param reqBuilder Request.Builder
*/
public void processCookieParams(Map<String, String> cookieParams, Request.Builder reqBuilder) {
for (Entry<String, String> param : cookieParams.entrySet()) {
reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue()));
}
for (Entry<String, String> param : defaultCookieMap.entrySet()) {
if (!cookieParams.containsKey(param.getKey())) {
reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue()));
}
}
}
/**
* Update query and header parameters based on authentication settings.
*
* @param authNames The authentications to apply
* @param queryParams List of query parameters
* @param headerParams Map of header parameters
* @param cookieParams Map of cookie parameters
*/
public void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) {
public void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams) {
for (String authName : authNames) {
Authentication auth = authentications.get(authName);
if (auth == null) {
throw new RuntimeException("Authentication undefined: " + authName);
}
auth.applyToParams(queryParams, headerParams);
auth.applyToParams(queryParams, headerParams, cookieParams);
}
}
@ -1306,8 +1341,8 @@ public class ApiClient {
*/
private void applySslSettings() {
try {
TrustManager[] trustManagers = null;
HostnameVerifier hostnameVerifier = null;
TrustManager[] trustManagers;
HostnameVerifier hostnameVerifier;
if (!verifyingSsl) {
trustManagers = new TrustManager[]{
new X509TrustManager() {
@ -1325,40 +1360,42 @@ public class ApiClient {
}
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
} else if (sslCaCert != null) {
char[] password = null; // Any password will work.
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert);
if (certificates.isEmpty()) {
throw new IllegalArgumentException("expected non-empty set of trusted certificates");
}
KeyStore caKeyStore = newEmptyKeyStore(password);
int index = 0;
for (Certificate certificate : certificates) {
String certificateAlias = "ca" + Integer.toString(index++);
caKeyStore.setCertificateEntry(certificateAlias, certificate);
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(caKeyStore);
trustManagers = trustManagerFactory.getTrustManagers();
}
if (keyManagers != null || trustManagers != null) {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, new SecureRandom());
httpClient = httpClient.newBuilder().sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]).build();
} else {
httpClient = httpClient.newBuilder().sslSocketFactory(null, (X509TrustManager) trustManagers[0]).build();
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
if (sslCaCert == null) {
trustManagerFactory.init((KeyStore) null);
} else {
char[] password = null; // Any password will work.
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert);
if (certificates.isEmpty()) {
throw new IllegalArgumentException("expected non-empty set of trusted certificates");
}
KeyStore caKeyStore = newEmptyKeyStore(password);
int index = 0;
for (Certificate certificate : certificates) {
String certificateAlias = "ca" + Integer.toString(index++);
caKeyStore.setCertificateEntry(certificateAlias, certificate);
}
trustManagerFactory.init(caKeyStore);
}
trustManagers = trustManagerFactory.getTrustManagers();
hostnameVerifier = OkHostnameVerifier.INSTANCE;
}
httpClient = httpClient.newBuilder().hostnameVerifier(hostnameVerifier).build();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, new SecureRandom());
httpClient = httpClient.newBuilder()
.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0])
.hostnameVerifier(hostnameVerifier)
.build();
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}

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