Package video.api.client.api
Class ApiClient
- java.lang.Object
-
- video.api.client.api.ApiClient
-
public class ApiClient extends Object
-
-
Field Summary
Fields Modifier and Type Field Description static longDEFAULT_CHUNK_SIZEstatic longMAX_CHUNK_SIZEstatic longMIN_CHUNK_SIZE
-
Constructor Summary
Constructors Constructor Description ApiClient(String basePath)Constructor for ApiClient with custom API base path where API key is not required.ApiClient(String apiKey, String basePath)Constructor for ApiClient with custom API base pathApiClient(okhttp3.OkHttpClient client, String basePath)Constructor for ApiClient with custom http client
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description ApiClientaddDefaultCookie(String key, String value)Add a default cookie.ApiClientaddDefaultHeader(String key, String value)Add a default header.okhttp3.CallbuildCall(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String,String> headerParams, Map<String,String> cookieParams, Map<String,Object> formParams, ApiCallback callback)Build HTTP call with the given options.okhttp3.RequestbuildRequest(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String,String> headerParams, Map<String,String> cookieParams, Map<String,Object> formParams, ApiCallback callback)Build an HTTP request with the given options.okhttp3.RequestBodybuildRequestBodyFormEncoding(Map<String,Object> formParams)Build a form-encoding request body with the given form parameters.okhttp3.RequestBodybuildRequestBodyMultipart(Map<String,Object> formParams)Build a multipart (file uploading) request body with the given form parameters, which could contain text fields and file fields.StringbuildUrl(String path, List<Pair> queryParams, List<Pair> collectionQueryParams)Build full URL by concatenating base path, the given sub path and query parameters.StringcollectionPathParameterToString(String collectionFormat, Collection value)Formats the specified collection path parameter to a string value.<T> Tdeserialize(okhttp3.Response response, Type returnType)Deserialize response body to Java object, according to the return type and the Content-Type response header.FiledownloadFileFromResponse(okhttp3.Response response)Download file from the given response.StringescapeString(String str)Escape the given string to be used as URL query value.<T> ApiResponse<T>execute(okhttp3.Call call)<T> ApiResponse<T>execute(okhttp3.Call call, Type returnType)Execute HTTP call and deserialize the HTTP response body into the given return type.<T> voidexecuteAsync(okhttp3.Call call, Type returnType, ApiCallback<T> callback)Execute HTTP call asynchronously.<T> voidexecuteAsync(okhttp3.Call call, ApiCallback<T> callback)StringgetAccessToken()Get access tokenStringgetBasePath()Get base pathintgetConnectTimeout()Get connection timeout (in milliseconds).okhttp3.OkHttpClientgetHttpClient()Get HTTP clientJSONgetJSON()Get JSONKeyManager[]getKeyManagers()intgetReadTimeout()Get read timeout (in milliseconds).InputStreamgetSslCaCert()Get SSL CA cert.longgetUploadChunkSize()intgetWriteTimeout()Get write timeout (in milliseconds).StringguessContentTypeFromFile(File file)Guess Content-Type header from the given file (defaults to "application/octet-stream").<T> ThandleResponse(okhttp3.Response response, Type returnType)Handle the given response, return the deserialized object when the response is successful.booleanhasSdkName()booleanisDebugging()Check that whether debugging is enabled for this API client.booleanisJsonMime(String mime)Check if the given MIME is a JSON MIME.booleanisVerifyingSsl()True if isVerifyingSsl flag is onList<Pair>parameterToPair(String name, Object value)Formats the specified query parameter to a list containing a singlePairobject.List<Pair>parameterToPairs(String collectionFormat, String name, Collection value)Formats the specified collection query parameters to a list ofPairobjects.FileprepareDownloadFile(okhttp3.Response response)Prepare file for downloadvoidprocessCookieParams(Map<String,String> cookieParams, okhttp3.Request.Builder reqBuilder)Set cookie parameters to the request builder, including default cookies.voidprocessHeaderParams(Map<String,String> headerParams, okhttp3.Request.Builder reqBuilder)Set header parameters to the request builder, including default headers.ApiClientremoveDefaultHeader(String key)Remove a default header.StringsanitizeFilename(String filename)Sanitize filename by removing path.StringselectHeaderAccept(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)StringselectHeaderContentType(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.okhttp3.RequestBodyserialize(Object obj, String contentType)Serialize the given Java object into request body according to the object's class and the request Content-Type.voidsetApplicationName(String name, String version)voidsetBasePath(String basePath)Set base pathApiClientsetConnectTimeout(int connectionTimeout)Sets the connect timeout (in milliseconds).ApiClientsetDebugging(boolean debugging)Enable/disable debugging for this API client.ApiClientsetJSON(JSON json)Set JSONApiClientsetKeyManagers(KeyManager[] managers)Configure client keys to use for authorization in an SSL session.ApiClientsetReadTimeout(int readTimeout)Sets the read timeout (in milliseconds).voidsetSdkName(String name, String version)ApiClientsetSslCaCert(InputStream sslCaCert)Configure the CA certificate to be trusted when making https requests.voidsetUploadChunkSize(long uploadChunkSize)ApiClientsetVerifyingSsl(boolean verifyingSsl)Configure whether to verify certificate and hostname when making https requests.ApiClientsetWriteTimeout(int writeTimeout)Sets the write timeout (in milliseconds).
-
-
-
Field Detail
-
DEFAULT_CHUNK_SIZE
public static final long DEFAULT_CHUNK_SIZE
- See Also:
- Constant Field Values
-
MIN_CHUNK_SIZE
public static final long MIN_CHUNK_SIZE
- See Also:
- Constant Field Values
-
MAX_CHUNK_SIZE
public static final long MAX_CHUNK_SIZE
- See Also:
- Constant Field Values
-
-
Constructor Detail
-
ApiClient
public ApiClient(String basePath)
Constructor for ApiClient with custom API base path where API key is not required.- Parameters:
basePath- the api base path. Expected Environment.PRODUCTION.basePath (default) or Environment.SANDBOX.basePath.
-
ApiClient
public ApiClient(String apiKey, String basePath)
Constructor for ApiClient with custom API base path- Parameters:
apiKey- the api key to use to authenticate to the APIbasePath- the api base path. Expected Environment.PRODUCTION.basePath (default) or Environment.SANDBOX.basePath.
-
ApiClient
public ApiClient(okhttp3.OkHttpClient client, String basePath)Constructor for ApiClient with custom http client- Parameters:
client- an OkHttpClient instance used to make API call
-
-
Method Detail
-
hasSdkName
public boolean hasSdkName()
-
getBasePath
public String getBasePath()
Get base path- Returns:
- Base path
-
setBasePath
public void setBasePath(String basePath)
Set base path
-
getAccessToken
public String getAccessToken() throws ApiException
Get access token- Returns:
- Access token
- Throws:
ApiException
-
getHttpClient
public okhttp3.OkHttpClient getHttpClient()
Get HTTP client- Returns:
- An instance of OkHttpClient
-
getJSON
public JSON getJSON()
Get JSON- Returns:
- JSON object
-
setJSON
public ApiClient setJSON(JSON json)
Set JSON- Parameters:
json- JSON object- Returns:
- Api client
-
isVerifyingSsl
public boolean isVerifyingSsl()
True if isVerifyingSsl flag is on- Returns:
- True if isVerifySsl flag is on
-
setVerifyingSsl
public ApiClient setVerifyingSsl(boolean verifyingSsl)
Configure whether to verify certificate and hostname when making https requests. Default to true. NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks.- Parameters:
verifyingSsl- True to verify TLS/SSL connection- Returns:
- ApiClient
-
getSslCaCert
public InputStream getSslCaCert()
Get SSL CA cert.- Returns:
- Input stream to the SSL CA cert
-
setSslCaCert
public ApiClient setSslCaCert(InputStream sslCaCert)
Configure the CA certificate to be trusted when making https requests. Use null to reset to default.- Parameters:
sslCaCert- input stream for SSL CA cert- Returns:
- ApiClient
-
getKeyManagers
public KeyManager[] getKeyManagers()
-
setKeyManagers
public ApiClient setKeyManagers(KeyManager[] managers)
Configure client keys to use for authorization in an SSL session. Use null to reset to default.- Parameters:
managers- The KeyManagers to use- Returns:
- ApiClient
-
addDefaultHeader
public ApiClient addDefaultHeader(String key, String value)
Add a default header.- Parameters:
key- The header's keyvalue- The header's value- Returns:
- ApiClient
-
removeDefaultHeader
public ApiClient removeDefaultHeader(String key)
Remove a default header.- Parameters:
key- The header's key- Returns:
- ApiClient
-
addDefaultCookie
public ApiClient addDefaultCookie(String key, String value)
Add a default cookie.- Parameters:
key- The cookie's keyvalue- The cookie's value- Returns:
- ApiClient
-
isDebugging
public boolean isDebugging()
Check that whether debugging is enabled for this API client.- Returns:
- True if debugging is enabled, false otherwise.
-
setDebugging
public ApiClient setDebugging(boolean debugging)
Enable/disable debugging for this API client.- Parameters:
debugging- To enable (true) or disable (false) debugging- Returns:
- ApiClient
-
getConnectTimeout
public int getConnectTimeout()
Get connection timeout (in milliseconds).- Returns:
- Timeout in milliseconds
-
setConnectTimeout
public ApiClient setConnectTimeout(int connectionTimeout)
Sets 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()
Get read timeout (in milliseconds).- Returns:
- Timeout in milliseconds
-
setReadTimeout
public ApiClient setReadTimeout(int readTimeout)
Sets 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
-
getWriteTimeout
public int getWriteTimeout()
Get write timeout (in milliseconds).- Returns:
- Timeout in milliseconds
-
setWriteTimeout
public ApiClient setWriteTimeout(int writeTimeout)
Sets the write timeout (in milliseconds). A value of 0 means no timeout, otherwise values must be between 1 andInteger.MAX_VALUE.- Parameters:
writeTimeout- connection timeout in milliseconds- Returns:
- Api client
-
parameterToPair
public List<Pair> parameterToPair(String name, Object value)
Formats the specified query parameter to a list containing a singlePairobject. Note thatvaluemust not be a collection.- Parameters:
name- The name of the parameter.value- The value of the parameter.- Returns:
- A list containing a single
Pairobject.
-
parameterToPairs
public List<Pair> parameterToPairs(String collectionFormat, String name, Collection value)
Formats the specified collection query parameters to a list ofPairobjects. 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
Pairobjects.
-
collectionPathParameterToString
public String collectionPathParameterToString(String collectionFormat, Collection value)
Formats the specified collection path parameter to a string value.- Parameters:
collectionFormat- The collection format of the parameter.value- The value of the parameter.- Returns:
- String representation of the parameter
-
sanitizeFilename
public String sanitizeFilename(String filename)
Sanitize filename by removing path. e.g. ../../sun.gif becomes sun.gif- Parameters:
filename- The filename to be sanitized- Returns:
- The sanitized filename
-
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 (Multipurpose Internet Mail Extensions)- Returns:
- True if the given MIME is JSON, false otherwise.
-
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, or matches "any", JSON will be used.
-
escapeString
public String escapeString(String str)
Escape the given string to be used as URL query value.- Parameters:
str- String to be escaped- Returns:
- Escaped string
-
deserialize
public <T> T deserialize(okhttp3.Response response, Type returnType) throws ApiExceptionDeserialize response body to Java object, according to the return type and the Content-Type response header.- Type Parameters:
T- Type- Parameters:
response- HTTP responsereturnType- The type of the Java object- Returns:
- The deserialized Java object
- Throws:
ApiException- If fail to deserialize response body, i.e. cannot read response body or the Content-Type of the response is not supported.
-
serialize
public okhttp3.RequestBody serialize(Object obj, String contentType) throws ApiException
Serialize the given Java object into request body according to the object's class and the request Content-Type.- Parameters:
obj- The Java objectcontentType- The request Content-Type- Returns:
- The serialized request body
- Throws:
ApiException- If fail to serialize the given object
-
downloadFileFromResponse
public File downloadFileFromResponse(okhttp3.Response response) throws ApiException
Download file from the given response.- Parameters:
response- An instance of the Response object- Returns:
- Downloaded file
- Throws:
ApiException- If fail to read file content from response and write to disk
-
prepareDownloadFile
public File prepareDownloadFile(okhttp3.Response response) throws IOException
Prepare file for download- Parameters:
response- An instance of the Response object- Returns:
- Prepared file for the download
- Throws:
IOException- If fail to prepare file for download
-
execute
public <T> ApiResponse<T> execute(okhttp3.Call call) throws ApiException
- Type Parameters:
T- Type- Parameters:
call- An instance of the Call object- Returns:
- ApiResponse<T>
- Throws:
ApiException- If fail to execute the call
-
execute
public <T> ApiResponse<T> execute(okhttp3.Call call, Type returnType) throws ApiException
Execute HTTP call and deserialize the HTTP response body into the given return type.- Type Parameters:
T- The return type corresponding to (same with) returnType- Parameters:
returnType- The return type used to deserialize HTTP response bodycall- Call- Returns:
- ApiResponse object containing response status, headers and data, which is a Java object deserialized from response body and would be null when returnType is null.
- Throws:
ApiException- If fail to execute the call
-
executeAsync
public <T> void executeAsync(okhttp3.Call call, ApiCallback<T> callback)- Type Parameters:
T- Type- Parameters:
call- An instance of the Call objectcallback- ApiCallback<T>
-
executeAsync
public <T> void executeAsync(okhttp3.Call call, Type returnType, ApiCallback<T> callback)Execute HTTP call asynchronously.- Type Parameters:
T- Type- Parameters:
call- The callback to be executed when the API call finishesreturnType- Return typecallback- ApiCallback- See Also:
execute(Call, Type)
-
handleResponse
public <T> T handleResponse(okhttp3.Response response, Type returnType) throws ApiExceptionHandle the given response, return the deserialized object when the response is successful.- Type Parameters:
T- Type- Parameters:
response- ResponsereturnType- Return type- Returns:
- Type
- Throws:
ApiException- If the response has an unsuccessful status code or fail to deserialize the response body
-
buildCall
public okhttp3.Call buildCall(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String,String> headerParams, Map<String,String> cookieParams, Map<String,Object> formParams, ApiCallback callback) throws ApiException
Build HTTP call with the given options.- Parameters:
path- The sub-path of the HTTP URLmethod- The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"queryParams- The query parameterscollectionQueryParams- The collection query parametersbody- The request body objectheaderParams- The header parameterscookieParams- The cookie parametersformParams- The form parameterscallback- Callback for upload/download progress- Returns:
- The HTTP call
- Throws:
ApiException- If fail to serialize the request body object
-
buildRequest
public okhttp3.Request buildRequest(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String,String> headerParams, Map<String,String> cookieParams, Map<String,Object> formParams, ApiCallback callback) throws ApiException
Build an HTTP request with the given options.- Parameters:
path- The sub-path of the HTTP URLmethod- The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"queryParams- The query parameterscollectionQueryParams- The collection query parametersbody- The request body objectheaderParams- The header parameterscookieParams- The cookie parametersformParams- The form parameterscallback- Callback for upload/download progress- Returns:
- The HTTP request
- Throws:
ApiException- If fail to serialize the request body object
-
buildUrl
public String buildUrl(String path, List<Pair> queryParams, List<Pair> collectionQueryParams)
Build full URL by concatenating base path, the given sub path and query parameters.- Parameters:
path- The sub pathqueryParams- The query parameterscollectionQueryParams- The collection query parameters- Returns:
- The full URL
-
processHeaderParams
public void processHeaderParams(Map<String,String> headerParams, okhttp3.Request.Builder reqBuilder)
Set header parameters to the request builder, including default headers.- Parameters:
headerParams- Header parameters in the form of MapreqBuilder- Request.Builder
-
processCookieParams
public void processCookieParams(Map<String,String> cookieParams, okhttp3.Request.Builder reqBuilder)
Set cookie parameters to the request builder, including default cookies.- Parameters:
cookieParams- Cookie parameters in the form of MapreqBuilder- Request.Builder
-
buildRequestBodyFormEncoding
public okhttp3.RequestBody buildRequestBodyFormEncoding(Map<String,Object> formParams)
Build a form-encoding request body with the given form parameters.- Parameters:
formParams- Form parameters in the form of Map- Returns:
- RequestBody
-
buildRequestBodyMultipart
public okhttp3.RequestBody buildRequestBodyMultipart(Map<String,Object> formParams)
Build a multipart (file uploading) request body with the given form parameters, which could contain text fields and file fields.- Parameters:
formParams- Form parameters in the form of Map- Returns:
- RequestBody
-
guessContentTypeFromFile
public String guessContentTypeFromFile(File file)
Guess Content-Type header from the given file (defaults to "application/octet-stream").- Parameters:
file- The given file- Returns:
- The guessed Content-Type
-
getUploadChunkSize
public long getUploadChunkSize()
-
setUploadChunkSize
public void setUploadChunkSize(long uploadChunkSize)
-
-