Class ApiClient


  • public class ApiClient
    extends Object
    ApiClient class.
    • Field Detail

      • PRODUCTION_REST_BASEPATH

        public static final String PRODUCTION_REST_BASEPATH
        live/production base path.
        See Also:
        Constant Field Values
      • debugging

        protected boolean debugging
      • connectionTimeout

        protected int connectionTimeout
      • httpClient

        protected jakarta.ws.rs.client.Client httpClient
      • json

        protected JSON json
      • tempFolderPath

        protected String tempFolderPath
    • Constructor Detail

      • ApiClient

        public ApiClient()
        ApiClient constructor.
      • ApiClient

        public ApiClient​(String basePath)
        ApiClient constructor.
        Parameters:
        basePath - The base path to create the client with
      • ApiClient

        public ApiClient​(String oAuthBasePath,
                         String[] authNames)
        ApiClient constructor.
        Parameters:
        oAuthBasePath - The base path to create the client with
        authNames - The authentication names
      • ApiClient

        public ApiClient​(String oAuthBasePath,
                         String authName)
        Basic constructor for single auth name.
        Parameters:
        oAuthBasePath - the basepath
        authName - the auth name
      • ApiClient

        public ApiClient​(String oAuthBasePath,
                         String authName,
                         String clientId,
                         String secret)
        Helper constructor for OAuth2.
        Parameters:
        oAuthBasePath - The API base path
        authName - the authentication method name ("oauth" or "api_key")
        clientId - OAuth2 Client ID
        secret - OAuth2 Client secret
    • Method Detail

      • buildDefaultDateFormat

        public static DateFormat buildDefaultDateFormat()
        buildDefaultDateFormat method.
        Returns:
        DateFormat
      • rebuildHttpClient

        public ApiClient rebuildHttpClient()
        Build the Client used to make HTTP requests with the latest settings, i.e. objectMapper and debugging. TODO: better to use the Builder Pattern?
        Returns:
        API client
      • getObjectMapper

        public com.fasterxml.jackson.databind.ObjectMapper getObjectMapper()
        Returns the current object mapper used for JSON serialization/deserialization.

        Note: If you make changes to the object mapper, remember to set it back via setObjectMapper in order to trigger HTTP client rebuilding.

        Returns:
        Object mapper
      • setObjectMapper

        public ApiClient setObjectMapper​(com.fasterxml.jackson.databind.ObjectMapper objectMapper)
        Set the object mapper of client.
        Returns:
        API client
      • getJSON

        public JSON getJSON()
        Gets the JSON instance to do JSON serialization and deserialization.
        Returns:
        JSON
      • getHttpClient

        public jakarta.ws.rs.client.Client getHttpClient()
        Gets the API client.
        Returns:
        Client
      • setHttpClient

        public ApiClient setHttpClient​(jakarta.ws.rs.client.Client httpClient)
        Sets the API client.
        Returns:
        ApiClient
      • getBasePath

        public String getBasePath()
        Gets the basepath.
        Returns:
        String
      • setBasePath

        public ApiClient setBasePath​(String basePath)
        Sets the basepath.
        Returns:
        ApiClient
      • getStatusCode

        public int getStatusCode()
        Gets the status code of the previous request.
        Returns:
        Status code
      • getResponseHeaders

        public Map<String,​List<String>> getResponseHeaders()
        Gets the response headers of the previous request.
        Returns:
        Response headers
      • getAuthentications

        public Map<String,​Authentication> getAuthentications()
        Get authentications (key: authentication name, value: authentication).
        Returns:
        Map of authentication object
      • getAuthentication

        public Authentication getAuthentication​(String authName)
        Get authentication for the given name.
        Parameters:
        authName - The authentication name
        Returns:
        The authentication, null if not found
      • addAuthorization

        public void addAuthorization​(String authName,
                                     Authentication auth)
        Adds authorization.
      • setUsername

        public void setUsername​(String username)
        Helper method to set username for the first HTTP basic authentication.
        Parameters:
        username - Username
      • setPassword

        public void setPassword​(String password)
        Helper method to set password for the first HTTP basic authentication.
        Parameters:
        password - Password
      • setApiKey

        public void setApiKey​(String apiKey)
        Helper method to set API key value for the first API key authentication.
        Parameters:
        apiKey - API key
      • setApiKeyPrefix

        public void setApiKeyPrefix​(String apiKeyPrefix)
        Helper method to set API key prefix for the first API key authentication.
        Parameters:
        apiKeyPrefix - API key prefix
      • updateAccessToken

        public void updateAccessToken()
        Helper method to set access token for the first OAuth2 authentication.
      • setAccessToken

        public void setAccessToken​(String accessToken,
                                   Long expiresIn)
        Helper method to preset the OAuth access token of the first OAuth found in the apiAuthorizations (there should be only one).
        Parameters:
        accessToken - OAuth access token
        expiresIn - Validity period of the access token in seconds
      • getAccessToken

        public String getAccessToken()
        Gets the access token.
        Returns:
        String
      • setUserAgent

        public ApiClient setUserAgent​(String userAgent)
        Set the User-Agent header's value (by adding to the default header map).
        Parameters:
        userAgent - Http user agent
        Returns:
        API client
      • addDefaultHeader

        public ApiClient addDefaultHeader​(String key,
                                          String value)
        Add a default header.
        Parameters:
        key - The header's key
        value - The header's value
        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

        public ApiClient setDebugging​(boolean debugging)
        Enable/disable debugging for this API client.
        Parameters:
        debugging - To enable (true) or disable (false) debugging
        Returns:
        API client
      • getTempFolderPath

        public String getTempFolderPath()
        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.
        Returns:
        Temp folder path
      • setTempFolderPath

        public ApiClient setTempFolderPath​(String tempFolderPath)
        Set temp folder path.
        Parameters:
        tempFolderPath - Temp folder path
        Returns:
        API client
      • getConnectTimeout

        public int getConnectTimeout()
        Connect timeout (in milliseconds).
        Returns:
        Connection timeout
      • setConnectTimeout

        public ApiClient setConnectTimeout​(int connectionTimeout)
        Set the connect timeout (in milliseconds). A value of 0 means no timeout, otherwise values must be between 1 and Integer.MAX_VALUE.
        Parameters:
        connectionTimeout - Connection timeout in milliseconds
        Returns:
        API client
      • getReadTimeout

        public int getReadTimeout()
        read timeout (in milliseconds).
        Returns:
        Read timeout
      • setReadTimeout

        public ApiClient setReadTimeout​(int readTimeout)
        Set the read timeout (in milliseconds). A value of 0 means no timeout, otherwise values must be between 1 and Integer.MAX_VALUE.
        Parameters:
        readTimeout - Read timeout in milliseconds
        Returns:
        API client
      • getDateFormat

        public DateFormat getDateFormat()
        Get the date format used to parse/format date parameters.
        Returns:
        Date format
      • setDateFormat

        public ApiClient setDateFormat​(DateFormat dateFormat)
        Set the date format used to parse/format date parameters.
        Parameters:
        dateFormat - Date format
        Returns:
        API client
      • getTokenEndPoint

        public org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder getTokenEndPoint()
        Helper method to configure the token endpoint of the first oauth found in the authentications (there should be only one).
        Returns:
      • getAuthorizationEndPoint

        public org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder getAuthorizationEndPoint()
        Helper method to configure authorization endpoint of the first oauth found in the authentications (there should be only one).
        Returns:
      • configureAuthorizationFlow

        public void configureAuthorizationFlow​(String clientId,
                                               String clientSecret,
                                               String redirectURI)
        Helper method to configure the OAuth accessCode/implicit flow parameters.
        Parameters:
        clientId - OAuth2 client ID
        clientSecret - OAuth2 client secret
        redirectURI - OAuth2 redirect uri
      • getAuthorizationUri

        public String getAuthorizationUri()
                                   throws org.apache.oltu.oauth2.common.exception.OAuthSystemException
        Throws:
        org.apache.oltu.oauth2.common.exception.OAuthSystemException
      • getAuthorizationUri

        public URI getAuthorizationUri​(String clientId,
                                       List<String> scopes,
                                       String redirectUri,
                                       String responseType,
                                       String state)
                                throws IllegalArgumentException,
                                       jakarta.ws.rs.core.UriBuilderException
        Helper method to configure the OAuth accessCode/implicit flow parameters.
        Parameters:
        clientId - OAuth2 client ID: Identifies the client making the request. Client applications may be scoped to a limited set of system access.
        scopes - the list of requested scopes. Values include OAuth.Scope_SIGNATURE, OAuth.Scope_EXTENDED, OAuth.Scope_IMPERSONATION. You can also pass any advanced scope.
        redirectUri - this determines where to deliver the response containing the authorization code or access token.
        responseType - determines the response type of the authorization request.
        Note: these response types are mutually exclusive for a client application. A public/native client application may only request a response type of "token"; a private/trusted client application may only request a response type of "code".
        state - Allows for arbitrary state that may be useful to your application. The value in this parameter will be round-tripped along with the response so you can make sure it didn't change.
        Throws:
        IllegalArgumentException
        jakarta.ws.rs.core.UriBuilderException
      • getAuthorizationUri

        public URI getAuthorizationUri​(String clientId,
                                       List<String> scopes,
                                       String redirectUri,
                                       String responseType)
                                throws IllegalArgumentException,
                                       jakarta.ws.rs.core.UriBuilderException
        Helper method to configure the OAuth accessCode/implicit flow parameters.
        Parameters:
        clientId - OAuth2 client ID: Identifies the client making the request. Client applications may be scoped to a limited set of system access.
        scopes - the list of requested scopes. Values include OAuth.Scope_SIGNATURE, OAuth.Scope_EXTENDED, OAuth.Scope_IMPERSONATION. You can also pass any advanced scope.
        redirectUri - this determines where to deliver the response containing the authorization code or access token.
        responseType - determines the response type of the authorization request.
        Note: these response types are mutually exclusive for a client application. A public/native client application may only request a response type of "token"; a private/trusted client application may only request a response type of "code".
        Throws:
        IllegalArgumentException
        jakarta.ws.rs.core.UriBuilderException
      • setOAuthBasePath

        public ApiClient setOAuthBasePath​(String oAuthBasePath)
        Sets the OAuth base path. Values include OAuth.PRODUCTION_OAUTH_BASEPATH, OAuth.DEMO_OAUTH_BASEPATH and custom (e.g. "account-s.docusign.com").
        Parameters:
        oAuthBasePath - the new value for the OAuth base path
        Returns:
        this instance of the ApiClient updated with the new OAuth base path
      • generateAccessToken

        public OAuth.OAuthToken generateAccessToken​(String clientId,
                                                    String clientSecret,
                                                    String code)
                                             throws ApiException,
                                                    IOException
        Helper method to configure the OAuth accessCode/implicit flow parameters.
        Parameters:
        clientId - OAuth2 client ID: Identifies the client making the request. Client applications may be scoped to a limited set of system access.
        clientSecret - the secret key you generated when you set up the integration in DocuSign Admin console.
        code - The authorization code that you received from the getAuthorizationUri callback.
        Returns:
        OAuth.OAuthToken object.
        Throws:
        ApiException - if the HTTP call status is different than 2xx.
        IOException - if there is a problem while parsing the reponse object.
        See Also:
        OAuth.OAuthToken
      • registerAccessTokenListener

        public void registerAccessTokenListener​(AccessTokenListener accessTokenListener)
        Configures a listener which is notified when a new access token is received.
        Parameters:
        accessTokenListener - access token listener
      • getJWTUri

        public String getJWTUri​(String clientId,
                                String redirectURI,
                                String oAuthBasePath)
        Helper method to build the OAuth JWT grant uri (used once to get a user consent for impersonation).
        Parameters:
        clientId - OAuth2 client ID
        redirectURI - OAuth2 redirect uri
        Returns:
        the OAuth JWT grant uri as a String
      • configureJWTAuthorizationFlow

        @Deprecated
        public void configureJWTAuthorizationFlow​(String publicKeyFilename,
                                                  String privateKeyFilename,
                                                  String oAuthBasePath,
                                                  String clientId,
                                                  String userId,
                                                  long expiresIn)
                                           throws ApiException,
                                                  IOException
        Configures the current instance of ApiClient with a fresh OAuth JWT access token from DocuSign.
        Parameters:
        publicKeyFilename - the filename of the RSA public key
        privateKeyFilename - the filename of the RSA private key
        oAuthBasePath - DocuSign OAuth base path (account-d.docusign.com for the developer sandbox and account.docusign.com for the production platform)
        clientId - DocuSign OAuth Client Id (AKA Integrator Key)
        userId - DocuSign user Id to be impersonated (This is a UUID)
        expiresIn - number of seconds remaining before the JWT assertion is considered as invalid
        Throws:
        ApiException - if there is an error while exchanging the JWT with an access token
        IOException - if there is an issue with either the public or private file
      • requestJWTUserToken

        public OAuth.OAuthToken requestJWTUserToken​(String clientId,
                                                    String userId,
                                                    List<String> scopes,
                                                    byte[] rsaPrivateKey,
                                                    long expiresIn)
                                             throws IllegalArgumentException,
                                                    ApiException,
                                                    IOException
        Configures the current instance of ApiClient with a fresh OAuth JWT access token from DocuSign.
        Parameters:
        clientId - DocuSign OAuth Client Id (AKA Integrator Key)
        userId - DocuSign user Id to be impersonated (This is a UUID)
        scopes - the list of requested scopes. Values include OAuth.Scope_SIGNATURE, OAuth.Scope_EXTENDED, OAuth.Scope_IMPERSONATION. You can also pass any advanced scope.
        rsaPrivateKey - the byte contents of the RSA private key
        expiresIn - number of seconds remaining before the JWT assertion is considered as invalid
        Returns:
        OAuth.OAuthToken object.
        Throws:
        IllegalArgumentException - if one of the arguments is invalid
        ApiException - if there is an error while exchanging the JWT with an access token
        IOException - if there is an issue with either the public or private file
      • requestJWTApplicationToken

        public OAuth.OAuthToken requestJWTApplicationToken​(String clientId,
                                                           List<String> scopes,
                                                           byte[] rsaPrivateKey,
                                                           long expiresIn)
                                                    throws IllegalArgumentException,
                                                           IOException,
                                                           ApiException
        RESERVED FOR PARTNERS Request JWT Application Token. Configures the current instance of ApiClient with a fresh OAuth JWT access token from DocuSign
        Parameters:
        clientId - DocuSign OAuth Client Id (AKA Integrator Key)
        scopes - the list of requested scopes. Values include OAuth.Scope_SIGNATURE, OAuth.Scope_EXTENDED, OAuth.Scope_IMPERSONATION. You can also pass any advanced scope.
        rsaPrivateKey - the byte contents of the RSA private key
        expiresIn - number of seconds remaining before the JWT assertion is considered as invalid
        Returns:
        OAuth.OAuthToken object.
        Throws:
        IllegalArgumentException - if one of the arguments is invalid
        IOException - if there is an issue with either the public or private file
        ApiException - if there is an error while exchanging the JWT with an access token
      • parseDate

        public Date parseDate​(String str)
        Parse the given string into Date object.
        Parameters:
        str - String
        Returns:
        Date
      • formatDate

        public String formatDate​(Date date)
        Format the given Date object into string.
        Parameters:
        date - Date
        Returns:
        Date in string format
      • parameterToString

        public String parameterToString​(Object param)
        Format the given parameter object into string.
        Parameters:
        param - Object
        Returns:
        Object in string format
      • parameterToPair

        public List<Pair> parameterToPair​(String name,
                                          Object value)
        Formats the specified query parameter to a list containing a single Pair object.

        Note that value must not be a collection.

        Parameters:
        name - The name of the parameter.
        value - The value of the parameter.
        Returns:
        A list containing a single Pair object.
      • parameterToPairs

        public List<Pair> parameterToPairs​(String collectionFormat,
                                           String name,
                                           Collection value)
        Formats the specified collection query parameters to a list of Pair objects.

        Note that the values of each of the returned Pair objects are percent-encoded.

        Parameters:
        collectionFormat - The collection format of the parameter.
        name - The name of the parameter.
        value - The value of the parameter.
        Returns:
        A list of Pair objects.
      • parameterToPairs

        public List<Pair> parameterToPairs​(String collectionFormat,
                                           String name,
                                           Object value)
        Format to Pair objects.
        Parameters:
        collectionFormat - Collection format
        name - Name
        value - Value
        Returns:
        List of pairs
      • isJsonMime

        public boolean isJsonMime​(String mime)
        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

        public 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).
        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

        public 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.
        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

        public String escapeString​(String str)
        Escape the given string to be used as URL query value.
        Parameters:
        str - String
        Returns:
        Escaped string
      • serialize

        public Object serialize​(Object obj,
                                String contentType,
                                Map<String,​Object> formParams)
                         throws ApiException
        Serialize the given Java object into string according the given Content-Type (only JSON is supported for now).
        Parameters:
        obj - Object
        contentType - Content type
        formParams - Form parameters
        Returns:
        Object
        Throws:
        ApiException - API exception
      • serialize

        public jakarta.ws.rs.client.Entity<?> serialize​(Object obj,
                                                        Map<String,​Object> formParams,
                                                        String contentType)
                                                 throws ApiException
        Serialize the given Java object into string entity according the given Content-Type (only JSON is supported for now).
        Parameters:
        obj - Object
        formParams - Form parameters
        contentType - Context type
        Returns:
        Entity
        Throws:
        ApiException - API exception
      • deserialize

        public <T> T deserialize​(jakarta.ws.rs.core.Response response,
                                 jakarta.ws.rs.core.GenericType<T> returnType)
                          throws ApiException
        Deserialize response body to Java object according to the Content-Type.
        Type Parameters:
        T - Type
        Parameters:
        response - Response
        returnType - Return type
        Returns:
        Deserialize object
        Throws:
        ApiException - API exception
      • downloadFileFromResponse

        public File downloadFileFromResponse​(jakarta.ws.rs.core.Response response)
                                      throws ApiException
        Download file from the given response.
        Parameters:
        response - Response
        Returns:
        File
        Throws:
        ApiException - If fail to read file content from response and write to disk
      • prepareDownloadFile

        public File prepareDownloadFile​(jakarta.ws.rs.core.Response response)
                                 throws IOException
        Prepare to downloand file.
        Parameters:
        response - Response
        Returns:
        File
        Throws:
        ApiException - If fail to read file content from response and write to disk
        IOException
      • invokeAPI

        public <T> T invokeAPI​(String path,
                               String method,
                               List<Pair> queryParams,
                               List<Pair> collectionQueryParams,
                               Object body,
                               Map<String,​String> headerParams,
                               Map<String,​Object> formParams,
                               String accept,
                               String contentType,
                               String[] authNames,
                               jakarta.ws.rs.core.GenericType<T> returnType)
                        throws ApiException
        Invoke API by sending HTTP request with the given options.
        Type Parameters:
        T - Type
        Parameters:
        path - The sub-path of the HTTP URL
        method - The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE"
        queryParams - The query parameters
        collectionQueryParams - The collection query parameters
        body - The request body object
        headerParams - The header parameters
        formParams - The form parameters
        accept - The request's Accept header
        contentType - The request's Content-Type header
        authNames - The authentications to apply
        returnType - The return type into which to deserialize the response
        Returns:
        The response body in type of string
        Throws:
        ApiException - API exception
      • buildHttpClient

        protected jakarta.ws.rs.client.Client buildHttpClient​(boolean debugging)
        Build the Client used to make HTTP requests.
        Parameters:
        debugging - Debug setting
        Returns:
        Client
      • performAdditionalClientConfiguration

        protected void performAdditionalClientConfiguration​(org.glassfish.jersey.client.ClientConfig clientConfig)
      • buildResponseHeaders

        protected Map<String,​List<String>> buildResponseHeaders​(jakarta.ws.rs.core.Response response)
      • updateParamsForAuth

        protected void updateParamsForAuth​(String[] authNames,
                                           List<Pair> queryParams,
                                           Map<String,​String> headerParams)
        Update query and header parameters based on authentication settings.
        Parameters:
        authNames - The authentications to apply