public class BoxAPIConnection extends Object
This class handles storing authentication information, automatic token refresh, and rate-limiting. It can also be used to configure the Box API endpoint URL in order to hit a different version of the API. Multiple instances of BoxAPIConnection may be created to support multi-user login.
Modifier and Type | Class and Description |
---|---|
protected static class |
BoxAPIConnection.ResourceLinkType
Used to categorize the types of resource links.
|
Modifier and Type | Field and Description |
---|---|
protected static String |
DEFAULT_BASE_AUTHORIZATION_URL
Default authorization URL
|
static HostnameVerifier |
DEFAULT_HOSTNAME_VERIFIER
Used as a marker to setup connection to use default HostnameVerifier
Example:
|
static int |
DEFAULT_MAX_RETRIES
The default maximum number of times an API request will be retried after an error response
is received.
|
static X509TrustManager |
DEFAULT_TRUST_MANAGER
Used as a marker to setup connection to use default HostnameVerifier
Example:
|
Constructor and Description |
---|
BoxAPIConnection(BoxConfig boxConfig)
Constructs a new BoxAPIConnection levaraging BoxConfig.
|
BoxAPIConnection(String accessToken)
Constructs a new BoxAPIConnection that authenticates with a developer or access token.
|
BoxAPIConnection(String clientID,
String clientSecret)
Constructs a new BoxAPIConnection.
|
BoxAPIConnection(String clientID,
String clientSecret,
String authCode)
Constructs a new BoxAPIConnection with an auth code that was obtained from the first half of OAuth.
|
BoxAPIConnection(String clientID,
String clientSecret,
String accessToken,
String refreshToken)
Constructs a new BoxAPIConnection with an access token that can be refreshed.
|
Modifier and Type | Method and Description |
---|---|
void |
addListener(BoxAPIConnectionListener listener)
Add a listener to listen to Box API connection events.
|
void |
asSelf()
Sets this API connection to make API calls on behalf of the user with whom the access token is associated.
|
void |
asUser(String userID)
Set this API connection to make API calls on behalf of another users, impersonating them.
|
void |
authenticate(String authCode)
Authenticates the API connection by obtaining access and refresh tokens using the auth code that was obtained
from the first half of OAuth.
|
boolean |
canRefresh()
Determines if this connection's access token can be refreshed.
|
void |
configureSslCertificatesValidation(X509TrustManager trustManager,
HostnameVerifier hostnameVerifier)
Used to override default SSL certification handling.
|
protected Call |
createNewCall(OkHttpClient httpClient,
Request request) |
protected BoxAPIRequest |
createTokenRequest(URL url) |
protected BoxAPIConnection.ResourceLinkType |
determineResourceLinkType(String resourceLink)
Determines the type of resource, given a link to a Box resource.
|
void |
enableNotifications()
Re-enable email notifications from API actions if they have been suppressed.
|
protected void |
extractTokens(JsonObject jsonObject) |
String |
getAccessToken()
Gets an access token that can be used to authenticate an API request.
|
static URL |
getAuthorizationURL(String clientID,
URI redirectUri,
String state,
List<String> scopes)
Returns the default authorization URL which is used to perform the authorization_code based OAuth2 flow.
|
URL |
getAuthorizationURL(URI redirectUri,
String state,
List<String> scopes)
Returns the authorization URL which is used to perform the authorization_code based OAuth2 flow.
|
boolean |
getAutoRefresh()
Gets whether or not automatic refreshing of this connection's access token is enabled.
|
String |
getBaseAppUrl()
Gets the base App url.
|
String |
getBaseUploadURL()
Gets the base upload URL that's used when performing file uploads to Box.
|
String |
getBaseURL()
Gets the base URL that's used when sending requests to the Box API.
|
String |
getClientID()
Gets the client ID.
|
String |
getClientSecret()
Gets the client secret.
|
int |
getConnectTimeout()
Gets the connect timeout for this connection in milliseconds.
|
long |
getExpires()
Gets the amount of time for which this connection's access token is valid.
|
protected HostnameVerifier |
getHostnameVerifier() |
protected String |
getKeyValueOrDefault(JsonObject json,
String key,
String defaultValue) |
long |
getLastRefresh()
Gets the last time that the access token was refreshed.
|
ScopedToken |
getLowerScopedToken(List<String> scopes,
String resource)
Get a lower-scoped token restricted to a resource for the list of scopes that are passed.
|
int |
getMaxRetryAttempts()
Gets the maximum number of times an API request will be retried after an error response
is received.
|
Proxy |
getProxy()
Gets the proxy value to use for API calls to Box.
|
String |
getProxyPassword()
Gets the password to use for a proxy that requires basic auth.
|
String |
getProxyUsername()
Gets the username to use for a proxy that requires basic auth.
|
int |
getReadTimeout()
Gets the read timeout for this connection in milliseconds.
|
protected ReadWriteLock |
getRefreshLock()
Gets the refresh lock to be used when refreshing an access token.
|
String |
getRefreshToken()
Gets a refresh token that can be used to refresh an access token.
|
RequestInterceptor |
getRequestInterceptor()
Gets the RequestInterceptor associated with this API connection.
|
String |
getRevokeURL()
Returns the URL used for token revocation.
|
String |
getTokenURL()
Gets the token URL that's used to request access tokens.
|
protected X509TrustManager |
getTrustManager() |
String |
getUserAgent()
Gets the user agent that's used when sending requests to the Box API.
|
protected OkHttpClient.Builder |
modifyHttpClientBuilder(OkHttpClient.Builder httpClientBuilder)
Can be used to modify OkHttp.Builder used to create connection.
|
boolean |
needsRefresh()
Determines if this connection's access token has expired and needs to be refreshed.
|
protected void |
notifyError(BoxAPIException error)
Notifies an error event to all the listeners.
|
protected void |
notifyRefresh()
Notifies a refresh event to all the listeners.
|
void |
refresh()
Refresh's this connection's access token using its refresh token.
|
void |
removeCustomHeader(String header)
Removes a custom header, so it will no longer be sent on requests through this API connection.
|
void |
removeListener(BoxAPIConnectionListener listener)
Remove a listener listening to Box API connection events.
|
void |
restore(String state)
Restores a saved connection state into this BoxAPIConnection.
|
static BoxAPIConnection |
restore(String clientID,
String clientSecret,
String state)
Restores a BoxAPIConnection from a saved state.
|
void |
revokeToken()
Revokes the tokens associated with this API connection.
|
String |
save()
Saves the state of this connection to a string so that it can be persisted and restored at a later time.
|
void |
setAccessToken(String accessToken)
Sets the access token to use when authenticating API requests.
|
void |
setAutoRefresh(boolean autoRefresh)
Enables or disables automatic refreshing of this connection's access token.
|
void |
setBaseAppUrl(String baseAppURL)
Sets the base App url.
|
void |
setBaseAuthorizationURL(String baseAuthorizationURL)
Sets authorization base URL which is used to perform the authorization_code based OAuth2 flow.
|
void |
setBaseUploadURL(String baseUploadURL)
Sets the base upload URL to be used when performing file uploads to Box.
|
void |
setBaseURL(String baseURL)
Sets the base URL to be used when sending requests to the Box API.
|
void |
setConnectTimeout(int connectTimeout)
Sets the connect timeout for this connection.
|
void |
setCustomHeader(String header,
String value)
Sets a custom header to be sent on all requests through this API connection.
|
void |
setExpires(long milliseconds)
Sets the amount of time for which this connection's access token is valid before it must be refreshed.
|
void |
setLastRefresh(long lastRefresh)
Sets the last time that the access token was refreshed.
|
void |
setMaxRetryAttempts(int attempts)
Sets the maximum number of times an API request will be retried after an error response
is received.
|
void |
setProxy(Proxy proxy)
Sets the proxy to use for API calls to Box.
|
void |
setProxyAuthenticator(Authenticator authenticator)
Sets a proxy authenticator that will be used when proxy requires authentication.
|
void |
setProxyBasicAuthentication(String proxyUsername,
String proxyPassword)
Sets the proxy user and password used in basic authentication
|
void |
setProxyPassword(String proxyPassword)
Deprecated.
|
void |
setProxyUsername(String proxyUsername)
Deprecated.
|
void |
setReadTimeout(int readTimeout)
Sets the read timeout for this connection.
|
void |
setRefreshToken(String refreshToken)
Sets the refresh token to use when refreshing an access token.
|
void |
setRequestInterceptor(RequestInterceptor interceptor)
Sets a RequestInterceptor that can intercept requests and manipulate them before they're sent to the Box API.
|
void |
setUserAgent(String userAgent)
Sets the user agent to be used when sending requests to the Box API.
|
void |
suppressNotifications()
Suppresses email notifications from API actions.
|
public static final X509TrustManager DEFAULT_TRUST_MANAGER
BoxApiConnection api = new BoxApiConnection(...);
HostnameVerifier myHostnameVerifier = ...
api.configureSslCertificatesValidation(DEFAULT_TRUST_MANAGER, myHostnameVerifier);
public static final HostnameVerifier DEFAULT_HOSTNAME_VERIFIER
BoxApiConnection api = new BoxApiConnection(...);
X509TrustManager myTrustManager = ...
api.configureSslCertificatesValidation(myTrustManager, DEFAULT_HOSTNAME_VERIFIER);
public static final int DEFAULT_MAX_RETRIES
protected static final String DEFAULT_BASE_AUTHORIZATION_URL
public BoxAPIConnection(String accessToken)
accessToken
- a developer or access token to use for authenticating with the API.public BoxAPIConnection(String clientID, String clientSecret, String accessToken, String refreshToken)
clientID
- the client ID to use when refreshing the access token.clientSecret
- the client secret to use when refreshing the access token.accessToken
- an initial access token to use for authenticating with the API.refreshToken
- an initial refresh token to use when refreshing the access token.public BoxAPIConnection(String clientID, String clientSecret, String authCode)
clientID
- the client ID to use when exchanging the auth code for an access token.clientSecret
- the client secret to use when exchanging the auth code for an access token.authCode
- an auth code obtained from the first half of the OAuth process.public BoxAPIConnection(String clientID, String clientSecret)
clientID
- the client ID to use when exchanging the auth code for an access token.clientSecret
- the client secret to use when exchanging the auth code for an access token.public BoxAPIConnection(BoxConfig boxConfig)
boxConfig
- BoxConfig file, which should have clientId and clientSecretprotected OkHttpClient.Builder modifyHttpClientBuilder(OkHttpClient.Builder httpClientBuilder)
httpClientBuilder
- Builder that will be used to create http connection.public void setProxyAuthenticator(Authenticator authenticator)
setProxyBasicAuthentication(String, String)
it adds an authenticator
that performs Basic authorization. By calling this method you can override this behaviour.
You do not need to call setProxyBasicAuthentication(String, String)
in order to set custom authenticator.authenticator
- Custom authenticator that will be called when proxy asks for authorization.public static BoxAPIConnection restore(String clientID, String clientSecret, String state)
public static URL getAuthorizationURL(String clientID, URI redirectUri, String state, List<String> scopes)
getAuthorizationURL(java.lang.String, java.net.URI, java.lang.String, java.util.List<java.lang.String>)
clientID
- the client ID to use with the connection.redirectUri
- the URL to which Box redirects the browser when authentication completes.state
- the text string that you choose.
Box sends the same string to your redirect URL when authentication is complete.scopes
- this optional parameter identifies the Box scopes available
to the application once it's authenticated.public void authenticate(String authCode)
authCode
- the auth code obtained from the first half of the OAuth process.public String getClientID()
public String getClientSecret()
public long getExpires()
public void setExpires(long milliseconds)
milliseconds
- the number of milliseconds for which the access token is valid.public String getTokenURL()
baseURL
and TOKEN_URL_SUFFIX
.public String getRevokeURL()
baseURL
and REVOKE_URL_SUFFIX
.public String getBaseURL()
baseURL
and API_VERSION
.
The default value is "https://api.box.com/2.0/".public void setBaseURL(String baseURL)
getRevokeURL()
and getTokenURL()
are constructed.baseURL
- a base URLpublic String getBaseUploadURL()
baseUploadURL
and API_VERSION
.public void setBaseUploadURL(String baseUploadURL)
baseUploadURL
- a base upload URL.public URL getAuthorizationURL(URI redirectUri, String state, List<String> scopes)
baseAuthorizationURL
and OAUTH_SUFFIX
.redirectUri
- the URL to which Box redirects the browser when authentication completes.state
- the text string that you choose.
Box sends the same string to your redirect URL when authentication is complete.scopes
- this optional parameter identifies the Box scopes available
to the application once it's authenticated.public void setBaseAuthorizationURL(String baseAuthorizationURL)
baseAuthorizationURL
- Authorization URL. Default value is https://account.box.com/api/.public String getUserAgent()
public void setUserAgent(String userAgent)
userAgent
- the user agent.public String getBaseAppUrl()
public void setBaseAppUrl(String baseAppURL)
baseAppURL
- a base App Url.public String getAccessToken()
getAccessToken()
.public void setAccessToken(String accessToken)
accessToken
- a valid access token to use when authenticating API requests.protected ReadWriteLock getRefreshLock()
public String getRefreshToken()
public void setRefreshToken(String refreshToken)
refreshToken
- a valid refresh token.public long getLastRefresh()
public void setLastRefresh(long lastRefresh)
This value is used when determining if an access token needs to be auto-refreshed. If the amount of time since the last refresh exceeds the access token's expiration time, then the access token will be refreshed.
lastRefresh
- the new last refresh time in milliseconds.public boolean getAutoRefresh()
public void setAutoRefresh(boolean autoRefresh)
autoRefresh
- true to enable auto token refresh; otherwise false.public int getMaxRetryAttempts()
public void setMaxRetryAttempts(int attempts)
attempts
- the maximum number of request attempts.public int getConnectTimeout()
public void setConnectTimeout(int connectTimeout)
connectTimeout
- The number of milliseconds to wait for the connection to be established.public int getReadTimeout()
public void setReadTimeout(int readTimeout)
readTimeout
- The number of milliseconds to wait for bytes to be read.public Proxy getProxy()
public void setProxy(Proxy proxy)
proxy
- the proxy to use for API calls to Box.public String getProxyUsername()
public void setProxyUsername(String proxyUsername)
setProxyBasicAuthentication(String, String)
proxyUsername
- the username to use for a proxy that requires basic auth.public String getProxyPassword()
public void setProxyBasicAuthentication(String proxyUsername, String proxyPassword)
proxyUsername
- Username to use for a proxy that requires basic auth.proxyPassword
- Password to use for a proxy that requires basic auth.public void setProxyPassword(String proxyPassword)
setProxyBasicAuthentication(String, String)
proxyPassword
- the password to use for a proxy that requires basic auth.public boolean canRefresh()
public boolean needsRefresh()
public void refresh()
IllegalStateException
- if this connection's access token cannot be refreshed.public void restore(String state)
protected String getKeyValueOrDefault(JsonObject json, String key, String defaultValue)
protected void notifyRefresh()
protected void notifyError(BoxAPIException error)
error
- A BoxAPIException instance.public void addListener(BoxAPIConnectionListener listener)
listener
- a listener to listen to Box API connection.public void removeListener(BoxAPIConnectionListener listener)
listener
- the listener to remove.public RequestInterceptor getRequestInterceptor()
public void setRequestInterceptor(RequestInterceptor interceptor)
interceptor
- the RequestInterceptor.public ScopedToken getLowerScopedToken(List<String> scopes, String resource)
scopes
- the list of scopes to which the new token should be restricted forresource
- the resource for which the new token has to be obtainedBoxAPIException
- if resource is not a valid Box API endpoint or shared linkprotected BoxAPIConnection.ResourceLinkType determineResourceLinkType(String resourceLink)
resourceLink
- the resource URL to checkpublic void revokeToken()
public String save()
Note that proxy settings aren't automatically saved or restored. This is mainly due to security concerns around persisting proxy authentication details to the state string. If your connection uses a proxy, you will have to manually configure it again after restoring the connection.
restore(java.lang.String, java.lang.String, java.lang.String)
public void setCustomHeader(String header, String value)
header
- the header name.value
- the header value.public void removeCustomHeader(String header)
header
- the header name.public void suppressNotifications()
public void enableNotifications()
suppressNotifications()
public void asUser(String userID)
userID
- the ID of the user to act as.public void asSelf()
asUser(java.lang.String)
public void configureSslCertificatesValidation(X509TrustManager trustManager, HostnameVerifier hostnameVerifier)
trustManager
- TrustManager that verifies certificates are valid.hostnameVerifier
- HostnameVerifier that allows you to specify what hostnames are allowed.protected void extractTokens(JsonObject jsonObject)
protected BoxAPIRequest createTokenRequest(URL url)
protected Call createNewCall(OkHttpClient httpClient, Request request)
protected X509TrustManager getTrustManager()
protected HostnameVerifier getHostnameVerifier()