diff --git a/bin/configs/go-experimental-extensions-x-auth-id-alias.yaml b/bin/configs/go-experimental-extensions-x-auth-id-alias.yaml new file mode 100644 index 000000000000..517b6fe83d78 --- /dev/null +++ b/bin/configs/go-experimental-extensions-x-auth-id-alias.yaml @@ -0,0 +1,6 @@ +generatorName: go-experimental +outputDir: samples/openapi3/client/extensions/x-auth-id-alias/go-experimental +inputSpec: modules/openapi-generator/src/test/resources/3_0/extensions/x-auth-id-alias.yaml +templateDir: modules/openapi-generator/src/main/resources/go-experimental +additionalProperties: + packageName: x_auth_id_alias diff --git a/bin/configs/java-jersey2-extensions-x-auth-id-alias.yaml b/bin/configs/java-jersey2-extensions-x-auth-id-alias.yaml new file mode 100644 index 000000000000..8de24bd73e5f --- /dev/null +++ b/bin/configs/java-jersey2-extensions-x-auth-id-alias.yaml @@ -0,0 +1,7 @@ +generatorName: java +outputDir: samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8 +library: jersey2 +inputSpec: modules/openapi-generator/src/test/resources/3_0/extensions/x-auth-id-alias.yaml +additionalProperties: + artifactId: openapi3-extensions-x-auth-id-alias-jersey2-java8 + hideGenerationTimestamp: true diff --git a/bin/configs/python-experimental-extensions-x-auth-alias.yaml b/bin/configs/python-experimental-extensions-x-auth-id-alias.yaml similarity index 100% rename from bin/configs/python-experimental-extensions-x-auth-alias.yaml rename to bin/configs/python-experimental-extensions-x-auth-id-alias.yaml diff --git a/modules/openapi-generator/src/main/resources/go-experimental/api.mustache b/modules/openapi-generator/src/main/resources/go-experimental/api.mustache index fb2553be562a..d887bddecc5b 100644 --- a/modules/openapi-generator/src/main/resources/go-experimental/api.mustache +++ b/modules/openapi-generator/src/main/resources/go-experimental/api.mustache @@ -252,13 +252,24 @@ func (r api{{operationId}}Request) Execute() ({{#returnType}}{{{.}}}, {{/returnT if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { - if auth, ok := auth["{{#vendorExtensions.x-auth-id-alias}}{{.}}{{/vendorExtensions.x-auth-id-alias}}{{^vendorExtensions.x-auth-id-alias}}{{name}}{{/vendorExtensions.x-auth-id-alias}}"]; ok { + {{#vendorExtensions.x-auth-id-alias}} + if apiKey, ok := auth["{{.}}"]; ok { var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key + if prefix, ok := auth["{{name}}"]; ok && prefix.Prefix != "" { + key = prefix.Prefix + " " + apiKey.Key } else { - key = auth.Key + key = apiKey.Key } + {{/vendorExtensions.x-auth-id-alias}} + {{^vendorExtensions.x-auth-id-alias}} + if apiKey, ok := auth["{{name}}"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + {{/vendorExtensions.x-auth-id-alias}} {{#isKeyInHeader}} localVarHeaderParams["{{keyParamName}}"] = key {{/isKeyInHeader}} diff --git a/samples/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go b/samples/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go index d126ee0bd33e..85275b451382 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go @@ -97,12 +97,12 @@ func (r apiTestClassnameRequest) Execute() (Client, *_nethttp.Response, error) { if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { - if auth, ok := auth["api_key_query"]; ok { + if apiKey, ok := auth["api_key_query"]; ok { var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key } else { - key = auth.Key + key = apiKey.Key } localVarQueryParams.Add("api_key_query", key) } diff --git a/samples/client/petstore/go-experimental/go-petstore/api_pet.go b/samples/client/petstore/go-experimental/go-petstore/api_pet.go index 7bdcc03c6bff..65b9d66ad2b5 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_pet.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_pet.go @@ -489,12 +489,12 @@ func (r apiGetPetByIdRequest) Execute() (Pet, *_nethttp.Response, error) { if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { - if auth, ok := auth["api_key"]; ok { + if apiKey, ok := auth["api_key"]; ok { var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key } else { - key = auth.Key + key = apiKey.Key } localVarHeaderParams["api_key"] = key } diff --git a/samples/client/petstore/go-experimental/go-petstore/api_store.go b/samples/client/petstore/go-experimental/go-petstore/api_store.go index 8d81867701cf..7780395b95bc 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_store.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_store.go @@ -176,12 +176,12 @@ func (r apiGetInventoryRequest) Execute() (map[string]int32, *_nethttp.Response, if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { - if auth, ok := auth["api_key"]; ok { + if apiKey, ok := auth["api_key"]; ok { var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key } else { - key = auth.Key + key = apiKey.Key } localVarHeaderParams["api_key"] = key } diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.gitignore b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.gitignore new file mode 100644 index 000000000000..daf913b1b347 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.gitignore @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator-ignore b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/FILES b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/FILES new file mode 100644 index 000000000000..6ef83c13ad56 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/FILES @@ -0,0 +1,13 @@ +.gitignore +.travis.yml +README.md +api/openapi.yaml +api_usage.go +client.go +configuration.go +docs/UsageApi.md +git_push.sh +go.mod +go.sum +response.go +utils.go diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/VERSION b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/VERSION new file mode 100644 index 000000000000..d99e7162d01f --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.travis.yml b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.travis.yml new file mode 100644 index 000000000000..f5cb2ce9a5aa --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.travis.yml @@ -0,0 +1,8 @@ +language: go + +install: + - go get -d -v . + +script: + - go build -v ./ + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/README.md b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/README.md new file mode 100644 index 000000000000..6d017a13cd40 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/README.md @@ -0,0 +1,126 @@ +# Go API client for x_auth_id_alias + +This specification shows how to use x-auth-id-alias extension for API keys. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.GoClientExperimentalCodegen + +## Installation + +Install the following dependencies: + +```shell +go get github.com/stretchr/testify/assert +go get golang.org/x/oauth2 +go get golang.org/x/net/context +``` + +Put the package under your project folder and add the following in import: + +```golang +import sw "./x_auth_id_alias" +``` + +## Configuration of Server URL + +Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification. + +### Select Server Configuration + +For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`. + +```golang +ctx := context.WithValue(context.Background(), sw.ContextServerIndex, 1) +``` + +### Templated Server URL + +Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`. + +```golang +ctx := context.WithValue(context.Background(), sw.ContextServerVariables, map[string]string{ + "basePath": "v2", +}) +``` + +Note, enum values are always validated and all unused variables are silently ignored. + +### URLs Configuration per Operation + +Each operation can use different server URL defined using `OperationServers` map in the `Configuration`. +An operation is uniquely identifield by `"{classname}Service.{nickname}"` string. +Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. + +``` +ctx := context.WithValue(context.Background(), sw.ContextOperationServerIndices, map[string]int{ + "{classname}Service.{nickname}": 2, +}) +ctx = context.WithValue(context.Background(), sw.ContextOperationServerVariables, map[string]map[string]string{ + "{classname}Service.{nickname}": { + "port": "8443", + }, +}) +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*UsageApi* | [**AnyKey**](docs/UsageApi.md#anykey) | **Get** /any | Use any API key +*UsageApi* | [**BothKeys**](docs/UsageApi.md#bothkeys) | **Get** /both | Use both API keys +*UsageApi* | [**KeyInHeader**](docs/UsageApi.md#keyinheader) | **Get** /header | Use API key in header +*UsageApi* | [**KeyInQuery**](docs/UsageApi.md#keyinquery) | **Get** /query | Use API key in query + + +## Documentation For Models + + + +## Documentation For Authorization + + + +### api_key + +- **Type**: API key +- **API key parameter name**: X-Api-Key +- **Location**: HTTP header + +Note, each API key must be added to a map of `map[string]APIKey` where the key is: X-Api-Key and passed in as the auth context for each request. + + +### api_key_query + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: URL query string + +Note, each API key must be added to a map of `map[string]APIKey` where the key is: api_key and passed in as the auth context for each request. + + +## Documentation for Utility Methods + +Due to the fact that model structure members are all pointers, this package contains +a number of utility functions to easily obtain pointers to values of basic types. +Each of these functions takes a value of the given basic type and returns a pointer to it: + +* `PtrBool` +* `PtrInt` +* `PtrInt32` +* `PtrInt64` +* `PtrFloat` +* `PtrFloat32` +* `PtrFloat64` +* `PtrString` +* `PtrTime` + +## Author + + + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api/openapi.yaml b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api/openapi.yaml new file mode 100644 index 000000000000..a23135ce523d --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api/openapi.yaml @@ -0,0 +1,114 @@ +openapi: 3.0.0 +info: + description: This specification shows how to use x-auth-id-alias extension for API + keys. + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Extension x-auth-id-alias + version: 1.0.0 +servers: +- description: petstore server + url: http://{server}.swagger.io:{port}/v2 + variables: + server: + default: petstore + enum: + - petstore + - qa-petstore + - dev-petstore + port: + default: "80" + enum: + - "80" + - "8080" +- description: The local server + url: https://localhost:8080/{version} + variables: + version: + default: v2 + enum: + - v1 + - v2 +tags: +- description: Show usage of x-auth-id-alias + name: usage +paths: + /both: + get: + description: Use both API keys + operationId: bothKeys + responses: + "200": + content: + application/json: + schema: + type: object + description: successful operation + security: + - api_key_query: [] + api_key: [] + summary: Use both API keys + tags: + - usage + /any: + get: + description: Use any API key + operationId: anyKey + responses: + "200": + content: + application/json: + schema: + type: object + description: successful operation + security: + - api_key_query: [] + - api_key: [] + summary: Use any API key + tags: + - usage + /query: + get: + description: Use API key in query + operationId: keyInQuery + responses: + "200": + content: + application/json: + schema: + type: object + description: successful operation + security: + - api_key_query: [] + summary: Use API key in query + tags: + - usage + /header: + get: + description: Use API key in header + operationId: keyInHeader + responses: + "200": + content: + application/json: + schema: + type: object + description: successful operation + security: + - api_key: [] + summary: Use API key in header + tags: + - usage +components: + schemas: {} + securitySchemes: + api_key: + in: header + name: X-Api-Key + type: apiKey + api_key_query: + in: query + name: api_key + type: apiKey + x-auth-id-alias: api_key diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api_usage.go b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api_usage.go new file mode 100644 index 000000000000..7bd99eeb9731 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api_usage.go @@ -0,0 +1,490 @@ +/* + * OpenAPI Extension x-auth-id-alias + * + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package x_auth_id_alias + +import ( + _context "context" + _ioutil "io/ioutil" + _nethttp "net/http" + _neturl "net/url" +) + +// Linger please +var ( + _ _context.Context +) + +// UsageApiService UsageApi service +type UsageApiService service + +type apiAnyKeyRequest struct { + ctx _context.Context + apiService *UsageApiService +} + +/* +AnyKey Use any API key +Use any API key + * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). +@return apiAnyKeyRequest +*/ +func (a *UsageApiService) AnyKey(ctx _context.Context) apiAnyKeyRequest { + return apiAnyKeyRequest{ + apiService: a, + ctx: ctx, + } +} + +/* +Execute executes the request +@return map[string]interface{} +*/ +func (r apiAnyKeyRequest) Execute() (map[string]interface{}, *_nethttp.Response, error) { + var ( + localVarHTTPMethod = _nethttp.MethodGet + localVarPostBody interface{} + localVarFormFileName string + localVarFileName string + localVarFileBytes []byte + localVarReturnValue map[string]interface{} + ) + + localBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, "UsageApiService.AnyKey") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/any" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := _neturl.Values{} + localVarFormParams := _neturl.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["api_key"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["X-Api-Key"] = key + } + } + } + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["api_key"]; ok { + var key string + if prefix, ok := auth["api_key_query"]; ok && prefix.Prefix != "" { + key = prefix.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarQueryParams.Add("api_key", key) + } + } + } + req, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := r.apiService.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} +type apiBothKeysRequest struct { + ctx _context.Context + apiService *UsageApiService +} + +/* +BothKeys Use both API keys +Use both API keys + * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). +@return apiBothKeysRequest +*/ +func (a *UsageApiService) BothKeys(ctx _context.Context) apiBothKeysRequest { + return apiBothKeysRequest{ + apiService: a, + ctx: ctx, + } +} + +/* +Execute executes the request +@return map[string]interface{} +*/ +func (r apiBothKeysRequest) Execute() (map[string]interface{}, *_nethttp.Response, error) { + var ( + localVarHTTPMethod = _nethttp.MethodGet + localVarPostBody interface{} + localVarFormFileName string + localVarFileName string + localVarFileBytes []byte + localVarReturnValue map[string]interface{} + ) + + localBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, "UsageApiService.BothKeys") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/both" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := _neturl.Values{} + localVarFormParams := _neturl.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["api_key"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["X-Api-Key"] = key + } + } + } + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["api_key"]; ok { + var key string + if prefix, ok := auth["api_key_query"]; ok && prefix.Prefix != "" { + key = prefix.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarQueryParams.Add("api_key", key) + } + } + } + req, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := r.apiService.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} +type apiKeyInHeaderRequest struct { + ctx _context.Context + apiService *UsageApiService +} + +/* +KeyInHeader Use API key in header +Use API key in header + * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). +@return apiKeyInHeaderRequest +*/ +func (a *UsageApiService) KeyInHeader(ctx _context.Context) apiKeyInHeaderRequest { + return apiKeyInHeaderRequest{ + apiService: a, + ctx: ctx, + } +} + +/* +Execute executes the request +@return map[string]interface{} +*/ +func (r apiKeyInHeaderRequest) Execute() (map[string]interface{}, *_nethttp.Response, error) { + var ( + localVarHTTPMethod = _nethttp.MethodGet + localVarPostBody interface{} + localVarFormFileName string + localVarFileName string + localVarFileBytes []byte + localVarReturnValue map[string]interface{} + ) + + localBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, "UsageApiService.KeyInHeader") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/header" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := _neturl.Values{} + localVarFormParams := _neturl.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["api_key"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["X-Api-Key"] = key + } + } + } + req, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := r.apiService.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} +type apiKeyInQueryRequest struct { + ctx _context.Context + apiService *UsageApiService +} + +/* +KeyInQuery Use API key in query +Use API key in query + * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). +@return apiKeyInQueryRequest +*/ +func (a *UsageApiService) KeyInQuery(ctx _context.Context) apiKeyInQueryRequest { + return apiKeyInQueryRequest{ + apiService: a, + ctx: ctx, + } +} + +/* +Execute executes the request +@return map[string]interface{} +*/ +func (r apiKeyInQueryRequest) Execute() (map[string]interface{}, *_nethttp.Response, error) { + var ( + localVarHTTPMethod = _nethttp.MethodGet + localVarPostBody interface{} + localVarFormFileName string + localVarFileName string + localVarFileBytes []byte + localVarReturnValue map[string]interface{} + ) + + localBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, "UsageApiService.KeyInQuery") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/query" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := _neturl.Values{} + localVarFormParams := _neturl.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["api_key"]; ok { + var key string + if prefix, ok := auth["api_key_query"]; ok && prefix.Prefix != "" { + key = prefix.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarQueryParams.Add("api_key", key) + } + } + } + req, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := r.apiService.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api_usage_test.go b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api_usage_test.go new file mode 100644 index 000000000000..5cd1dd678357 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api_usage_test.go @@ -0,0 +1,120 @@ +package x_auth_id_alias + +import ( + "bytes" + "context" + "fmt" + "io/ioutil" + "net/http" + "testing" +) + +// RoundTripFunc . +type RoundTripFunc func(req *http.Request) *http.Response + +// RoundTrip calls f on given request. +func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req), nil +} + +//NewTestClient returns *http.Client with replaced Transport layer. +func NewTestClient(fn RoundTripFunc) *http.Client { + return &http.Client{ + Transport: RoundTripFunc(fn), + } +} + +type APIRequest interface { + Execute() (map[string]interface{}, *http.Response, error) +} + +func TestAPIKeys(t *testing.T) { + ctx := context.WithValue( + context.Background(), + ContextAPIKeys, + map[string]APIKey{ + "api_key": { + Key: "SECRET_VALUE", + Prefix: "PREFIX", + }, + }, + ) + configuration := NewConfiguration() + apiClient := NewAPIClient(configuration) + + testCases := map[string]struct { + Check func(t *testing.T, req *http.Request) + Request APIRequest + }{ + "AnyKey": { + Check: func(t *testing.T, req *http.Request) { + if req.Header.Get("X-Api-Key") != "PREFIX SECRET_VALUE" { + t.Fatalf("%s != %s", req.Header.Get("X-Api-Key"), "PREFIX SECRET_VALUE") + } + values := req.URL.Query() + if values.Get("api_key") != "SECRET_VALUE" { + t.Fatalf("%s != %s", values.Get("api_key"), "SECRET_VALUE") + } + }, + Request: apiClient.UsageApi.AnyKey(ctx), + }, + "BothKeys": { + Check: func(t *testing.T, req *http.Request) { + if req.Header.Get("X-Api-Key") != "PREFIX SECRET_VALUE" { + t.Fatalf("%s != %s", req.Header.Get("X-Api-Key"), "PREFIX SECRET_VALUE") + } + values := req.URL.Query() + if values.Get("api_key") != "SECRET_VALUE" { + t.Fatalf("%s != %s", values.Get("api_key"), "SECRET_VALUE") + } + }, + Request: apiClient.UsageApi.BothKeys(ctx), + }, + "KeyInHeader": { + Check: func(t *testing.T, req *http.Request) { + if req.Header.Get("X-Api-Key") != "PREFIX SECRET_VALUE" { + t.Fatalf("%s != %s", req.Header.Get("X-Api-Key"), "PREFIX SECRET_VALUE") + } + values := req.URL.Query() + if values.Get("api_key") != "" { + t.Fatalf("%s != %s", values.Get("api_key"), "") + } + }, + Request: apiClient.UsageApi.KeyInHeader(ctx), + }, + "KeyInQuery": { + Check: func(t *testing.T, req *http.Request) { + if req.Header.Get("X-Api-Key") != "" { + t.Fatalf("%s != %s", req.Header.Get("X-Api-Key"), "") + } + values := req.URL.Query() + if values.Get("api_key") != "SECRET_VALUE" { + t.Fatalf("%s != %s", values.Get("api_key"), "SECRET_VALUE") + } + }, + Request: apiClient.UsageApi.KeyInQuery(ctx), + }, + } + + for name, tc := range testCases { + t.Run(name, func(t *testing.T) { + configuration.HTTPClient = NewTestClient(func(req *http.Request) *http.Response { + tc.Check(t, req) + return &http.Response{ + StatusCode: 200, + Body: ioutil.NopCloser(bytes.NewBufferString("")), + Header: make(http.Header), + } + }) + _, httpresp, err := tc.Request.Execute() + if httpresp.StatusCode != 200 { + fmt.Printf("%v != 200", httpresp.StatusCode) + t.FailNow() + } + if err != nil { + fmt.Printf("%v, error: %v", httpresp.Body, err) + t.FailNow() + } + }) + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/client.go b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/client.go new file mode 100644 index 000000000000..30335de6c297 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/client.go @@ -0,0 +1,532 @@ +/* + * OpenAPI Extension x-auth-id-alias + * + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package x_auth_id_alias + +import ( + "bytes" + "context" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "log" + "mime/multipart" + "net/http" + "net/http/httputil" + "net/url" + "os" + "path/filepath" + "reflect" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" + + "golang.org/x/oauth2" +) + +var ( + jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`) + xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`) +) + +// APIClient manages communication with the OpenAPI Extension x-auth-id-alias API v1.0.0 +// In most cases there should be only one, shared, APIClient. +type APIClient struct { + cfg *Configuration + common service // Reuse a single struct instead of allocating one for each service on the heap. + + // API Services + + UsageApi *UsageApiService +} + +type service struct { + client *APIClient +} + +// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +// optionally a custom http.Client to allow for advanced features such as caching. +func NewAPIClient(cfg *Configuration) *APIClient { + if cfg.HTTPClient == nil { + cfg.HTTPClient = http.DefaultClient + } + + c := &APIClient{} + c.cfg = cfg + c.common.client = c + + // API Services + c.UsageApi = (*UsageApiService)(&c.common) + + return c +} + +func atoi(in string) (int, error) { + return strconv.Atoi(in) +} + +// selectHeaderContentType select a content type from the available list. +func selectHeaderContentType(contentTypes []string) string { + if len(contentTypes) == 0 { + return "" + } + if contains(contentTypes, "application/json") { + return "application/json" + } + return contentTypes[0] // use the first content type specified in 'consumes' +} + +// selectHeaderAccept join all accept types and return +func selectHeaderAccept(accepts []string) string { + if len(accepts) == 0 { + return "" + } + + if contains(accepts, "application/json") { + return "application/json" + } + + return strings.Join(accepts, ",") +} + +// contains is a case insenstive match, finding needle in a haystack +func contains(haystack []string, needle string) bool { + for _, a := range haystack { + if strings.ToLower(a) == strings.ToLower(needle) { + return true + } + } + return false +} + +// Verify optional parameters are of the correct type. +func typeCheckParameter(obj interface{}, expected string, name string) error { + // Make sure there is an object. + if obj == nil { + return nil + } + + // Check the type is as expected. + if reflect.TypeOf(obj).String() != expected { + return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) + } + return nil +} + +// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. +func parameterToString(obj interface{}, collectionFormat string) string { + var delimiter string + + switch collectionFormat { + case "pipes": + delimiter = "|" + case "ssv": + delimiter = " " + case "tsv": + delimiter = "\t" + case "csv": + delimiter = "," + } + + if reflect.TypeOf(obj).Kind() == reflect.Slice { + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") + } else if t, ok := obj.(time.Time); ok { + return t.Format(time.RFC3339) + } + + return fmt.Sprintf("%v", obj) +} + +// helper for converting interface{} parameters to json strings +func parameterToJson(obj interface{}) (string, error) { + jsonBuf, err := json.Marshal(obj) + if err != nil { + return "", err + } + return string(jsonBuf), err +} + + +// callAPI do the request. +func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { + if c.cfg.Debug { + dump, err := httputil.DumpRequestOut(request, true) + if err != nil { + return nil, err + } + log.Printf("\n%s\n", string(dump)) + } + + resp, err := c.cfg.HTTPClient.Do(request) + if err != nil { + return resp, err + } + + if c.cfg.Debug { + dump, err := httputil.DumpResponse(resp, true) + if err != nil { + return resp, err + } + log.Printf("\n%s\n", string(dump)) + } + return resp, err +} + +// Allow modification of underlying config for alternate implementations and testing +// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior +func (c *APIClient) GetConfig() *Configuration { + return c.cfg +} + +// prepareRequest build the request +func (c *APIClient) prepareRequest( + ctx context.Context, + path string, method string, + postBody interface{}, + headerParams map[string]string, + queryParams url.Values, + formParams url.Values, + formFileName string, + fileName string, + fileBytes []byte) (localVarRequest *http.Request, err error) { + + var body *bytes.Buffer + + // Detect postBody type and post. + if postBody != nil { + contentType := headerParams["Content-Type"] + if contentType == "" { + contentType = detectContentType(postBody) + headerParams["Content-Type"] = contentType + } + + body, err = setBody(postBody, contentType) + if err != nil { + return nil, err + } + } + + // add form parameters and file if available. + if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if body != nil { + return nil, errors.New("Cannot specify postBody and multipart form at the same time.") + } + body = &bytes.Buffer{} + w := multipart.NewWriter(body) + + for k, v := range formParams { + for _, iv := range v { + if strings.HasPrefix(k, "@") { // file + err = addFile(w, k[1:], iv) + if err != nil { + return nil, err + } + } else { // form value + w.WriteField(k, iv) + } + } + } + if len(fileBytes) > 0 && fileName != "" { + w.Boundary() + //_, fileNm := filepath.Split(fileName) + part, err := w.CreateFormFile(formFileName, filepath.Base(fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(fileBytes) + if err != nil { + return nil, err + } + } + + // Set the Boundary in the Content-Type + headerParams["Content-Type"] = w.FormDataContentType() + + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + w.Close() + } + + if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 { + if body != nil { + return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.") + } + body = &bytes.Buffer{} + body.WriteString(formParams.Encode()) + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + } + + // Setup path and query parameters + url, err := url.Parse(path) + if err != nil { + return nil, err + } + + // Override request host, if applicable + if c.cfg.Host != "" { + url.Host = c.cfg.Host + } + + // Override request scheme, if applicable + if c.cfg.Scheme != "" { + url.Scheme = c.cfg.Scheme + } + + // Adding Query Param + query := url.Query() + for k, v := range queryParams { + for _, iv := range v { + query.Add(k, iv) + } + } + + // Encode the parameters. + url.RawQuery = query.Encode() + + // Generate a new request + if body != nil { + localVarRequest, err = http.NewRequest(method, url.String(), body) + } else { + localVarRequest, err = http.NewRequest(method, url.String(), nil) + } + if err != nil { + return nil, err + } + + // add header parameters, if any + if len(headerParams) > 0 { + headers := http.Header{} + for h, v := range headerParams { + headers.Set(h, v) + } + localVarRequest.Header = headers + } + + // Add the user agent to the request. + localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) + + if ctx != nil { + // add context to the request + localVarRequest = localVarRequest.WithContext(ctx) + + // Walk through any authentication. + + // OAuth2 authentication + if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { + // We were able to grab an oauth2 token from the context + var latestToken *oauth2.Token + if latestToken, err = tok.Token(); err != nil { + return nil, err + } + + latestToken.SetAuthHeader(localVarRequest) + } + + // Basic HTTP Authentication + if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { + localVarRequest.SetBasicAuth(auth.UserName, auth.Password) + } + + // AccessToken Authentication + if auth, ok := ctx.Value(ContextAccessToken).(string); ok { + localVarRequest.Header.Add("Authorization", "Bearer "+auth) + } + } + + for header, value := range c.cfg.DefaultHeader { + localVarRequest.Header.Add(header, value) + } + return localVarRequest, nil +} + +func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { + if len(b) == 0 { + return nil + } + if s, ok := v.(*string); ok { + *s = string(b) + return nil + } + if xmlCheck.MatchString(contentType) { + if err = xml.Unmarshal(b, v); err != nil { + return err + } + return nil + } + if jsonCheck.MatchString(contentType) { + if actualObj, ok := v.(interface{GetActualInstance() interface{}}); ok { // oneOf, anyOf schemas + if unmarshalObj, ok := actualObj.(interface{UnmarshalJSON([]byte) error}); ok { // make sure it has UnmarshalJSON defined + if err = unmarshalObj.UnmarshalJSON(b); err!= nil { + return err + } + } else { + errors.New("Unknown type with GetActualInstance but no unmarshalObj.UnmarshalJSON defined") + } + } else if err = json.Unmarshal(b, v); err != nil { // simple model + return err + } + return nil + } + return errors.New("undefined response type") +} + +// Add a file to the multipart request +func addFile(w *multipart.Writer, fieldName, path string) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + + part, err := w.CreateFormFile(fieldName, filepath.Base(path)) + if err != nil { + return err + } + _, err = io.Copy(part, file) + + return err +} + +// Prevent trying to import "fmt" +func reportError(format string, a ...interface{}) error { + return fmt.Errorf(format, a...) +} + +// Set request body from an interface{} +func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { + if bodyBuf == nil { + bodyBuf = &bytes.Buffer{} + } + + if reader, ok := body.(io.Reader); ok { + _, err = bodyBuf.ReadFrom(reader) + } else if b, ok := body.([]byte); ok { + _, err = bodyBuf.Write(b) + } else if s, ok := body.(string); ok { + _, err = bodyBuf.WriteString(s) + } else if s, ok := body.(*string); ok { + _, err = bodyBuf.WriteString(*s) + } else if jsonCheck.MatchString(contentType) { + err = json.NewEncoder(bodyBuf).Encode(body) + } else if xmlCheck.MatchString(contentType) { + err = xml.NewEncoder(bodyBuf).Encode(body) + } + + if err != nil { + return nil, err + } + + if bodyBuf.Len() == 0 { + err = fmt.Errorf("Invalid body type %s\n", contentType) + return nil, err + } + return bodyBuf, nil +} + +// detectContentType method is used to figure out `Request.Body` content type for request header +func detectContentType(body interface{}) string { + contentType := "text/plain; charset=utf-8" + kind := reflect.TypeOf(body).Kind() + + switch kind { + case reflect.Struct, reflect.Map, reflect.Ptr: + contentType = "application/json; charset=utf-8" + case reflect.String: + contentType = "text/plain; charset=utf-8" + default: + if b, ok := body.([]byte); ok { + contentType = http.DetectContentType(b) + } else if kind == reflect.Slice { + contentType = "application/json; charset=utf-8" + } + } + + return contentType +} + +// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go +type cacheControl map[string]string + +func parseCacheControl(headers http.Header) cacheControl { + cc := cacheControl{} + ccHeader := headers.Get("Cache-Control") + for _, part := range strings.Split(ccHeader, ",") { + part = strings.Trim(part, " ") + if part == "" { + continue + } + if strings.ContainsRune(part, '=') { + keyval := strings.Split(part, "=") + cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") + } else { + cc[part] = "" + } + } + return cc +} + +// CacheExpires helper function to determine remaining time before repeating a request. +func CacheExpires(r *http.Response) time.Time { + // Figure out when the cache expires. + var expires time.Time + now, err := time.Parse(time.RFC1123, r.Header.Get("date")) + if err != nil { + return time.Now() + } + respCacheControl := parseCacheControl(r.Header) + + if maxAge, ok := respCacheControl["max-age"]; ok { + lifetime, err := time.ParseDuration(maxAge + "s") + if err != nil { + expires = now + } else { + expires = now.Add(lifetime) + } + } else { + expiresHeader := r.Header.Get("Expires") + if expiresHeader != "" { + expires, err = time.Parse(time.RFC1123, expiresHeader) + if err != nil { + expires = now + } + } + } + return expires +} + +func strlen(s string) int { + return utf8.RuneCountInString(s) +} + +// GenericOpenAPIError Provides access to the body, error and model on returned errors. +type GenericOpenAPIError struct { + body []byte + error string + model interface{} +} + +// Error returns non-empty string if there was an error. +func (e GenericOpenAPIError) Error() string { + return e.error +} + +// Body returns the raw bytes of the response +func (e GenericOpenAPIError) Body() []byte { + return e.body +} + +// Model returns the unpacked model of the error +func (e GenericOpenAPIError) Model() interface{} { + return e.model +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/configuration.go b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/configuration.go new file mode 100644 index 000000000000..425e8f19c156 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/configuration.go @@ -0,0 +1,262 @@ +/* + * OpenAPI Extension x-auth-id-alias + * + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package x_auth_id_alias + +import ( + "context" + "fmt" + "net/http" + "strings" +) + +// contextKeys are used to identify the type of value in the context. +// Since these are string, it is possible to get a short description of the +// context key for logging and debugging using key.String(). + +type contextKey string + +func (c contextKey) String() string { + return "auth " + string(c) +} + +var ( + // ContextOAuth2 takes an oauth2.TokenSource as authentication for the request. + ContextOAuth2 = contextKey("token") + + // ContextBasicAuth takes BasicAuth as authentication for the request. + ContextBasicAuth = contextKey("basic") + + // ContextAccessToken takes a string oauth2 access token as authentication for the request. + ContextAccessToken = contextKey("accesstoken") + + // ContextAPIKeys takes a string apikey as authentication for the request + ContextAPIKeys = contextKey("apiKeys") + + // ContextHttpSignatureAuth takes HttpSignatureAuth as authentication for the request. + ContextHttpSignatureAuth = contextKey("httpsignature") + + // ContextServerIndex uses a server configuration from the index. + ContextServerIndex = contextKey("serverIndex") + + // ContextOperationServerIndices uses a server configuration from the index mapping. + ContextOperationServerIndices = contextKey("serverOperationIndices") + + // ContextServerVariables overrides a server configuration variables. + ContextServerVariables = contextKey("serverVariables") + + // ContextOperationServerVariables overrides a server configuration variables using operation specific values. + ContextOperationServerVariables = contextKey("serverOperationVariables") +) + +// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth +type BasicAuth struct { + UserName string `json:"userName,omitempty"` + Password string `json:"password,omitempty"` +} + +// APIKey provides API key based authentication to a request passed via context using ContextAPIKey +type APIKey struct { + Key string + Prefix string +} + +// ServerVariable stores the information about a server variable +type ServerVariable struct { + Description string + DefaultValue string + EnumValues []string +} + +// ServerConfiguration stores the information about a server +type ServerConfiguration struct { + URL string + Description string + Variables map[string]ServerVariable +} + +// ServerConfigurations stores multiple ServerConfiguration items +type ServerConfigurations []ServerConfiguration + +// Configuration stores the configuration of the API client +type Configuration struct { + Host string `json:"host,omitempty"` + Scheme string `json:"scheme,omitempty"` + DefaultHeader map[string]string `json:"defaultHeader,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + Debug bool `json:"debug,omitempty"` + Servers ServerConfigurations + OperationServers map[string]ServerConfigurations + HTTPClient *http.Client +} + +// NewConfiguration returns a new Configuration object +func NewConfiguration() *Configuration { + cfg := &Configuration{ + DefaultHeader: make(map[string]string), + UserAgent: "OpenAPI-Generator/1.0.0/go", + Debug: false, + Servers: ServerConfigurations{ + { + URL: "http://{server}.swagger.io:{port}/v2", + Description: "petstore server", + Variables: map[string]ServerVariable{ + "server": ServerVariable{ + Description: "No description provided", + DefaultValue: "petstore", + EnumValues: []string{ + "petstore", + "qa-petstore", + "dev-petstore", + }, + }, + "port": ServerVariable{ + Description: "No description provided", + DefaultValue: "80", + EnumValues: []string{ + "80", + "8080", + }, + }, + }, + }, + { + URL: "https://localhost:8080/{version}", + Description: "The local server", + Variables: map[string]ServerVariable{ + "version": ServerVariable{ + Description: "No description provided", + DefaultValue: "v2", + EnumValues: []string{ + "v1", + "v2", + }, + }, + }, + }, + }, + OperationServers: map[string]ServerConfigurations{ + }, + } + return cfg +} + +// AddDefaultHeader adds a new HTTP header to the default header in the request +func (c *Configuration) AddDefaultHeader(key string, value string) { + c.DefaultHeader[key] = value +} + +// URL formats template on a index using given variables +func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) { + if index < 0 || len(sc) <= index { + return "", fmt.Errorf("Index %v out of range %v", index, len(sc)-1) + } + server := sc[index] + url := server.URL + + // go through variables and replace placeholders + for name, variable := range server.Variables { + if value, ok := variables[name]; ok { + found := bool(len(variable.EnumValues) == 0) + for _, enumValue := range variable.EnumValues { + if value == enumValue { + found = true + } + } + if !found { + return "", fmt.Errorf("The variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues) + } + url = strings.Replace(url, "{"+name+"}", value, -1) + } else { + url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1) + } + } + return url, nil +} + +// ServerURL returns URL based on server settings +func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) { + return c.Servers.URL(index, variables) +} + +func getServerIndex(ctx context.Context) (int, error) { + si := ctx.Value(ContextServerIndex) + if si != nil { + if index, ok := si.(int); ok { + return index, nil + } + return 0, reportError("Invalid type %T should be int", si) + } + return 0, nil +} + +func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) { + osi := ctx.Value(ContextOperationServerIndices) + if osi != nil { + if operationIndices, ok := osi.(map[string]int); !ok { + return 0, reportError("Invalid type %T should be map[string]int", osi) + } else { + index, ok := operationIndices[endpoint] + if ok { + return index, nil + } + } + } + return getServerIndex(ctx) +} + +func getServerVariables(ctx context.Context) (map[string]string, error) { + sv := ctx.Value(ContextServerVariables) + if sv != nil { + if variables, ok := sv.(map[string]string); ok { + return variables, nil + } + return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv) + } + return nil, nil +} + +func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) { + osv := ctx.Value(ContextOperationServerVariables) + if osv != nil { + if operationVariables, ok := osv.(map[string]map[string]string); !ok { + return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv) + } else { + variables, ok := operationVariables[endpoint] + if ok { + return variables, nil + } + } + } + return getServerVariables(ctx) +} + +// ServerURLWithContext returns a new server URL given an endpoint +func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) { + sc, ok := c.OperationServers[endpoint] + if !ok { + sc = c.Servers + } + + if ctx == nil { + return sc.URL(0, nil) + } + + index, err := getServerOperationIndex(ctx, endpoint) + if err != nil { + return "", err + } + + variables, err := getServerOperationVariables(ctx, endpoint) + if err != nil { + return "", err + } + + return sc.URL(index, variables) +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/docs/UsageApi.md b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/docs/UsageApi.md new file mode 100644 index 000000000000..eb6a220249cd --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/docs/UsageApi.md @@ -0,0 +1,256 @@ +# \UsageApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**AnyKey**](UsageApi.md#AnyKey) | **Get** /any | Use any API key +[**BothKeys**](UsageApi.md#BothKeys) | **Get** /both | Use both API keys +[**KeyInHeader**](UsageApi.md#KeyInHeader) | **Get** /header | Use API key in header +[**KeyInQuery**](UsageApi.md#KeyInQuery) | **Get** /query | Use API key in query + + + +## AnyKey + +> map[string]interface{} AnyKey(ctx).Execute() + +Use any API key + + + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "./openapi" +) + +func main() { + + configuration := openapiclient.NewConfiguration() + api_client := openapiclient.NewAPIClient(configuration) + resp, r, err := api_client.UsageApi.AnyKey(context.Background(), ).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UsageApi.AnyKey``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `AnyKey`: map[string]interface{} + fmt.Fprintf(os.Stdout, "Response from `UsageApi.AnyKey`: %v\n", resp) +} +``` + +### Path Parameters + +This endpoint does not need any parameter. + +### Other Parameters + +Other parameters are passed through a pointer to a apiAnyKeyRequest struct via the builder pattern + + +### Return type + +**map[string]interface{}** + +### Authorization + +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + + +## BothKeys + +> map[string]interface{} BothKeys(ctx).Execute() + +Use both API keys + + + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "./openapi" +) + +func main() { + + configuration := openapiclient.NewConfiguration() + api_client := openapiclient.NewAPIClient(configuration) + resp, r, err := api_client.UsageApi.BothKeys(context.Background(), ).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UsageApi.BothKeys``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `BothKeys`: map[string]interface{} + fmt.Fprintf(os.Stdout, "Response from `UsageApi.BothKeys`: %v\n", resp) +} +``` + +### Path Parameters + +This endpoint does not need any parameter. + +### Other Parameters + +Other parameters are passed through a pointer to a apiBothKeysRequest struct via the builder pattern + + +### Return type + +**map[string]interface{}** + +### Authorization + +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + + +## KeyInHeader + +> map[string]interface{} KeyInHeader(ctx).Execute() + +Use API key in header + + + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "./openapi" +) + +func main() { + + configuration := openapiclient.NewConfiguration() + api_client := openapiclient.NewAPIClient(configuration) + resp, r, err := api_client.UsageApi.KeyInHeader(context.Background(), ).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UsageApi.KeyInHeader``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `KeyInHeader`: map[string]interface{} + fmt.Fprintf(os.Stdout, "Response from `UsageApi.KeyInHeader`: %v\n", resp) +} +``` + +### Path Parameters + +This endpoint does not need any parameter. + +### Other Parameters + +Other parameters are passed through a pointer to a apiKeyInHeaderRequest struct via the builder pattern + + +### Return type + +**map[string]interface{}** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + + +## KeyInQuery + +> map[string]interface{} KeyInQuery(ctx).Execute() + +Use API key in query + + + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "./openapi" +) + +func main() { + + configuration := openapiclient.NewConfiguration() + api_client := openapiclient.NewAPIClient(configuration) + resp, r, err := api_client.UsageApi.KeyInQuery(context.Background(), ).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UsageApi.KeyInQuery``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `KeyInQuery`: map[string]interface{} + fmt.Fprintf(os.Stdout, "Response from `UsageApi.KeyInQuery`: %v\n", resp) +} +``` + +### Path Parameters + +This endpoint does not need any parameter. + +### Other Parameters + +Other parameters are passed through a pointer to a apiKeyInQueryRequest struct via the builder pattern + + +### Return type + +**map[string]interface{}** + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/git_push.sh b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/git_push.sh new file mode 100644 index 000000000000..ced3be2b0c7b --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/go.mod b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/go.mod new file mode 100644 index 000000000000..f9811556cc5a --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/go.mod @@ -0,0 +1,7 @@ +module github.com/GIT_USER_ID/GIT_REPO_ID + +go 1.13 + +require ( + golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 +) diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/go.sum b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/go.sum new file mode 100644 index 000000000000..ce55b3c6a08f --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/go.sum @@ -0,0 +1,15 @@ +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/antihax/optional v1.0.0 h1:xK2lYat7ZLaVVcIuj82J8kIro4V6kDe0AUDFboUCwcg= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e h1:bRhVy7zSSasaqNksaRZiA5EEI+Ei4I1nO5Jh72wfHlg= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/response.go b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/response.go new file mode 100644 index 000000000000..f5aa518c3c5d --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/response.go @@ -0,0 +1,46 @@ +/* + * OpenAPI Extension x-auth-id-alias + * + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package x_auth_id_alias + +import ( + "net/http" +) + +// APIResponse stores the API response returned by the server. +type APIResponse struct { + *http.Response `json:"-"` + Message string `json:"message,omitempty"` + // Operation is the name of the OpenAPI operation. + Operation string `json:"operation,omitempty"` + // RequestURL is the request URL. This value is always available, even if the + // embedded *http.Response is nil. + RequestURL string `json:"url,omitempty"` + // Method is the HTTP method used for the request. This value is always + // available, even if the embedded *http.Response is nil. + Method string `json:"method,omitempty"` + // Payload holds the contents of the response body (which may be nil or empty). + // This is provided here as the raw response.Body() reader will have already + // been drained. + Payload []byte `json:"-"` +} + +// NewAPIResponse returns a new APIResonse object. +func NewAPIResponse(r *http.Response) *APIResponse { + + response := &APIResponse{Response: r} + return response +} + +// NewAPIResponseWithError returns a new APIResponse object with the provided error message. +func NewAPIResponseWithError(errorMessage string) *APIResponse { + + response := &APIResponse{Message: errorMessage} + return response +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/utils.go b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/utils.go new file mode 100644 index 000000000000..c6930485543b --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/utils.go @@ -0,0 +1,334 @@ +/* + * OpenAPI Extension x-auth-id-alias + * + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package x_auth_id_alias + +import ( + "encoding/json" + "time" +) + +// PtrBool is a helper routine that returns a pointer to given integer value. +func PtrBool(v bool) *bool { return &v } + +// PtrInt is a helper routine that returns a pointer to given integer value. +func PtrInt(v int) *int { return &v } + +// PtrInt32 is a helper routine that returns a pointer to given integer value. +func PtrInt32(v int32) *int32 { return &v } + +// PtrInt64 is a helper routine that returns a pointer to given integer value. +func PtrInt64(v int64) *int64 { return &v } + +// PtrFloat32 is a helper routine that returns a pointer to given float value. +func PtrFloat32(v float32) *float32 { return &v } + +// PtrFloat64 is a helper routine that returns a pointer to given float value. +func PtrFloat64(v float64) *float64 { return &v } + +// PtrString is a helper routine that returns a pointer to given string value. +func PtrString(v string) *string { return &v } + +// PtrTime is helper routine that returns a pointer to given Time value. +func PtrTime(v time.Time) *time.Time { return &v } + +type NullableBool struct { + value *bool + isSet bool +} + +func (v NullableBool) Get() *bool { + return v.value +} + +func (v *NullableBool) Set(val *bool) { + v.value = val + v.isSet = true +} + +func (v NullableBool) IsSet() bool { + return v.isSet +} + +func (v *NullableBool) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableBool(val *bool) *NullableBool { + return &NullableBool{value: val, isSet: true} +} + +func (v NullableBool) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableBool) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + +type NullableInt struct { + value *int + isSet bool +} + +func (v NullableInt) Get() *int { + return v.value +} + +func (v *NullableInt) Set(val *int) { + v.value = val + v.isSet = true +} + +func (v NullableInt) IsSet() bool { + return v.isSet +} + +func (v *NullableInt) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt(val *int) *NullableInt { + return &NullableInt{value: val, isSet: true} +} + +func (v NullableInt) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + +type NullableInt32 struct { + value *int32 + isSet bool +} + +func (v NullableInt32) Get() *int32 { + return v.value +} + +func (v *NullableInt32) Set(val *int32) { + v.value = val + v.isSet = true +} + +func (v NullableInt32) IsSet() bool { + return v.isSet +} + +func (v *NullableInt32) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt32(val *int32) *NullableInt32 { + return &NullableInt32{value: val, isSet: true} +} + +func (v NullableInt32) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt32) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + +type NullableInt64 struct { + value *int64 + isSet bool +} + +func (v NullableInt64) Get() *int64 { + return v.value +} + +func (v *NullableInt64) Set(val *int64) { + v.value = val + v.isSet = true +} + +func (v NullableInt64) IsSet() bool { + return v.isSet +} + +func (v *NullableInt64) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt64(val *int64) *NullableInt64 { + return &NullableInt64{value: val, isSet: true} +} + +func (v NullableInt64) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt64) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + +type NullableFloat32 struct { + value *float32 + isSet bool +} + +func (v NullableFloat32) Get() *float32 { + return v.value +} + +func (v *NullableFloat32) Set(val *float32) { + v.value = val + v.isSet = true +} + +func (v NullableFloat32) IsSet() bool { + return v.isSet +} + +func (v *NullableFloat32) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFloat32(val *float32) *NullableFloat32 { + return &NullableFloat32{value: val, isSet: true} +} + +func (v NullableFloat32) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFloat32) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + +type NullableFloat64 struct { + value *float64 + isSet bool +} + +func (v NullableFloat64) Get() *float64 { + return v.value +} + +func (v *NullableFloat64) Set(val *float64) { + v.value = val + v.isSet = true +} + +func (v NullableFloat64) IsSet() bool { + return v.isSet +} + +func (v *NullableFloat64) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFloat64(val *float64) *NullableFloat64 { + return &NullableFloat64{value: val, isSet: true} +} + +func (v NullableFloat64) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFloat64) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + +type NullableString struct { + value *string + isSet bool +} + +func (v NullableString) Get() *string { + return v.value +} + +func (v *NullableString) Set(val *string) { + v.value = val + v.isSet = true +} + +func (v NullableString) IsSet() bool { + return v.isSet +} + +func (v *NullableString) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableString(val *string) *NullableString { + return &NullableString{value: val, isSet: true} +} + +func (v NullableString) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableString) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + +type NullableTime struct { + value *time.Time + isSet bool +} + +func (v NullableTime) Get() *time.Time { + return v.value +} + +func (v *NullableTime) Set(val *time.Time) { + v.value = val + v.isSet = true +} + +func (v NullableTime) IsSet() bool { + return v.isSet +} + +func (v *NullableTime) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTime(val *time.Time) *NullableTime { + return &NullableTime{value: val, isSet: true} +} + +func (v NullableTime) MarshalJSON() ([]byte, error) { + return v.value.MarshalJSON() +} + +func (v *NullableTime) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.gitignore b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.gitignore new file mode 100644 index 000000000000..a530464afa1b --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.gitignore @@ -0,0 +1,21 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator-ignore b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/FILES b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/FILES new file mode 100644 index 000000000000..d26aa67445a2 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/FILES @@ -0,0 +1,33 @@ +.gitignore +.travis.yml +README.md +api/openapi.yaml +build.gradle +build.sbt +docs/UsageApi.md +git_push.sh +gradle.properties +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +pom.xml +settings.gradle +src/main/AndroidManifest.xml +src/main/java/org/openapitools/client/ApiClient.java +src/main/java/org/openapitools/client/ApiException.java +src/main/java/org/openapitools/client/ApiResponse.java +src/main/java/org/openapitools/client/Configuration.java +src/main/java/org/openapitools/client/CustomInstantDeserializer.java +src/main/java/org/openapitools/client/JSON.java +src/main/java/org/openapitools/client/Pair.java +src/main/java/org/openapitools/client/RFC3339DateFormat.java +src/main/java/org/openapitools/client/ServerConfiguration.java +src/main/java/org/openapitools/client/ServerVariable.java +src/main/java/org/openapitools/client/StringUtil.java +src/main/java/org/openapitools/client/api/UsageApi.java +src/main/java/org/openapitools/client/auth/ApiKeyAuth.java +src/main/java/org/openapitools/client/auth/Authentication.java +src/main/java/org/openapitools/client/auth/HttpBasicAuth.java +src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/VERSION b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/VERSION new file mode 100644 index 000000000000..d99e7162d01f --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.travis.yml b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.travis.yml new file mode 100644 index 000000000000..e3bdf2af1bea --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.travis.yml @@ -0,0 +1,22 @@ +# +# Generated by OpenAPI Generator: https://openapi-generator.tech +# +# Ref: https://docs.travis-ci.com/user/languages/java/ +# +language: java +jdk: + - openjdk12 + - openjdk11 + - openjdk10 + - openjdk9 + - openjdk8 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + #- mvn test + # test using gradle + - gradle test + # test using sbt + # - sbt test diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/README.md b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/README.md new file mode 100644 index 000000000000..7bf2775d7a8c --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/README.md @@ -0,0 +1,155 @@ +# openapi3-extensions-x-auth-id-alias-jersey2-java8 + +OpenAPI Extension x-auth-id-alias + +- API version: 1.0.0 + +This specification shows how to use x-auth-id-alias extension for API keys. + + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + +## Requirements + +Building the API client library requires: + +1. Java 1.7+ +2. Maven/Gradle + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + org.openapitools + openapi3-extensions-x-auth-id-alias-jersey2-java8 + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "org.openapitools:openapi3-extensions-x-auth-id-alias-jersey2-java8:1.0.0" +``` + +### Others + +At first generate the JAR by executing: + +```shell +mvn clean package +``` + +Then manually install the following JARs: + +- `target/openapi3-extensions-x-auth-id-alias-jersey2-java8-1.0.0.jar` +- `target/lib/*.jar` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +import org.openapitools.client.*; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UsageApi; + +public class UsageApiExample { + + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + // Configure API key authorization: api_key_query + ApiKeyAuth api_key_query = (ApiKeyAuth) defaultClient.getAuthentication("api_key_query"); + api_key_query.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key_query.setApiKeyPrefix("Token"); + + UsageApi apiInstance = new UsageApi(defaultClient); + try { + Object result = apiInstance.anyKey(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UsageApi#anyKey"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*UsageApi* | [**anyKey**](docs/UsageApi.md#anyKey) | **GET** /any | Use any API key +*UsageApi* | [**bothKeys**](docs/UsageApi.md#bothKeys) | **GET** /both | Use both API keys +*UsageApi* | [**keyInHeader**](docs/UsageApi.md#keyInHeader) | **GET** /header | Use API key in header +*UsageApi* | [**keyInQuery**](docs/UsageApi.md#keyInQuery) | **GET** /query | Use API key in query + + +## Documentation for Models + + + +## Documentation for Authorization + +Authentication schemes defined for the API: +### api_key + + +- **Type**: API key +- **API key parameter name**: X-Api-Key +- **Location**: HTTP header + +### api_key_query + + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: URL query string + + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + + + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/api/openapi.yaml b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/api/openapi.yaml new file mode 100644 index 000000000000..1ea9d4a67836 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/api/openapi.yaml @@ -0,0 +1,119 @@ +openapi: 3.0.0 +info: + description: This specification shows how to use x-auth-id-alias extension for API + keys. + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Extension x-auth-id-alias + version: 1.0.0 +servers: +- description: petstore server + url: http://{server}.swagger.io:{port}/v2 + variables: + server: + default: petstore + enum: + - petstore + - qa-petstore + - dev-petstore + port: + default: "80" + enum: + - "80" + - "8080" +- description: The local server + url: https://localhost:8080/{version} + variables: + version: + default: v2 + enum: + - v1 + - v2 +tags: +- description: Show usage of x-auth-id-alias + name: usage +paths: + /both: + get: + description: Use both API keys + operationId: bothKeys + responses: + "200": + content: + application/json: + schema: + type: object + description: successful operation + security: + - api_key_query: [] + api_key: [] + summary: Use both API keys + tags: + - usage + x-accepts: application/json + /any: + get: + description: Use any API key + operationId: anyKey + responses: + "200": + content: + application/json: + schema: + type: object + description: successful operation + security: + - api_key_query: [] + - api_key: [] + summary: Use any API key + tags: + - usage + x-accepts: application/json + /query: + get: + description: Use API key in query + operationId: keyInQuery + responses: + "200": + content: + application/json: + schema: + type: object + description: successful operation + security: + - api_key_query: [] + summary: Use API key in query + tags: + - usage + x-accepts: application/json + /header: + get: + description: Use API key in header + operationId: keyInHeader + responses: + "200": + content: + application/json: + schema: + type: object + description: successful operation + security: + - api_key: [] + summary: Use API key in header + tags: + - usage + x-accepts: application/json +components: + schemas: {} + securitySchemes: + api_key: + in: header + name: X-Api-Key + type: apiKey + api_key_query: + in: query + name: api_key + type: apiKey + x-auth-id-alias: api_key + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/build.gradle b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/build.gradle new file mode 100644 index 000000000000..dcebf9606eef --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/build.gradle @@ -0,0 +1,125 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'org.openapitools' +version = '1.0.0' + +buildscript { + repositories { + maven { url "https://repo1.maven.org/maven2" } + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.3.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 25 + buildToolsVersion '25.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 25 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'openapi3-extensions-x-auth-id-alias-jersey2-java8' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.22" + jackson_version = "2.10.3" + jackson_databind_version = "2.10.4" + jackson_databind_nullable_version = "0.2.1" + jersey_version = "2.27" + junit_version = "4.13" + threetenbp_version = "2.9.10" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "com.google.code.findbugs:jsr305:3.0.2" + compile "org.glassfish.jersey.core:jersey-client:$jersey_version" + compile "org.glassfish.jersey.inject:jersey-hk2:$jersey_version" + compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" + compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version" + compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" + compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$threetenbp_version" + compile "com.brsanthu:migbase64:2.2" + compile 'javax.annotation:javax.annotation-api:1.3.2' + testCompile "junit:junit:$junit_version" +} + +javadoc { + options.tags = [ "http.response.details:a:Http Response Details" ] +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/build.sbt b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/build.sbt new file mode 100644 index 000000000000..358d6dc183a0 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/build.sbt @@ -0,0 +1,26 @@ +lazy val root = (project in file(".")). + settings( + organization := "org.openapitools", + name := "openapi3-extensions-x-auth-id-alias-jersey2-java8", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.22", + "org.glassfish.jersey.core" % "jersey-client" % "2.27", + "org.glassfish.jersey.inject" % "jersey-hk2" % "2.27", + "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.27", + "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.27", + "com.fasterxml.jackson.core" % "jackson-core" % "2.10.4" % "compile", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.4" % "compile", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.4" % "compile", + "com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.9.10" % "compile", + "com.brsanthu" % "migbase64" % "2.2", + "javax.annotation" % "javax.annotation-api" % "1.3.2" % "compile", + "junit" % "junit" % "4.13" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/docs/UsageApi.md b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/docs/UsageApi.md new file mode 100644 index 000000000000..7af13f24d178 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/docs/UsageApi.md @@ -0,0 +1,296 @@ +# UsageApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**anyKey**](UsageApi.md#anyKey) | **GET** /any | Use any API key +[**bothKeys**](UsageApi.md#bothKeys) | **GET** /both | Use both API keys +[**keyInHeader**](UsageApi.md#keyInHeader) | **GET** /header | Use API key in header +[**keyInQuery**](UsageApi.md#keyInQuery) | **GET** /query | Use API key in query + + + +## anyKey + +> Object anyKey() + +Use any API key + +Use any API key + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UsageApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + // Configure API key authorization: api_key_query + ApiKeyAuth api_key_query = (ApiKeyAuth) defaultClient.getAuthentication("api_key_query"); + api_key_query.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key_query.setApiKeyPrefix("Token"); + + UsageApi apiInstance = new UsageApi(defaultClient); + try { + Object result = apiInstance.anyKey(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UsageApi#anyKey"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Object** + +### Authorization + +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## bothKeys + +> Object bothKeys() + +Use both API keys + +Use both API keys + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UsageApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + // Configure API key authorization: api_key_query + ApiKeyAuth api_key_query = (ApiKeyAuth) defaultClient.getAuthentication("api_key_query"); + api_key_query.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key_query.setApiKeyPrefix("Token"); + + UsageApi apiInstance = new UsageApi(defaultClient); + try { + Object result = apiInstance.bothKeys(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UsageApi#bothKeys"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Object** + +### Authorization + +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## keyInHeader + +> Object keyInHeader() + +Use API key in header + +Use API key in header + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UsageApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + UsageApi apiInstance = new UsageApi(defaultClient); + try { + Object result = apiInstance.keyInHeader(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UsageApi#keyInHeader"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Object** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## keyInQuery + +> Object keyInQuery() + +Use API key in query + +Use API key in query + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UsageApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure API key authorization: api_key_query + ApiKeyAuth api_key_query = (ApiKeyAuth) defaultClient.getAuthentication("api_key_query"); + api_key_query.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key_query.setApiKeyPrefix("Token"); + + UsageApi apiInstance = new UsageApi(defaultClient); + try { + Object result = apiInstance.keyInQuery(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UsageApi#keyInQuery"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Object** + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/git_push.sh b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/git_push.sh new file mode 100644 index 000000000000..ced3be2b0c7b --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle.properties b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle.properties new file mode 100644 index 000000000000..05644f0754af --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle/wrapper/gradle-wrapper.jar b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000000..e35d600ab118 Binary files /dev/null and b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle/wrapper/gradle-wrapper.properties b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..94920145f34e --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradlew b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradlew new file mode 100644 index 000000000000..2fe81a7d95e4 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# 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 +# +# https://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. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradlew.bat b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradlew.bat new file mode 100644 index 000000000000..9618d8d9607c --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradlew.bat @@ -0,0 +1,100 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/pom.xml b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/pom.xml new file mode 100644 index 000000000000..4ec080f6d957 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/pom.xml @@ -0,0 +1,309 @@ + + 4.0.0 + org.openapitools + openapi3-extensions-x-auth-id-alias-jersey2-java8 + jar + openapi3-extensions-x-auth-id-alias-jersey2-java8 + 1.0.0 + https://github.com/openapitools/openapi-generator + OpenAPI Java + + scm:git:git@github.com:openapitools/openapi-generator.git + scm:git:git@github.com:openapitools/openapi-generator.git + https://github.com/openapitools/openapi-generator + + + + + Unlicense + https://www.apache.org/licenses/LICENSE-2.0.html + repo + + + + + + OpenAPI-Generator Contributors + team@openapitools.org + OpenAPITools.org + http://openapitools.org + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M4 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + 10 + false + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.10 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.7 + 1.7 + true + 128m + 512m + + -Xlint:all + -J-Xss4m + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.1.1 + + + attach-javadocs + + jar + + + + + none + 1.7 + + + http.response.details + a + Http Response Details: + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + + + org.glassfish.jersey.core + jersey-client + ${jersey-version} + + + org.glassfish.jersey.inject + jersey-hk2 + ${jersey-version} + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey-version} + + + org.glassfish.jersey.media + jersey-media-json-jackson + ${jersey-version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind-version} + + + org.openapitools + jackson-databind-nullable + ${jackson-databind-nullable-version} + + + com.github.joschi.jackson + jackson-datatype-threetenbp + ${threetenbp-version} + + + + com.brsanthu + migbase64 + 2.2 + + + javax.annotation + javax.annotation-api + ${javax-annotation-version} + provided + + + + junit + junit + ${junit-version} + test + + + + UTF-8 + 1.6.1 + 2.30.1 + 2.10.4 + 2.10.4 + 0.2.1 + 2.9.10 + 1.3.2 + 4.13 + + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/settings.gradle b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/settings.gradle new file mode 100644 index 000000000000..488eab4f0474 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "openapi3-extensions-x-auth-id-alias-jersey2-java8" \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/AndroidManifest.xml b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/AndroidManifest.xml new file mode 100644 index 000000000000..54fbcb3da1e8 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java new file mode 100644 index 000000000000..f6ecb14f80ea --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java @@ -0,0 +1,1149 @@ +package org.openapitools.client; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Form; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.client.HttpUrlConnectorProvider; +import org.glassfish.jersey.jackson.JacksonFeature; +import org.glassfish.jersey.media.multipart.FormDataBodyPart; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; + +import java.io.IOException; +import java.io.InputStream; + +import java.net.URI; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.security.cert.X509Certificate; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import org.glassfish.jersey.logging.LoggingFeature; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Date; + +import java.net.URLEncoder; + +import java.io.File; +import java.io.UnsupportedEncodingException; + +import java.text.DateFormat; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.openapitools.client.auth.Authentication; +import org.openapitools.client.auth.HttpBasicAuth; +import org.openapitools.client.auth.HttpBearerAuth; +import org.openapitools.client.auth.ApiKeyAuth; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ApiClient { + protected Map defaultHeaderMap = new HashMap(); + protected Map defaultCookieMap = new HashMap(); + protected String basePath = "http://petstore.swagger.io:80/v2"; + protected String userAgent; + private static final Logger log = Logger.getLogger(ApiClient.class.getName()); + + protected List servers = new ArrayList(Arrays.asList( + new ServerConfiguration( + "http://{server}.swagger.io:{port}/v2", + "petstore server", + new HashMap() {{ + put("server", new ServerVariable( + "No description provided", + "petstore", + new HashSet( + Arrays.asList( + "petstore", + "qa-petstore", + "dev-petstore" + ) + ) + )); + put("port", new ServerVariable( + "No description provided", + "80", + new HashSet( + Arrays.asList( + "80", + "8080" + ) + ) + )); + }} + ), + new ServerConfiguration( + "https://localhost:8080/{version}", + "The local server", + new HashMap() {{ + put("version", new ServerVariable( + "No description provided", + "v2", + new HashSet( + Arrays.asList( + "v1", + "v2" + ) + ) + )); + }} + ) + )); + protected Integer serverIndex = 0; + protected Map serverVariables = null; + protected Map> operationServers = new HashMap>() {{ + }}; + protected Map operationServerIndex = new HashMap(); + protected Map> operationServerVariables = new HashMap>(); + protected boolean debugging = false; + protected int connectionTimeout = 0; + private int readTimeout = 0; + + protected Client httpClient; + protected JSON json; + protected String tempFolderPath = null; + + protected Map authentications; + protected Map authenticationLookup; + + protected DateFormat dateFormat; + + /** + * Constructs a new ApiClient with default parameters. + */ + public ApiClient() { + this(null); + } + + /** + * Constructs a new ApiClient with the specified authentication parameters. + * + * @param authMap A hash map containing authentication parameters. + */ + public ApiClient(Map authMap) { + json = new JSON(); + httpClient = buildHttpClient(debugging); + + this.dateFormat = new RFC3339DateFormat(); + + // Set default User-Agent. + setUserAgent("OpenAPI-Generator/1.0.0/java"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + Authentication auth = null; + if (authMap != null) { + auth = authMap.get("api_key"); + } + if (auth instanceof ApiKeyAuth) { + authentications.put("api_key", auth); + } else { + authentications.put("api_key", new ApiKeyAuth("header", "X-Api-Key")); + } + if (authMap != null) { + auth = authMap.get("api_key_query"); + } + if (auth instanceof ApiKeyAuth) { + authentications.put("api_key_query", auth); + } else { + authentications.put("api_key_query", new ApiKeyAuth("query", "api_key")); + } + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + + // Setup authentication lookup (key: authentication alias, value: authentication name) + authenticationLookup = new HashMap(); + authenticationLookup.put("api_key_query", "api_key"); + } + + /** + * Gets the JSON instance to do JSON serialization and deserialization. + * + * @return JSON + */ + public JSON getJSON() { + return json; + } + + public Client getHttpClient() { + return httpClient; + } + + public ApiClient setHttpClient(Client httpClient) { + this.httpClient = httpClient; + return this; + } + + /** + * Returns the base URL to the location where the OpenAPI document is being served. + * + * @return The base URL to the target host. + */ + public String getBasePath() { + return basePath; + } + + /** + * Sets the base URL to the location where the OpenAPI document is being served. + * + * @param basePath The base URL to the target host. + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + public List getServers() { + return servers; + } + + public ApiClient setServers(List servers) { + this.servers = servers; + updateBasePath(); + return this; + } + + public Integer getServerIndex() { + return serverIndex; + } + + public ApiClient setServerIndex(Integer serverIndex) { + this.serverIndex = serverIndex; + updateBasePath(); + return this; + } + + public Map getServerVariables() { + return serverVariables; + } + + public ApiClient setServerVariables(Map serverVariables) { + this.serverVariables = serverVariables; + updateBasePath(); + return this; + } + + private void updateBasePath() { + if (serverIndex != null) { + setBasePath(servers.get(serverIndex).URL(serverVariables)); + } + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication object + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public ApiClient setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return this; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public ApiClient setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return this; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public ApiClient setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return this; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to configure authentications which respects aliases of API keys. + * + * @param secrets Hash map from authentication name to its secret. + */ + public ApiClient configureApiKeys(HashMap secrets) { + for (Map.Entry authEntry : authentications.entrySet()) { + Authentication auth = authEntry.getValue(); + if (auth instanceof ApiKeyAuth) { + String name = authEntry.getKey(); + // respect x-auth-id-alias property + name = authenticationLookup.containsKey(name) ? authenticationLookup.get(name) : name; + if (secrets.containsKey(name)) { + ((ApiKeyAuth) auth).setApiKey(secrets.get(name)); + } + } + } + return this; + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public ApiClient setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return this; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set bearer token for the first Bearer authentication. + * + * @param bearerToken Bearer token + */ + public ApiClient setBearerToken(String bearerToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(bearerToken); + return this; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } + + + /** + * Set the User-Agent header's value (by adding to the default header map). + * @param userAgent Http user agent + * @return API client + */ + public ApiClient setUserAgent(String userAgent) { + userAgent = userAgent; + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Get the User-Agent header's value. + * @return User-Agent string + */ + public String getUserAgent(){ + return userAgent; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return API client + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + 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 + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return API client + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + // Rebuild HTTP Client according to the new "debugging" value. + this.httpClient = buildHttpClient(debugging); + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @return Temp folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set temp folder path + * @param tempFolderPath Temp folder path + * @return API client + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Connect timeout (in milliseconds). + * @return Connection timeout + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + * @param connectionTimeout Connection timeout in milliseconds + * @return API client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); + return this; + } + + /** + * read timeout (in milliseconds). + * @return Read timeout + */ + 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 + * {@link Integer#MAX_VALUE}. + * @param readTimeout Read timeout in milliseconds + * @return API client + */ + public ApiClient setReadTimeout(int readTimeout) { + this.readTimeout = readTimeout; + httpClient.property(ClientProperties.READ_TIMEOUT, readTimeout); + return this; + } + + /** + * Get the date format used to parse/format date parameters. + * @return Date format + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + * @param dateFormat Date format + * @return API client + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + // also set the date format for model (de)serialization with Date properties + this.json.setDateFormat((DateFormat) dateFormat.clone()); + return this; + } + + /** + * Parse the given string into Date object. + * @param str String + * @return Date + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + * @param date Date + * @return Date in string format + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given parameter object into string. + * @param param Object + * @return Object in string format + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection)param) { + if(b.length() > 0) { + b.append(','); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /* + * Format to {@code Pair} objects. + * @param collectionFormat Collection format + * @param name Name + * @param value Value + * @return List of pairs + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format (default: csv) + String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); + + // create the params based on the collection format + if ("multi".equals(format)) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if ("csv".equals(format)) { + delimiter = ","; + } else if ("ssv".equals(format)) { + delimiter = " "; + } else if ("tsv".equals(format)) { + delimiter = "\t"; + } else if ("pipes".equals(format)) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * "* / *" is also default to JSON + * @param mime MIME + * @return True if the MIME type is JSON + */ + public boolean isJsonMime(String mime) { + String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; + return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * @param str String + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * @param obj Object + * @param formParams Form parameters + * @param contentType Context type + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + Entity entity; + if (contentType.startsWith("multipart/form-data")) { + MultiPart multiPart = new MultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()) + .fileName(file.getName()).size(file.length()).build(); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + } else { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()).build(); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(param.getValue()))); + } + } + entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + Form form = new Form(); + for (Entry param: formParams.entrySet()) { + form.param(param.getKey(), parameterToString(param.getValue())); + } + entity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); + } else { + // We let jersey handle the serialization + if (isBodyNullable) { // payload is nullable + if (obj instanceof String) { + entity = Entity.entity(obj == null ? "null" : "\"" + ((String)obj).replaceAll("\"", Matcher.quoteReplacement("\\\"")) + "\"", contentType); + } else { + entity = Entity.entity(obj == null ? "null" : obj, contentType); + } + } else { + if (obj instanceof String) { + entity = Entity.entity(obj == null ? "" : "\"" + ((String)obj).replaceAll("\"", Matcher.quoteReplacement("\\\"")) + "\"", contentType); + } else { + entity = Entity.entity(obj == null ? "" : obj, contentType); + } + } + } + return entity; + } + + /** + * Serialize the given Java object into string according the given + * Content-Type (only JSON, HTTP form is supported for now). + * @param obj Object + * @param formParams Form parameters + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return String + * @throws ApiException API exception + */ + public String serializeToString(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + try { + if (contentType.startsWith("multipart/form-data")) { + throw new ApiException("multipart/form-data not yet supported for serializeToString (http signature authentication)"); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + String formString = ""; + for (Entry param : formParams.entrySet()) { + formString = param.getKey() + "=" + URLEncoder.encode(parameterToString(param.getValue()), "UTF-8") + "&"; + } + + if (formString.length() == 0) { // empty string + return formString; + } else { + return formString.substring(0, formString.length() - 1); + } + } else { + if (isBodyNullable) { + return obj == null ? "null" : json.getMapper().writeValueAsString(obj); + } else { + return obj == null ? "" : json.getMapper().writeValueAsString(obj); + } + } + } catch (Exception ex) { + throw new ApiException("Failed to perform serializeToString: " + ex.toString()); + } + } + + /** + * Deserialize response body to Java object according to the Content-Type. + * @param Type + * @param response Response + * @param returnType Return type + * @return Deserialize object + * @throws ApiException API exception + */ + @SuppressWarnings("unchecked") + public T deserialize(Response response, GenericType returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + return (T) response.readEntity(byte[].class); + } else if (returnType.getRawType() == File.class) { + // Handle file downloading. + T file = (T) downloadFileFromResponse(response); + return file; + } + + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = String.valueOf(contentTypes.get(0)); + + // read the entity stream multiple times + response.bufferEntity(); + + return response.readEntity(returnType); + } + + /** + * Download file from the given response. + * @param response Response + * @return File + * @throws ApiException If fail to read file content from response and write to disk + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + Files.copy(response.readEntity(InputStream.class), file.toPath(), StandardCopyOption.REPLACE_EXISTING); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = (String) response.getHeaders().getFirst("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) + filename = matcher.group(1); + } + + String prefix; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf('.'); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @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 + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable) + throws ApiException { + + // Not using `.target(targetURL).path(path)` below, + // to support (constant) query string in `path`, e.g. "/posts?draft=1" + String targetURL; + if (serverIndex != null && operationServers.containsKey(operation)) { + Integer index = operationServerIndex.containsKey(operation) ? operationServerIndex.get(operation) : serverIndex; + Map variables = operationServerVariables.containsKey(operation) ? + operationServerVariables.get(operation) : serverVariables; + List serverConfigurations = operationServers.get(operation); + if (index < 0 || index >= serverConfigurations.size()) { + throw new ArrayIndexOutOfBoundsException( + String.format( + "Invalid index %d when selecting the host settings. Must be less than %d", + index, serverConfigurations.size())); + } + targetURL = serverConfigurations.get(index).URL(variables) + path; + } else { + targetURL = this.basePath + path; + } + WebTarget target = httpClient.target(targetURL); + + if (queryParams != null) { + for (Pair queryParam : queryParams) { + if (queryParam.getValue() != null) { + target = target.queryParam(queryParam.getName(), escapeString(queryParam.getValue())); + } + } + } + + Invocation.Builder invocationBuilder = target.request().accept(accept); + + for (Entry entry : cookieParams.entrySet()) { + String value = entry.getValue(); + if (value != null) { + invocationBuilder = invocationBuilder.cookie(entry.getKey(), value); + } + } + + for (Entry entry : defaultCookieMap.entrySet()) { + String value = entry.getValue(); + if (value != null) { + invocationBuilder = invocationBuilder.cookie(entry.getKey(), value); + } + } + + Entity entity = serialize(body, formParams, contentType, isBodyNullable); + + // put all headers in one place + Map allHeaderParams = new HashMap<>(defaultHeaderMap); + allHeaderParams.putAll(headerParams); + + // update different parameters (e.g. headers) for authentication + updateParamsForAuth( + authNames, + queryParams, + allHeaderParams, + cookieParams, + serializeToString(body, formParams, contentType, isBodyNullable), + method, + target.getUri()); + + for (Entry entry : allHeaderParams.entrySet()) { + String value = entry.getValue(); + if (value != null) { + invocationBuilder = invocationBuilder.header(entry.getKey(), value); + } + } + + Response response = null; + + try { + response = sendRequest(method, invocationBuilder, entity); + + int statusCode = response.getStatusInfo().getStatusCode(); + Map> responseHeaders = buildResponseHeaders(response); + + if (response.getStatusInfo() == Status.NO_CONTENT) { + return new ApiResponse(statusCode, responseHeaders); + } else if (response.getStatusInfo().getFamily() == Status.Family.SUCCESSFUL) { + if (returnType == null) { + return new ApiResponse(statusCode, responseHeaders); + } else { + return new ApiResponse(statusCode, responseHeaders, deserialize(response, returnType)); + } + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { + try { + respBody = String.valueOf(response.readEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + throw new ApiException( + response.getStatus(), message, buildResponseHeaders(response), respBody); + } + } finally { + try { + response.close(); + } catch (Exception e) { + // it's not critical, since the response object is local in method invokeAPI; that's fine, + // just continue + } + } + } + + private Response sendRequest(String method, Invocation.Builder invocationBuilder, Entity entity) { + Response response; + if ("POST".equals(method)) { + response = invocationBuilder.post(entity); + } else if ("PUT".equals(method)) { + response = invocationBuilder.put(entity); + } else if ("DELETE".equals(method)) { + response = invocationBuilder.method("DELETE", entity); + } else if ("PATCH".equals(method)) { + response = invocationBuilder.method("PATCH", entity); + } else { + response = invocationBuilder.method(method); + } + return response; + } + + /** + * @deprecated Add qualified name of the operation as a first parameter. + */ + @Deprecated + public ApiResponse invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType, boolean isBodyNullable) throws ApiException { + return invokeAPI(null, path, method, queryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType, isBodyNullable); + } + + /** + * Build the Client used to make HTTP requests. + * @param debugging Debug setting + * @return Client + */ + protected Client buildHttpClient(boolean debugging) { + final ClientConfig clientConfig = new ClientConfig(); + clientConfig.register(MultiPartFeature.class); + clientConfig.register(json); + clientConfig.register(JacksonFeature.class); + clientConfig.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true); + // turn off compliance validation to be able to send payloads with DELETE calls + clientConfig.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); + if (debugging) { + clientConfig.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 1024*50 /* Log payloads up to 50K */)); + clientConfig.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY, LoggingFeature.Verbosity.PAYLOAD_ANY); + // Set logger to ALL + java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME).setLevel(java.util.logging.Level.ALL); + } else { + // suppress warnings for payloads with DELETE calls: + java.util.logging.Logger.getLogger("org.glassfish.jersey.client").setLevel(java.util.logging.Level.SEVERE); + } + performAdditionalClientConfiguration(clientConfig); + ClientBuilder clientBuilder = ClientBuilder.newBuilder(); + customizeClientBuilder(clientBuilder); + clientBuilder = clientBuilder.withConfig(clientConfig); + return clientBuilder.build(); + } + + /** + * Perform additional configuration of the API client. + * This method can be overriden to customize the API client. + */ + protected void performAdditionalClientConfiguration(ClientConfig clientConfig) { + // No-op extension point + } + + /** + * Customize the client builder. + * + * This method can be overriden to customize the API client. For example, this can be used to: + * 1. Set the hostname verifier to be used by the client to verify the endpoint's hostname + * against its identification information. + * 2. Set the client-side key store. + * 3. Set the SSL context that will be used when creating secured transport connections to + * server endpoints from web targets created by the client instance that is using this SSL context. + * 4. Set the client-side trust store. + * + * To completely disable certificate validation (at your own risk), you can + * override this method and invoke disableCertificateValidation(clientBuilder). + */ + protected void customizeClientBuilder(ClientBuilder clientBuilder) { + // No-op extension point + } + + /** + * Disable X.509 certificate validation in TLS connections. + * + * Please note that trusting all certificates is extremely risky. + * This may be useful in a development environment with self-signed certificates. + */ + protected void disableCertificateValidation(ClientBuilder clientBuilder) throws KeyManagementException, NoSuchAlgorithmException { + TrustManager[] trustAllCerts = new X509TrustManager[] { + new X509TrustManager() { + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + @Override + public void checkClientTrusted(X509Certificate[] certs, String authType) { + } + @Override + public void checkServerTrusted(X509Certificate[] certs, String authType) { + } + } + }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, trustAllCerts, new SecureRandom()); + clientBuilder.sslContext(sslContext); + } + + protected Map> buildResponseHeaders(Response response) { + Map> responseHeaders = new HashMap>(); + for (Entry> entry: response.getHeaders().entrySet()) { + List values = entry.getValue(); + List headers = new ArrayList(); + for (Object o : values) { + headers.add(String.valueOf(o)); + } + responseHeaders.put(entry.getKey(), headers); + } + return responseHeaders; + } + + /** + * 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 + * @param method HTTP method (e.g. POST) + * @param uri HTTP URI + */ + protected void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams, + Map cookieParams, String payload, String method, URI uri) throws ApiException { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) { + continue; + } + auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); + } + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiException.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiException.java new file mode 100644 index 000000000000..efc394e679d5 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiException.java @@ -0,0 +1,94 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.Map; +import java.util.List; + +/** + * API Exception + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ApiException extends Exception { + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiResponse.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiResponse.java new file mode 100644 index 000000000000..7a74030c85ed --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiResponse.java @@ -0,0 +1,74 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + * + * @param The type of data that is deserialized from response body + */ +public class ApiResponse { + private final int statusCode; + private final Map> headers; + private final T data; + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + /** + * Get the status code + * + * @return status code + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Get the headers + * + * @return map of headers + */ + public Map> getHeaders() { + return headers; + } + + /** + * Get the data + * + * @return data + */ + public T getData() { + return data; + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/Configuration.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/Configuration.java new file mode 100644 index 000000000000..40ca8cd299bb --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/Configuration.java @@ -0,0 +1,39 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/CustomInstantDeserializer.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/CustomInstantDeserializer.java new file mode 100644 index 000000000000..83d4514b071b --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/CustomInstantDeserializer.java @@ -0,0 +1,232 @@ +package org.openapitools.client; + +import com.fasterxml.jackson.core.JsonParser; +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.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; +import org.threeten.bp.ZonedDateTime; +import org.threeten.bp.format.DateTimeFormatter; +import org.threeten.bp.temporal.Temporal; +import org.threeten.bp.temporal.TemporalAccessor; + +import java.io.IOException; +import java.math.BigDecimal; + +/** + * Deserializer for ThreeTen temporal {@link Instant}s, {@link OffsetDateTime}, and {@link ZonedDateTime}s. + * Adapted from the jackson threetenbp InstantDeserializer to add support for deserializing rfc822 format. + * + * @author Nick Williams + */ +public class CustomInstantDeserializer + extends ThreeTenDateTimeDeserializerBase { + private static final long serialVersionUID = 1L; + + public static final CustomInstantDeserializer INSTANT = new CustomInstantDeserializer( + Instant.class, DateTimeFormatter.ISO_INSTANT, + new Function() { + @Override + public Instant apply(TemporalAccessor temporalAccessor) { + return Instant.from(temporalAccessor); + } + }, + new Function() { + @Override + public Instant apply(FromIntegerArguments a) { + return Instant.ofEpochMilli(a.value); + } + }, + new Function() { + @Override + public Instant apply(FromDecimalArguments a) { + return Instant.ofEpochSecond(a.integer, a.fraction); + } + }, + null + ); + + public static final CustomInstantDeserializer OFFSET_DATE_TIME = new CustomInstantDeserializer( + OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME, + new Function() { + @Override + public OffsetDateTime apply(TemporalAccessor temporalAccessor) { + return OffsetDateTime.from(temporalAccessor); + } + }, + new Function() { + @Override + public OffsetDateTime apply(FromIntegerArguments a) { + return OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); + } + }, + new Function() { + @Override + public OffsetDateTime apply(FromDecimalArguments a) { + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); + } + }, + new BiFunction() { + @Override + public OffsetDateTime apply(OffsetDateTime d, ZoneId z) { + return d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime())); + } + } + ); + + public static final CustomInstantDeserializer ZONED_DATE_TIME = new CustomInstantDeserializer( + ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME, + new Function() { + @Override + public ZonedDateTime apply(TemporalAccessor temporalAccessor) { + return ZonedDateTime.from(temporalAccessor); + } + }, + new Function() { + @Override + public ZonedDateTime apply(FromIntegerArguments a) { + return ZonedDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); + } + }, + new Function() { + @Override + public ZonedDateTime apply(FromDecimalArguments a) { + return ZonedDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); + } + }, + new BiFunction() { + @Override + public ZonedDateTime apply(ZonedDateTime zonedDateTime, ZoneId zoneId) { + return zonedDateTime.withZoneSameInstant(zoneId); + } + } + ); + + protected final Function fromMilliseconds; + + protected final Function fromNanoseconds; + + protected final Function parsedToValue; + + protected final BiFunction adjust; + + protected CustomInstantDeserializer(Class supportedType, + DateTimeFormatter parser, + Function parsedToValue, + Function fromMilliseconds, + Function fromNanoseconds, + BiFunction adjust) { + super(supportedType, parser); + this.parsedToValue = parsedToValue; + this.fromMilliseconds = fromMilliseconds; + this.fromNanoseconds = fromNanoseconds; + this.adjust = adjust == null ? new BiFunction() { + @Override + public T apply(T t, ZoneId zoneId) { + return t; + } + } : adjust; + } + + @SuppressWarnings("unchecked") + protected CustomInstantDeserializer(CustomInstantDeserializer base, DateTimeFormatter f) { + super((Class) base.handledType(), f); + parsedToValue = base.parsedToValue; + fromMilliseconds = base.fromMilliseconds; + fromNanoseconds = base.fromNanoseconds; + adjust = base.adjust; + } + + @Override + protected JsonDeserializer withDateFormat(DateTimeFormatter dtf) { + if (dtf == _formatter) { + return this; + } + return new CustomInstantDeserializer(this, dtf); + } + + @Override + public T deserialize(JsonParser parser, DeserializationContext context) throws IOException { + //NOTE: Timestamps contain no timezone info, and are always in configured TZ. Only + //string values have to be adjusted to the configured TZ. + switch (parser.getCurrentTokenId()) { + case JsonTokenId.ID_NUMBER_FLOAT: { + BigDecimal value = parser.getDecimalValue(); + long seconds = value.longValue(); + int nanoseconds = DecimalUtils.extractNanosecondDecimal(value, seconds); + return fromNanoseconds.apply(new FromDecimalArguments( + seconds, nanoseconds, getZone(context))); + } + + case JsonTokenId.ID_NUMBER_INT: { + long timestamp = parser.getLongValue(); + if (context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) { + return this.fromNanoseconds.apply(new FromDecimalArguments( + timestamp, 0, this.getZone(context) + )); + } + return this.fromMilliseconds.apply(new FromIntegerArguments( + timestamp, this.getZone(context) + )); + } + + case JsonTokenId.ID_STRING: { + String string = parser.getText().trim(); + if (string.length() == 0) { + return null; + } + if (string.endsWith("+0000")) { + string = string.substring(0, string.length() - 5) + "Z"; + } + T value; + try { + TemporalAccessor acc = _formatter.parse(string); + value = parsedToValue.apply(acc); + if (context.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)) { + return adjust.apply(value, this.getZone(context)); + } + } catch (DateTimeException e) { + throw _peelDTE(e); + } + return value; + } + } + throw context.mappingException("Expected type float, integer, or string."); + } + + private ZoneId getZone(DeserializationContext context) { + // Instants are always in UTC, so don't waste compute cycles + return (_valueClass == Instant.class) ? null : DateTimeUtils.toZoneId(context.getTimeZone()); + } + + private static class FromIntegerArguments { + public final long value; + public final ZoneId zoneId; + + private FromIntegerArguments(long value, ZoneId zoneId) { + this.value = value; + this.zoneId = zoneId; + } + } + + private static class FromDecimalArguments { + public final long integer; + public final int fraction; + public final ZoneId zoneId; + + private FromDecimalArguments(long integer, int fraction, ZoneId zoneId) { + this.integer = integer; + this.fraction = fraction; + this.zoneId = zoneId; + } + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/JSON.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/JSON.java new file mode 100644 index 000000000000..7e2afd3432b6 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/JSON.java @@ -0,0 +1,252 @@ +package org.openapitools.client; + +import org.threeten.bp.*; +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import org.openapitools.jackson.nullable.JsonNullableModule; +import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; + +import java.text.DateFormat; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.ext.ContextResolver; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class JSON implements ContextResolver { + private ObjectMapper mapper; + + public JSON() { + mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); + mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.setDateFormat(new RFC3339DateFormat()); + ThreeTenModule module = new ThreeTenModule(); + module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT); + module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME); + module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME); + mapper.registerModule(module); + JsonNullableModule jnm = new JsonNullableModule(); + mapper.registerModule(jnm); + } + + /** + * Set the date format for JSON (de)serialization with Date properties. + * @param dateFormat Date format + */ + public void setDateFormat(DateFormat dateFormat) { + mapper.setDateFormat(dateFormat); + } + + @Override + public ObjectMapper getContext(Class type) { + return mapper; + } + + /** + * Get the object mapper + * + * @return object mapper + */ + public ObjectMapper getMapper() { return mapper; } + + /** + * Returns the target model class that should be used to deserialize the input data. + * The discriminator mappings are used to determine the target model class. + * + * @param node The input data. + * @param modelClass The class that contains the discriminator mappings. + */ + public static Class getClassForElement(JsonNode node, Class modelClass) { + ClassDiscriminatorMapping cdm = modelDiscriminators.get(modelClass); + if (cdm != null) { + return cdm.getClassForElement(node, new HashSet>()); + } + return null; + } + + /** + * Helper class to register the discriminator mappings. + */ + private static class ClassDiscriminatorMapping { + // The model class name. + Class modelClass; + // The name of the discriminator property. + String discriminatorName; + // The discriminator mappings for a model class. + Map> discriminatorMappings; + + // Constructs a new class discriminator. + ClassDiscriminatorMapping(Class cls, String propertyName, Map> mappings) { + modelClass = cls; + discriminatorName = propertyName; + discriminatorMappings = new HashMap>(); + if (mappings != null) { + discriminatorMappings.putAll(mappings); + } + } + + // Return the name of the discriminator property for this model class. + String getDiscriminatorPropertyName() { + return discriminatorName; + } + + // Return the discriminator value or null if the discriminator is not + // present in the payload. + String getDiscriminatorValue(JsonNode node) { + // Determine the value of the discriminator property in the input data. + if (discriminatorName != null) { + // Get the value of the discriminator property, if present in the input payload. + node = node.get(discriminatorName); + if (node != null && node.isValueNode()) { + String discrValue = node.asText(); + if (discrValue != null) { + return discrValue; + } + } + } + return null; + } + + /** + * Returns the target model class that should be used to deserialize the input data. + * This function can be invoked for anyOf/oneOf composed models with discriminator mappings. + * The discriminator mappings are used to determine the target model class. + * + * @param node The input data. + * @param visitedClasses The set of classes that have already been visited. + */ + Class getClassForElement(JsonNode node, Set> visitedClasses) { + if (visitedClasses.contains(modelClass)) { + // Class has already been visited. + return null; + } + // Determine the value of the discriminator property in the input data. + String discrValue = getDiscriminatorValue(node); + if (discrValue == null) { + return null; + } + Class cls = discriminatorMappings.get(discrValue); + // It may not be sufficient to return this cls directly because that target class + // may itself be a composed schema, possibly with its own discriminator. + visitedClasses.add(modelClass); + for (Class childClass : discriminatorMappings.values()) { + ClassDiscriminatorMapping childCdm = modelDiscriminators.get(childClass); + if (childCdm == null) { + continue; + } + if (!discriminatorName.equals(childCdm.discriminatorName)) { + discrValue = getDiscriminatorValue(node); + if (discrValue == null) { + continue; + } + } + if (childCdm != null) { + // Recursively traverse the discriminator mappings. + Class childDiscr = childCdm.getClassForElement(node, visitedClasses); + if (childDiscr != null) { + return childDiscr; + } + } + } + return cls; + } + } + + /** + * Returns true if inst is an instance of modelClass in the OpenAPI model hierarchy. + * + * The Java class hierarchy is not implemented the same way as the OpenAPI model hierarchy, + * so it's not possible to use the instanceof keyword. + * + * @param modelClass A OpenAPI model class. + * @param inst The instance object. + */ + public static boolean isInstanceOf(Class modelClass, Object inst, Set> visitedClasses) { + if (modelClass.isInstance(inst)) { + // This handles the 'allOf' use case with single parent inheritance. + return true; + } + if (visitedClasses.contains(modelClass)) { + // This is to prevent infinite recursion when the composed schemas have + // a circular dependency. + return false; + } + visitedClasses.add(modelClass); + + // Traverse the oneOf/anyOf composed schemas. + Map descendants = modelDescendants.get(modelClass); + if (descendants != null) { + for (GenericType childType : descendants.values()) { + if (isInstanceOf(childType.getRawType(), inst, visitedClasses)) { + return true; + } + } + } + return false; + } + + /** + * A map of discriminators for all model classes. + */ + private static Map, ClassDiscriminatorMapping> modelDiscriminators = new HashMap, ClassDiscriminatorMapping>(); + + /** + * A map of oneOf/anyOf descendants for each model class. + */ + private static Map, Map> modelDescendants = new HashMap, Map>(); + + /** + * Register a model class discriminator. + * + * @param modelClass the model class + * @param discriminatorPropertyName the name of the discriminator property + * @param mappings a map with the discriminator mappings. + */ + public static void registerDiscriminator(Class modelClass, String discriminatorPropertyName, Map> mappings) { + ClassDiscriminatorMapping m = new ClassDiscriminatorMapping(modelClass, discriminatorPropertyName, mappings); + modelDiscriminators.put(modelClass, m); + } + + /** + * Register the oneOf/anyOf descendants of the modelClass. + * + * @param modelClass the model class + * @param descendants a map of oneOf/anyOf descendants. + */ + public static void registerDescendants(Class modelClass, Map descendants) { + modelDescendants.put(modelClass, descendants); + } + + private static JSON json; + + static + { + json = new JSON(); + } + + /** + * Get the default JSON instance. + * + * @return the default JSON instance + */ + public static JSON getDefault() { + return json; + } + + /** + * Set the default JSON instance. + * + * @param json JSON instance to be used + */ + public static void setDefault(JSON json) { + JSON.json = json; + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/Pair.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/Pair.java new file mode 100644 index 000000000000..e62f20b92ee3 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/Pair.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) { + return; + } + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) { + return; + } + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) { + return false; + } + + if (arg.trim().isEmpty()) { + return false; + } + + return true; + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/RFC3339DateFormat.java new file mode 100644 index 000000000000..9ed3230bd364 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -0,0 +1,55 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +import com.fasterxml.jackson.databind.util.StdDateFormat; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.ParsePosition; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); + + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } +} \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ServerConfiguration.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ServerConfiguration.java new file mode 100644 index 000000000000..a1107a8690e4 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ServerConfiguration.java @@ -0,0 +1,58 @@ +package org.openapitools.client; + +import java.util.Map; + +/** + * Representing a Server configuration. + */ +public class ServerConfiguration { + public String URL; + public String description; + public Map variables; + + /** + * @param URL A URL to the target host. + * @param description A describtion of the host designated by the URL. + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ + public ServerConfiguration(String URL, String description, Map variables) { + this.URL = URL; + this.description = description; + this.variables = variables; + } + + /** + * Format URL template using given variables. + * + * @param variables A map between a variable name and its value. + * @return Formatted URL. + */ + public String URL(Map variables) { + String url = this.URL; + + // go through variables and replace placeholders + for (Map.Entry variable: this.variables.entrySet()) { + String name = variable.getKey(); + ServerVariable serverVariable = variable.getValue(); + String value = serverVariable.defaultValue; + + if (variables != null && variables.containsKey(name)) { + value = variables.get(name); + if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { + throw new RuntimeException("The variable " + name + " in the server URL has invalid value " + value + "."); + } + } + url = url.replaceAll("\\{" + name + "\\}", value); + } + return url; + } + + /** + * Format URL template using default server variables. + * + * @return Formatted URL. + */ + public String URL() { + return URL(null); + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ServerVariable.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ServerVariable.java new file mode 100644 index 000000000000..c2f13e216662 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ServerVariable.java @@ -0,0 +1,23 @@ +package org.openapitools.client; + +import java.util.HashSet; + +/** + * Representing a Server Variable for server URL template substitution. + */ +public class ServerVariable { + public String description; + public String defaultValue; + public HashSet enumValues = null; + + /** + * @param description A description for the server variable. + * @param defaultValue The default value to use for substitution. + * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. + */ + public ServerVariable(String description, String defaultValue, HashSet enumValues) { + this.description = description; + this.defaultValue = defaultValue; + this.enumValues = enumValues; + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/StringUtil.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/StringUtil.java new file mode 100644 index 000000000000..baacf90a2b13 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/StringUtil.java @@ -0,0 +1,83 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.Collection; +import java.util.Iterator; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) { + return true; + } + if (value != null && value.equalsIgnoreCase(str)) { + return true; + } + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

+ * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) { + return ""; + } + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Join a list of strings with the given separator. + * + * @param list The list of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(Collection list, String separator) { + Iterator iterator = list.iterator(); + StringBuilder out = new StringBuilder(); + if (iterator.hasNext()) { + out.append(iterator.next()); + } + while (iterator.hasNext()) { + out.append(separator).append(iterator.next()); + } + return out.toString(); + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/api/UsageApi.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/api/UsageApi.java new file mode 100644 index 000000000000..668cbec37c2d --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/api/UsageApi.java @@ -0,0 +1,287 @@ +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import javax.ws.rs.core.GenericType; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class UsageApi { + private ApiClient apiClient; + + public UsageApi() { + this(Configuration.getDefaultApiClient()); + } + + public UsageApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Get the API cilent + * + * @return API client + */ + public ApiClient getApiClient() { + return apiClient; + } + + /** + * Set the API cilent + * + * @param apiClient an instance of API client + */ + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Use any API key + * Use any API key + * @return Object + * @throws ApiException if fails to make API call + * @http.response.details + + + +
Status Code Description Response Headers
200 successful operation -
+ */ + public Object anyKey() throws ApiException { + return anyKeyWithHttpInfo().getData(); + } + + /** + * Use any API key + * Use any API key + * @return ApiResponse<Object> + * @throws ApiException if fails to make API call + * @http.response.details + + + +
Status Code Description Response Headers
200 successful operation -
+ */ + public ApiResponse anyKeyWithHttpInfo() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/any"; + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key", "api_key_query" }; + + GenericType localVarReturnType = new GenericType() {}; + + return apiClient.invokeAPI("UsageApi.anyKey", localVarPath, "GET", localVarQueryParams, localVarPostBody, + localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, + localVarAuthNames, localVarReturnType, false); + } + /** + * Use both API keys + * Use both API keys + * @return Object + * @throws ApiException if fails to make API call + * @http.response.details + + + +
Status Code Description Response Headers
200 successful operation -
+ */ + public Object bothKeys() throws ApiException { + return bothKeysWithHttpInfo().getData(); + } + + /** + * Use both API keys + * Use both API keys + * @return ApiResponse<Object> + * @throws ApiException if fails to make API call + * @http.response.details + + + +
Status Code Description Response Headers
200 successful operation -
+ */ + public ApiResponse bothKeysWithHttpInfo() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/both"; + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key", "api_key_query" }; + + GenericType localVarReturnType = new GenericType() {}; + + return apiClient.invokeAPI("UsageApi.bothKeys", localVarPath, "GET", localVarQueryParams, localVarPostBody, + localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, + localVarAuthNames, localVarReturnType, false); + } + /** + * Use API key in header + * Use API key in header + * @return Object + * @throws ApiException if fails to make API call + * @http.response.details + + + +
Status Code Description Response Headers
200 successful operation -
+ */ + public Object keyInHeader() throws ApiException { + return keyInHeaderWithHttpInfo().getData(); + } + + /** + * Use API key in header + * Use API key in header + * @return ApiResponse<Object> + * @throws ApiException if fails to make API call + * @http.response.details + + + +
Status Code Description Response Headers
200 successful operation -
+ */ + public ApiResponse keyInHeaderWithHttpInfo() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/header"; + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key" }; + + GenericType localVarReturnType = new GenericType() {}; + + return apiClient.invokeAPI("UsageApi.keyInHeader", localVarPath, "GET", localVarQueryParams, localVarPostBody, + localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, + localVarAuthNames, localVarReturnType, false); + } + /** + * Use API key in query + * Use API key in query + * @return Object + * @throws ApiException if fails to make API call + * @http.response.details + + + +
Status Code Description Response Headers
200 successful operation -
+ */ + public Object keyInQuery() throws ApiException { + return keyInQueryWithHttpInfo().getData(); + } + + /** + * Use API key in query + * Use API key in query + * @return ApiResponse<Object> + * @throws ApiException if fails to make API call + * @http.response.details + + + +
Status Code Description Response Headers
200 successful operation -
+ */ + public ApiResponse keyInQueryWithHttpInfo() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/query"; + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key_query" }; + + GenericType localVarReturnType = new GenericType() {}; + + return apiClient.invokeAPI("UsageApi.keyInQuery", localVarPath, "GET", localVarQueryParams, localVarPostBody, + localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, + localVarAuthNames, localVarReturnType, false); + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java new file mode 100644 index 000000000000..dc5960d01a69 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java @@ -0,0 +1,79 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if ("query".equals(location)) { + queryParams.add(new Pair(paramName, value)); + } else if ("header".equals(location)) { + headerParams.put(paramName, value); + } else if ("cookie".equals(location)) { + cookieParams.put(paramName, value); + } + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/Authentication.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/Authentication.java new file mode 100644 index 000000000000..56295a0d83cd --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/Authentication.java @@ -0,0 +1,33 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + * @param cookieParams Map of cookie parameters + */ + void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException; + +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java new file mode 100644 index 000000000000..cdf367d2a505 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java @@ -0,0 +1,60 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import com.migcomponents.migbase64.Base64; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + try { + headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java new file mode 100644 index 000000000000..2bae057b7c42 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -0,0 +1,62 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class HttpBearerAuth implements Authentication { + private final String scheme; + private String bearerToken; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ + public String getBearerToken() { + return bearerToken; + } + + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ + public void setBearerToken(String bearerToken) { + this.bearerToken = bearerToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + if(bearerToken == null) { + return; + } + + headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java new file mode 100644 index 000000000000..618f7e4efd62 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -0,0 +1,149 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.openapitools.client.ApiException; +import java.util.Objects; +import java.lang.reflect.Type; +import java.util.Map; +import javax.ws.rs.core.GenericType; + +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public abstract class AbstractOpenApiSchema { + + // store the actual instance of the schema/object + private Object instance; + + // is nullable + private Boolean isNullable; + + // schema type (e.g. oneOf, anyOf) + private final String schemaType; + + public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { + this.schemaType = schemaType; + this.isNullable = isNullable; + } + + /** + * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object + * + * @return an instance of the actual schema/object + */ + public abstract Map getSchemas(); + + /** + * Get the actual instance + * + * @return an instance of the actual schema/object + */ + @JsonValue + public Object getActualInstance() {return instance;} + + /** + * Set the actual instance + * + * @param instance the actual instance of the schema/object + */ + public void setActualInstance(Object instance) {this.instance = instance;} + + /** + * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well + * + * @return an instance of the actual schema/object + */ + public Object getActualInstanceRecursively() { + return getActualInstanceRecursively(this); + } + + private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { + if (object.getActualInstance() == null) { + return null; + } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { + return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); + } else { + return object.getActualInstance(); + } + } + + /** + * Get the schema type (e.g. anyOf, oneOf) + * + * @return the schema type + */ + public String getSchemaType() { + return schemaType; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ").append(getClass()).append(" {\n"); + sb.append(" instance: ").append(toIndentedString(instance)).append("\n"); + sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n"); + sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; + return Objects.equals(this.instance, a.instance) && + Objects.equals(this.isNullable, a.isNullable) && + Objects.equals(this.schemaType, a.schemaType); + } + + @Override + public int hashCode() { + return Objects.hash(instance, isNullable, schemaType); + } + + /** + * Is nullalble + * + * @return true if it's nullable + */ + public Boolean isNullable() { + if (Boolean.TRUE.equals(isNullable)) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } + + + +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/test/java/org/openapitools/client/api/UsageApiTest.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/test/java/org/openapitools/client/api/UsageApiTest.java new file mode 100644 index 000000000000..4c5fc6feab40 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/test/java/org/openapitools/client/api/UsageApiTest.java @@ -0,0 +1,91 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.*; +import org.openapitools.client.auth.*; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for UsageApi + */ +public class UsageApiTest { + + private final UsageApi api = new UsageApi(); + + /** + * Use any API key + * + * Use any API key + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void anyKeyTest() throws ApiException { + //Object response = api.anyKey(); + // TODO: test validations + } + + /** + * Use both API keys + * + * Use both API keys + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void bothKeysTest() throws ApiException { + //Object response = api.bothKeys(); + // TODO: test validations + } + + /** + * Use API key in header + * + * Use API key in header + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void keyInHeaderTest() throws ApiException { + //Object response = api.keyInHeader(); + // TODO: test validations + } + + /** + * Use API key in query + * + * Use API key in query + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void keyInQueryTest() throws ApiException { + //Object response = api.keyInQuery(); + // TODO: test validations + } + +} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go index 4456d5af6e73..8efc1bb8e664 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go @@ -97,12 +97,12 @@ func (r apiTestClassnameRequest) Execute() (Client, *_nethttp.Response, error) { if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { - if auth, ok := auth["api_key_query"]; ok { + if apiKey, ok := auth["api_key_query"]; ok { var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key } else { - key = auth.Key + key = apiKey.Key } localVarQueryParams.Add("api_key_query", key) } diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_pet.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_pet.go index 31bdd2c3cf87..318ee2f6ea28 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_pet.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_pet.go @@ -489,12 +489,12 @@ func (r apiGetPetByIdRequest) Execute() (Pet, *_nethttp.Response, error) { if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { - if auth, ok := auth["api_key"]; ok { + if apiKey, ok := auth["api_key"]; ok { var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key } else { - key = auth.Key + key = apiKey.Key } localVarHeaderParams["api_key"] = key } diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_store.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_store.go index 6d48bf45defb..1857755301cf 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_store.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_store.go @@ -176,12 +176,12 @@ func (r apiGetInventoryRequest) Execute() (map[string]int32, *_nethttp.Response, if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { - if auth, ok := auth["api_key"]; ok { + if apiKey, ok := auth["api_key"]; ok { var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key } else { - key = auth.Key + key = apiKey.Key } localVarHeaderParams["api_key"] = key }