Class ApiClient
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected Map<String,Authentication> protected Stringprotected org.glassfish.jersey.client.ClientConfigprotected booleanprotected intprotected DateFormatprotected booleanprotected jakarta.ws.rs.client.Clientprotected JSONprotected static final Loggerprotected Map<String,List<ServerConfiguration>> protected RetryConfigprotected Integerprotected List<ServerConfiguration>protected Stringprotected String -
Constructor Summary
ConstructorsConstructorDescriptionConstructs a new ApiClient with default parameters.ApiClient(Map<String, Authentication> authMap) Constructs a new ApiClient with the specified authentication parameters. -
Method Summary
Modifier and TypeMethodDescriptionaddDefaultCookie(String key, String value) Add a default cookie.addDefaultHeader(String key, String value) Add a default header.protected jakarta.ws.rs.client.ClientBuild the Client used to make HTTP requests.buildResponseHeaders(jakarta.ws.rs.core.Response response) configureApiKeys(Map<String, String> secrets) Helper method to configure authentications which respects aliases of API keys.jakarta.ws.rs.client.Invocation.BuildercreateBuilder(String operation, String path, List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams, String[] accepts, String[] authNames) Create builder to invoke the API.protected voidcustomizeClientBuilder(jakarta.ws.rs.client.ClientBuilder clientBuilder) Customize the client builder.<T> Tdeserialize(jakarta.ws.rs.core.Response response, jakarta.ws.rs.core.GenericType<T> returnType) Deserialize response body to Java object according to the Content-Type.protected voiddisableCertificateValidation(jakarta.ws.rs.client.ClientBuilder clientBuilder) Disable X.509 certificate validation in TLS connections.voidenableRetry(boolean enableRetry) Enable retry directly on the client instead of creating a new retry objectescapeString(String str) Escape the given string to be used as URL query value.formatDate(Date date) Format the given Date object into string.formatOffsetDateTime(OffsetDateTime offsetDateTime) Format the givenOffsetDateTimeobject into string.getAuthentication(String authName) Get authentication for the given name.Get authentications (key: authentication name, value: authentication).Returns the base URL to the location where the OpenAPI document is being served.org.glassfish.jersey.client.ClientConfigGets the client config.intConnect timeout (in milliseconds).Get the date format used to parse/format date parameters.static ApiClientGet the default API client, which would be used when creating API instances without providing an API client.org.glassfish.jersey.client.ClientConfigGet the default client config.jakarta.ws.rs.client.ClientbooleangetIsIaC()Get whether this API client is managed by Infrastructure as Code (IaC) tooling.getJSON()Gets the JSON instance to do JSON serialization and deserialization.Get the ApiClient loggerGet the date format used to parse/formatOffsetDateTimeparameters.intread timeout (in milliseconds).getRetry()Return the retryConfig objectThe path of temporary folder used to store downloaded files from endpoints with file response.Get list of all unstable operationsGet the User-Agent header's value.<T> ApiResponse<T>invokeAPI(String method, jakarta.ws.rs.client.Invocation.Builder invocationBuilder, Map<String, String> headerParams, String[] contentTypes, Object body, Map<String, Object> formParams, Boolean isBodyNullable, jakarta.ws.rs.core.GenericType<T> returnType) Invoke API by sending HTTP request with the given options.<T> CompletableFuture<ApiResponse<T>>invokeAPIAsync(String method, jakarta.ws.rs.client.Invocation.Builder invocationBuilder, Map<String, String> headerParams, String[] contentTypes, Object body, Map<String, Object> formParams, Boolean isBodyNullable, jakarta.ws.rs.core.GenericType<T> returnType) Invoke API by sending HTTP request with the given options, asynchronously.booleanCheck that whether compress is enabled for this API client.booleanCheck that whether debugging is enabled for this API client.booleanisJsonMime(String mime) Check if the given MIME is a JSON MIME.booleanisUnstableOperation(String operation) Determine whether an operation is an unstable operation.booleanisUnstableOperationEnabled(String operation) Determine whether an unstable operation is enabled.parameterToPairs(String collectionFormat, String name, Object value) parameterToString(Object param) Format the given parameter object into string.selectHeaderAccept(String[] accepts) 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)selectHeaderContentType(String[] contentTypes) 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.jakarta.ws.rs.client.Entity<?>serialize(Object obj, Map<String, Object> formParams, String contentType, String contentEncoding, boolean isBodyNullable) Serialize the given Java object into string entity according the given Content-Type (only JSON is supported for now).setAccessToken(String accessToken) Helper method to set access token for the first OAuth2 authentication.Helper method to set API key value for the first API key authentication.setApiKeyPrefix(String apiKeyPrefix) Helper method to set API key prefix for the first API key authentication.setBasePath(String basePath) Sets the base URL to the location where the OpenAPI document is being served.setBearerToken(String bearerToken) Helper method to set bearer token for the first Bearer authentication.setClientConfig(org.glassfish.jersey.client.ClientConfig clientConfig) Set the client config.setCompress(boolean compress) Enable/disable compress for this API client.setConnectTimeout(int connectionTimeout) Set the connect timeout (in milliseconds).setDateFormat(DateFormat dateFormat) Set the date format used to parse/format date parameters.setDebugging(boolean debugging) Enable/disable debugging for this API client.static voidsetDefaultApiClient(ApiClient apiClient) Set the default API client, which would be used when creating API instances without providing an API client.setHttpClient(jakarta.ws.rs.client.Client httpClient) setIsIaC(boolean isIaC) Set whether this API client is managed by Infrastructure as Code (IaC) tooling.Helper method to set the authorization code flow for the first OAuth2 authentication.setOauthCredentials(String clientId, String clientSecret) Helper method to set the credentials for the first OAuth2 authentication.setOauthPasswordFlow(String username, String password) Helper method to set the password flow for the first OAuth2 authentication.setOauthScope(String scope) Helper method to set the scopes for the first OAuth2 authentication.voidsetOffsetDateTimeFormatter(DateTimeFormatter offsetDateTimeFormatter) Set the date format used to parse/formatOffsetDateTimeparameters.setPassword(String password) Helper method to set password for the first HTTP basic authentication.setReadTimeout(int readTimeout) Set the read timeout (in milliseconds).voidsetRetry(RetryConfig retry) Add custom retry object in the clientsetServerIndex(Integer serverIndex) setServers(List<ServerConfiguration> servers) setServerVariables(Map<String, String> serverVariables) setTempFolderPath(String tempFolderPath) Set temp folder pathbooleansetUnstableOperationEnabled(String operation, boolean enabled) Mark an unstable operation as enabled/disabled.Set the default User-Agent header's value with telemetry information (by adding to the default header map).setUserAgent(String userAgent) Set the User-Agent header's value (by adding to the default header map).setUsername(String username) Helper method to set username for the first HTTP basic authentication.protected voidupdateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams, URI uri) Update query and header parameters based on authentication settings.
-
Field Details
-
defaultHeaderMap
-
defaultCookieMap
-
basePath
-
userAgent
-
servers
-
serverIndex
-
serverVariables
-
operationServers
-
operationServerIndex
-
operationServerVariables
-
debugging
protected boolean debugging -
retry
-
compress
protected boolean compress -
clientConfig
protected org.glassfish.jersey.client.ClientConfig clientConfig -
connectionTimeout
protected int connectionTimeout -
httpClient
protected jakarta.ws.rs.client.Client httpClient -
json
-
tempFolderPath
-
authentications
-
dateFormat
-
unstableOperations
-
logger
-
-
Constructor Details
-
ApiClient
public ApiClient()Constructs a new ApiClient with default parameters. -
ApiClient
Constructs a new ApiClient with the specified authentication parameters.- Parameters:
authMap- A hash map containing authentication parameters.
-
-
Method Details
-
getDefaultApiClient
Get the default API client, which would be used when creating API instances without providing an API client.- Returns:
- Default API client
-
setDefaultApiClient
Set the default API client, which would be used when creating API instances without providing an API client.- Parameters:
apiClient- API client
-
getOffsetDateTimeFormatter
Get the date format used to parse/formatOffsetDateTimeparameters.- Returns:
- DateTimeFormatter
-
setRetry
Add custom retry object in the client- Parameters:
retry- retry object
-
getRetry
Return the retryConfig object- Returns:
- retryConfig
-
enableRetry
public void enableRetry(boolean enableRetry) Enable retry directly on the client instead of creating a new retry object- Parameters:
enableRetry- bool, enable retry or not
-
setOffsetDateTimeFormatter
Set the date format used to parse/formatOffsetDateTimeparameters.- Parameters:
offsetDateTimeFormatter-DateTimeFormatter
-
formatOffsetDateTime
Format the givenOffsetDateTimeobject into string.- Parameters:
offsetDateTime-OffsetDateTime- Returns:
OffsetDateTimein string format
-
getJSON
Gets the JSON instance to do JSON serialization and deserialization.- Returns:
- JSON
-
getHttpClient
public jakarta.ws.rs.client.Client getHttpClient() -
setHttpClient
-
getBasePath
Returns the base URL to the location where the OpenAPI document is being served.- Returns:
- The base URL to the target host.
-
setBasePath
Sets the base URL to the location where the OpenAPI document is being served.- Parameters:
basePath- The base URL to the target host.- Returns:
- API client
-
getServers
-
setServers
-
getServerIndex
-
setServerIndex
-
getServerVariables
-
setServerVariables
-
getAuthentications
Get authentications (key: authentication name, value: authentication).- Returns:
- Map of authentication object
-
getAuthentication
Get authentication for the given name.- Parameters:
authName- The authentication name- Returns:
- The authentication, null if not found
-
setUsername
Helper method to set username for the first HTTP basic authentication.- Parameters:
username- Username- Returns:
- API client
-
setPassword
Helper method to set password for the first HTTP basic authentication.- Parameters:
password- Password- Returns:
- API client
-
setApiKey
Helper method to set API key value for the first API key authentication.- Parameters:
apiKey- API key- Returns:
- API client
-
configureApiKeys
Helper method to configure authentications which respects aliases of API keys.- Parameters:
secrets- Hash map from authentication name to its secret.- Returns:
- API client
-
setApiKeyPrefix
Helper method to set API key prefix for the first API key authentication.- Parameters:
apiKeyPrefix- API key prefix- Returns:
- API client
-
setBearerToken
Helper method to set bearer token for the first Bearer authentication.- Parameters:
bearerToken- Bearer token- Returns:
- API client
-
setAccessToken
Helper method to set access token for the first OAuth2 authentication.- Parameters:
accessToken- Access token- Returns:
- API client
-
setOauthCredentials
Helper method to set the credentials for the first OAuth2 authentication.- Parameters:
clientId- the client IDclientSecret- the client secret- Returns:
- API client
-
setOauthPasswordFlow
Helper method to set the password flow for the first OAuth2 authentication.- Parameters:
username- the user namepassword- the user password- Returns:
- API client
-
setOauthAuthorizationCodeFlow
Helper method to set the authorization code flow for the first OAuth2 authentication.- Parameters:
code- the authorization code- Returns:
- API client
-
setOauthScope
Helper method to set the scopes for the first OAuth2 authentication.- Parameters:
scope- the oauth scope- Returns:
- API client
-
setUserAgent
Set the User-Agent header's value (by adding to the default header map).- Parameters:
userAgent- Http user agent- Returns:
- API client
-
getUserAgent
Get the User-Agent header's value.- Returns:
- User-Agent string
-
setUserAgent
Set the default User-Agent header's value with telemetry information (by adding to the default header map).- Returns:
- API client
-
addDefaultHeader
Add a default header.- Parameters:
key- The header's keyvalue- The header's value- Returns:
- API client
-
setIsIaC
Set whether this API client is managed by Infrastructure as Code (IaC) tooling. When enabled, theX-Datadog-Managed-By: iacheader is sent on every request made through this client (by adding to the default header map).- Parameters:
isIaC- Whether calls made with this client originate from IaC tooling- Returns:
- API client
-
getIsIaC
public boolean getIsIaC()Get whether this API client is managed by Infrastructure as Code (IaC) tooling.- Returns:
- Whether this client is managed by IaC tooling
-
addDefaultCookie
Add a default cookie.- Parameters:
key- The cookie's keyvalue- The cookie's value- Returns:
- API client
-
getClientConfig
public org.glassfish.jersey.client.ClientConfig getClientConfig()Gets the client config.- Returns:
- Client config
-
setClientConfig
Set the client config.- Parameters:
clientConfig- Set the client config- Returns:
- API client
-
isDebugging
public boolean isDebugging()Check that whether debugging is enabled for this API client.- Returns:
- True if debugging is switched on
-
setDebugging
Enable/disable debugging for this API client.- Parameters:
debugging- To enable (true) or disable (false) debugging- Returns:
- API client
-
isCompress
public boolean isCompress()Check that whether compress is enabled for this API client.- Returns:
- True if compress is switched on
-
setCompress
Enable/disable compress for this API client.- Parameters:
compress- To enable (true) or disable (false) compress- Returns:
- API client
-
getTempFolderPath
The path of temporary folder used to store downloaded files from endpoints with file response. The default value isnull, i.e. using the system's default temporary folder.- Returns:
- Temp folder path
-
setTempFolderPath
Set temp folder path- Parameters:
tempFolderPath- Temp folder path- Returns:
- API client
-
getConnectTimeout
public int getConnectTimeout()Connect timeout (in milliseconds).- Returns:
- Connection timeout
-
setConnectTimeout
Set the connect timeout (in milliseconds). A value of 0 means no timeout, otherwise values must be between 1 andInteger.MAX_VALUE.- Parameters:
connectionTimeout- Connection timeout in milliseconds- Returns:
- API client
-
getReadTimeout
public int getReadTimeout()read timeout (in milliseconds).- Returns:
- Read timeout
-
setReadTimeout
Set the read timeout (in milliseconds). A value of 0 means no timeout, otherwise values must be between 1 andInteger.MAX_VALUE.- Parameters:
readTimeout- Read timeout in milliseconds- Returns:
- API client
-
getDateFormat
Get the date format used to parse/format date parameters.- Returns:
- Date format
-
setDateFormat
Set the date format used to parse/format date parameters.- Parameters:
dateFormat- Date format- Returns:
- API client
-
getUnstableOperations
Get list of all unstable operations- Returns:
- set of all unstable operations Ids
-
setUnstableOperationEnabled
Mark an unstable operation as enabled/disabled.- Parameters:
operation- operation Id - this is the name of the method on the API class, e.g. "createFoo"enabled- whether to mark the operation as enabled (true) or disabled (false)- Returns:
- true if the operation is marked as unstable and thus was enabled/disabled, false otherwise
-
isUnstableOperation
Determine whether an operation is an unstable operation.- Parameters:
operation- operation Id - this is the name of the method on the API class, e.g. "createFoo"- Returns:
- true if the operation is an unstable operation, false otherwise
-
isUnstableOperationEnabled
Determine whether an unstable operation is enabled.- Parameters:
operation- operation Id - this is the name of the method on the API class, e.g. "createFoo"- Returns:
- true if the operation is unstable and it is enabled, false otherwise
-
getLogger
Get the ApiClient logger- Returns:
- ApiClient logger
-
formatDate
Format the given Date object into string.- Parameters:
date- Date- Returns:
- Date in string format
-
parameterToString
Format the given parameter object into string.- Parameters:
param- Object- Returns:
- Object in string format
-
parameterToPairs
-
isJsonMime
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- Parameters:
mime- MIME- Returns:
- True if the MIME type is JSON
-
selectHeaderAccept
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)- Parameters:
accepts- The accepts array to select from- Returns:
- The Accept header to use. If the given array is empty, null will be returned (not to set the Accept header explicitly).
-
selectHeaderContentType
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.- Parameters:
contentTypes- The Content-Type array to select from- Returns:
- The Content-Type header to use. If the given array is empty, JSON will be used.
-
escapeString
Escape the given string to be used as URL query value.- Parameters:
str- String- Returns:
- Escaped string
-
serialize
public jakarta.ws.rs.client.Entity<?> serialize(Object obj, Map<String, Object> formParams, String contentType, String contentEncoding, boolean isBodyNullable) Serialize the given Java object into string entity according the given Content-Type (only JSON is supported for now).- Parameters:
obj- ObjectformParams- Form parameterscontentType- Content type headercontentEncoding- Content encoding headerisBodyNullable- Whether the body can be null or not- Returns:
- Entity
-
deserialize
public <T> T deserialize(jakarta.ws.rs.core.Response response, jakarta.ws.rs.core.GenericType<T> returnType) Deserialize response body to Java object according to the Content-Type.- Type Parameters:
T- Type- Parameters:
response- ResponsereturnType- Return type- Returns:
- Deserialize object
-
createBuilder
public jakarta.ws.rs.client.Invocation.Builder createBuilder(String operation, String path, List<Pair> queryParams, Map<String, String> headerParams, Map<String, throws ApiExceptionString> cookieParams, String[] accepts, String[] authNames) Create builder to invoke the API.- Parameters:
operation- The qualified name of the operationpath- The sub-path of the HTTP URLqueryParams- The query parametersheaderParams- The header parameterscookieParams- The cookie parametersaccepts- The list of possible request's Accept headerauthNames- The authentications to apply- Returns:
- The invocation builder
- Throws:
ApiException- API exception
-
invokeAPI
public <T> ApiResponse<T> invokeAPI(String method, jakarta.ws.rs.client.Invocation.Builder invocationBuilder, Map<String, String> headerParams, String[] contentTypes, Object body, Map<String, throws ApiExceptionObject> formParams, Boolean isBodyNullable, jakarta.ws.rs.core.GenericType<T> returnType) Invoke API by sending HTTP request with the given options.- Type Parameters:
T- Type- Parameters:
invocationBuilder- HTTP requests buildermethod- The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE"body- The request body objectheaderParams- The header parametersformParams- The form parameterscontentTypes- The list of request Content-Type headersreturnType- The return type into which to deserialize the responseisBodyNullable- True if the body is nullable- Returns:
- The response body in type of string
- Throws:
ApiException- API exception
-
invokeAPIAsync
public <T> CompletableFuture<ApiResponse<T>> invokeAPIAsync(String method, jakarta.ws.rs.client.Invocation.Builder invocationBuilder, Map<String, String> headerParams, String[] contentTypes, Object body, Map<String, Object> formParams, Boolean isBodyNullable, jakarta.ws.rs.core.GenericType<T> returnType) Invoke API by sending HTTP request with the given options, asynchronously.- Type Parameters:
T- Type- Parameters:
invocationBuilder- HTTP requests buildermethod- The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE"body- The request body objectheaderParams- The header parametersformParams- The form parameterscontentTypes- The list of request Content-Type headersreturnType- The return type into which to deserialize the responseisBodyNullable- True if the body is nullable- Returns:
- The future which be fired with the response
-
buildHttpClient
protected jakarta.ws.rs.client.Client buildHttpClient()Build the Client used to make HTTP requests.- Returns:
- Client
-
getDefaultClientConfig
public org.glassfish.jersey.client.ClientConfig getDefaultClientConfig()Get the default client config.- Returns:
- Client config
-
customizeClientBuilder
protected void customizeClientBuilder(jakarta.ws.rs.client.ClientBuilder clientBuilder) Customize the client builder.This method can be overridden 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).
- Parameters:
clientBuilder- : HTTP client builder
-
disableCertificateValidation
protected void disableCertificateValidation(jakarta.ws.rs.client.ClientBuilder clientBuilder) throws KeyManagementException, NoSuchAlgorithmException 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.
- Parameters:
clientBuilder- : HTTP client builder- Throws:
KeyManagementException- When the SSL context can't be initializedNoSuchAlgorithmException- If the environment doesn't support the required algorithm
-
buildResponseHeaders
-
updateParamsForAuth
protected void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams, Map<String, throws ApiExceptionString> cookieParams, URI uri) Update query and header parameters based on authentication settings.- Parameters:
authNames- The authentications to applyqueryParams- List of query parametersheaderParams- Map of header parameterscookieParams- Map of cookie parametersuri- HTTP URI- Throws:
ApiException- If one of the authentication schemes failed to be applied
-