Class WLClient
- java.lang.Object
-
- com.worklight.wlclient.api.WLClient
-
public class WLClient extends java.lang.Object
This singleton class exposes methods that you use to communicate with the MobileFirst Platform server.
-
-
Field Summary
Fields Modifier and Type Field and Description protected static java.lang.String
LOG_ACTIVITY_INIT_ERROR
static java.lang.Object
WAIT_LOCK
-
Method Summary
Methods Modifier and Type Method and Description void
addGlobalHeader(java.lang.String headerName, java.lang.String value)
You use this method to add a global header, which is sent on each request.void
checkForNotifications()
You use this method to check for notifications on the server, such as new block/notify rules, or notifications.void
connect(WLResponseListener responseListener)
This method sends an initialization request to the MobileFirst Platform Server, establishes a connection with the server, and validates the application version.void
connect(WLResponseListener responseListener, WLRequestOptions options)
This method sends an initialization request to the MobileFirst Platform Server, establishes a connection with the server, and validates the application version.static WLClient
createInstance(android.content.Context context)
This method creates the singleton instance ofWLClient
.protected java.util.Hashtable
getchMap()
WLConfig
getConfig()
Deprecated.org.apache.http.client.CookieStore
getCookieStore()
Retrieves the cookie store that is used by the framework when communicating with the server.void
getFriendlyName(WLResponseListener responseListener)
Gets the display name ("friendly name") of the device from MobileFirst Server.protected java.util.Map
getGlobalHeaders()
static WLClient
getInstance()
This method gets the singleton instance ofWLClient
.java.lang.String
getLastAccessToken()
Deprecated.Use WLAuthorizationManager API instead.
Gets the last obtained access token (regardless of scope).java.lang.String
getLastAccessToken(java.lang.String scope)
Deprecated.Use WLAuthorizationManager API instead.
Gets the last obtained access token for the given scope.WLPush
getPush()
Gets the WLPush instance that exposes the methods that are required for push notifications.java.lang.String
getRequiredAccessTokenScope(int status, java.lang.String header)
Deprecated.Use WLAuthorizationManager API instead.
Determines whether an access token is requested by the server, and returns the required scope.java.net.URL
getServerUrl()
Returns the current MobileFirst Platform server URLprotected java.util.Map
getUserPreferencemap()
WLDevice
getWLDevice()
Gets the WLDevice instanceprotected java.lang.String
getWLServerURL()
void
init(WLResponseListener responseListener)
@deprecated - useWLClient.connect(WLResponseListener)
instead.
Sends an 'init' request to the server, establishing server connection and application version validity.void
invokeProcedure(WLProcedureInvocationData invocationData, WLResponseListener responseListener)
Invokes an adapter procedure (similar toJavaScript WL.Client.invokeProcedure
).void
invokeProcedure(WLProcedureInvocationData invocationData, WLResponseListener responseListener, WLRequestOptions requestOptions)
This method sends an asynchronous call to an adapter procedure.static boolean
isApplicationSentToBackground(android.content.Context context)
void
logActivity(java.lang.String activityType)
Deprecated.This method is deprecated in V7.0. Use com.worklight.common.Logger instead.void
login(java.lang.String realmName, WLRequestListener listener)
This method triggers log-in into a specific realm.void
login(java.lang.String realmName, WLRequestListener listener, WLRequestOptions options)
This method triggers log-in into a specific realm.void
logout(java.lang.String realmName, WLRequestListener listener)
This method logs out of a specific realm.void
logout(java.lang.String realmName, WLRequestListener listener, WLRequestOptions options)
This method logs out of a specific realm.void
obtainAccessToken(java.lang.String scope, WLResponseListener responseListener)
Deprecated.Use WLAuthorizationManager API instead.
Obtains an oauth 2.0 access token from the MobileFirst Platform server. The token is required in order to send a request to an external server which uses this MobileFirst Platform authentication method.void
obtainAccessToken(java.lang.String scope, WLResponseListener responseListener, WLRequestOptions requestOptions)
Deprecated.Use WLAuthorizationManager API instead.
Obtains an oauth 2.0 access token from the MobileFirst Platform server. The token is required in order to send a request to an external server which uses this MobileFirst Platform authentication method.void
pinTrustedCertificatePublicKey(java.lang.String certificateFilename)
Pins the host X509 certificate public key to the client application.void
pinTrustedCertificatePublicKey(java.lang.String[] certificateFileNames)
Pins multiple X509 certificates' public key to the client application.void
purgeEventTransmissionBuffer()
Purges the internal event transmission buffer.void
registerChallengeHandler(BaseChallengeHandler challengeHandler)
You can use this method to register a Challenge Handler in the client.protected static void
releaseInstance()
void
removeGlobalHeader(java.lang.String headerName)
You use this method to remove a global header.void
sendRequest(org.apache.http.client.methods.HttpUriRequest request, WLHttpResponseListener listener)
Executes the given HTTP request.void
sendRequest(org.apache.http.client.methods.HttpUriRequest request, WLResponseListener listener)
Executes the given HTTP request.void
setAllowHTTPClientCircularRedirect(boolean isSet)
Allow circular redirect for the HTTP client.void
setEventTransmissionPolicy(WLEventTransmissionPolicy policy)
Configures the transmission of events from the client to the server, according to the specified transmission policy.void
setFriendlyName(java.lang.String friendlyName, WLResponseListener responseListener)
Sets the display name ("friendly name") of the device in MobileFirst Server.void
setHeartBeatInterval(int newInterval)
Sets heart beat interval.void
setServerUrl(java.net.URL url)
Sets the MobileFirst Platform server URL to the specified URLvoid
transmitEvent(org.json.JSONObject event)
Equivalent totransmitEvent(event, false)
void
transmitEvent(org.json.JSONObject event, boolean transmitImmediately)
Transmits a specified event object to the server.
-
-
-
Field Detail
-
WAIT_LOCK
public static final java.lang.Object WAIT_LOCK
-
LOG_ACTIVITY_INIT_ERROR
protected static final java.lang.String LOG_ACTIVITY_INIT_ERROR
- See Also:
- Constant Field Values
-
-
Method Detail
-
getGlobalHeaders
protected java.util.Map getGlobalHeaders()
-
getUserPreferencemap
protected java.util.Map getUserPreferencemap()
-
getchMap
protected java.util.Hashtable getchMap()
-
createInstance
public static WLClient createInstance(android.content.Context context)
This method creates the singleton instance ofWLClient
.Note: This method is the first
WLClient
method that you use.
It must be called before subsequent calls togetInstance
.
You must invoke this method at the beginning of the main activity of the application.- Parameters:
context
- Android , for example the Android Activity that creates theWLClient
object.- Returns:
WLClient
-
getInstance
public static WLClient getInstance()
This method gets the singleton instance ofWLClient
.- Returns:
WLClient
-
getConfig
@Deprecated public WLConfig getConfig()
Deprecated.
-
releaseInstance
protected static void releaseInstance()
-
init
public void init(WLResponseListener responseListener)
@deprecated - useWLClient.connect(WLResponseListener)
instead.
Sends an 'init' request to the server, establishing server connection and application version validity.- Parameters:
responseListener
- Listener to invoke success or failure when init done
-
connect
public void connect(WLResponseListener responseListener)
This method sends an initialization request to the MobileFirst Platform Server, establishes a connection with the server, and validates the application version.Important: You must call this method before any other
WLClient
methods that communicate with the MobileFirst Platform Server, for exampleWLClient.invokeProcedure(WLProcedureInvocationData, WLResponseListener)
.- Parameters:
responseListener
- When a successful response is returned from the server, theWLResponseListener.onSuccess(WLResponse)
method is called. If an error occurs, theWLResponseListener.onFailure(WLFailResponse)
method is called.
-
connect
public void connect(WLResponseListener responseListener, WLRequestOptions options)
This method sends an initialization request to the MobileFirst Platform Server, establishes a connection with the server, and validates the application version.Important: You must call this method before any other
WLClient
methods that communicate with the MobileFirst Platform Server, for exampleWLClient.invokeProcedure(WLProcedureInvocationData, WLResponseListener)
.- Parameters:
responseListener
- When a successful response is returned from the server, theWLResponseListener.onSuccess(WLResponse)
method is called. If an error occurs, theWLResponseListener.onFailure(WLFailResponse)
method is called.options
- WLRequestOptions instance
-
login
public void login(java.lang.String realmName, WLRequestListener listener, WLRequestOptions options)
This method triggers log-in into a specific realm. If user authentication is required, WL server will return a set of challenges that should be handled by challenge handlers. It is an asynchronous function. You must specify the realm name and a WLRequestListener instance for accepting onSuccess and onFailure events. Use a WLRequestOptions instance and its setTimeout method in order to specify the number of milliseconds to wait for the server to respond before the request times out.- Parameters:
realmName
- Realm name to log in tolistener
- Implements WLRequestListener protocol (which has onSuccess and onFailure methods)options
- WLRequestOptions instance- Throws:
IllegalArgumentException,
- ifrealmName
orlistener
is null
-
login
public void login(java.lang.String realmName, WLRequestListener listener)
This method triggers log-in into a specific realm. If user authentication is required, WL server will return a set of challenges that should be handled by challenge handlers. It is an asynchronous function. You must specify the realm name and a WLRequestListener instance for accepting onSuccess and onFailure events. A default timeout of 60 seconds is used for waiting for the server to respond before the request times out.- Parameters:
realmName
- Realm name to log in tolistener
- Implements WLRequestListener protocol (which has onSuccess and onFailure methods)- Throws:
IllegalArgumentException,
- ifrealmName
orlistener
is null
-
logout
public void logout(java.lang.String realmName, WLRequestListener listener, WLRequestOptions options)
This method logs out of a specific realm. It is an asynchronous function. You must specify the realm name and a wlDelegate instance for accepting onSuccess and onFailure events. Use a WLRequestOptions instance and its setTimeout method in order to specify the number of milliseconds to wait for the server to respond before the request times out.- Parameters:
realmName
- Realm name to logout fromlistener
- Implements WLRequestListener protocol (which has onSuccess and onFailure methods)options
- WLRequestOptions instance- Throws:
IllegalArgumentException,
- ifrealmName
orlistener
is null
-
logout
public void logout(java.lang.String realmName, WLRequestListener listener)
This method logs out of a specific realm. It is an asynchronous function. You must specify the realm name and a WLRequestListener instance for accepting onSuccess and onFailure events. A default timeout of 60 seconds is used for waiting for the server to respond before the request times out- Parameters:
realmName
- Realm name to logout fromlistener
- Implements WLRequestListener protocol (which has onSuccess and onFailure methods)- Throws:
java.lang.IllegalArgumentException
- ifrealmName
orlistener
is null
-
checkForNotifications
public void checkForNotifications()
You use this method to check for notifications on the server, such as new block/notify rules, or notifications. When you call this method from the onResume Android Activity lifecycle event and you bring the activity to the foreground, the application checks for new notifications.
-
addGlobalHeader
public void addGlobalHeader(java.lang.String headerName, java.lang.String value)
You use this method to add a global header, which is sent on each request.- Parameters:
headerName
- Name of the headervalue
- Value of the header
-
removeGlobalHeader
public void removeGlobalHeader(java.lang.String headerName)
You use this method to remove a global header. Then, the header is no longer sent on each request.- Parameters:
headerName
- Name of the header
-
invokeProcedure
public void invokeProcedure(WLProcedureInvocationData invocationData, WLResponseListener responseListener, WLRequestOptions requestOptions)
This method sends an asynchronous call to an adapter procedure. The response is returned to the callback functions of the specifiedWLResponseListener
.
If the invocation succeeds,WLResponseListener.onSuccess(WLResponse)
is called. If it fails,WLResponseListener.onFailure(WLFailResponse)
is called.- Parameters:
invocationData
- Invocation data for the procedure call.responseListener
- Listener object whose callback methodsWLResponseListener.onSuccess(WLResponse)
andWLResponseListener.onFailure(WLFailResponse)
are called.requestOptions
- (optional) InvocationWLRequestOptions
options.
-
invokeProcedure
public void invokeProcedure(WLProcedureInvocationData invocationData, WLResponseListener responseListener)
Invokes an adapter procedure (similar toJavaScript WL.Client.invokeProcedure
).The response is returned to the provided listener callback functions. Upon a successful response from the server, the listener's
onSuccess
is called.onFailure
is called in case of an error, including a login form response from the server, which is also considered an error.Example
The following code invokes a procedure "getStoriesFiltered" in the adapter "RSSReader" using a parameter "Africa":
String adapterName = "RSSReader"; String procedureName = "getStoriesFiltered"; WLProcedureInvocationData invocationData = new WLProcedureInvocationData(adapterName, procedureName); Object[] parameters = new Object[] {"africa"}; invocationData.setParameters(parameters); WLClient client = WLClient.getInstance(); client.invokeProcedure(invocationData, new MyInvokeListener(), options);
- Parameters:
invocationData
- Invocation data parameters to send on the request.responseListener
- Listener that will handle the response when returned from the server (on success or failure).
-
logActivity
public void logActivity(java.lang.String activityType)
Deprecated. This method is deprecated in V7.0. Use com.worklight.common.Logger instead.This method reports a user activity for auditing or reporting purposes. The activity is stored in the application statistics tables (the GADGET_STAT_N tables).- Parameters:
activityType
- A string that identifies the activity.
-
pinTrustedCertificatePublicKey
public void pinTrustedCertificatePublicKey(java.lang.String certificateFilename) throws java.lang.IllegalArgumentException
Pins the host X509 certificate public key to the client application. Secured calls to the pinned remote host will be checked for a public key match. Secured calls to other hosts containing other certificates will be rejected. Some mobile operating systems might cache the certificate validation check results. Your app must call the certificate pinning method before making a secured request. Calling this method a second time overrides any previous pinning operation.- Parameters:
certificateFilename
- path to the certificate under the assets folder.- Throws:
java.lang.IllegalArgumentException
- ifcertificateFilename
is null, not found or is not in DER format.
-
pinTrustedCertificatePublicKey
public void pinTrustedCertificatePublicKey(java.lang.String[] certificateFileNames) throws java.lang.IllegalArgumentException
Pins multiple X509 certificates' public key to the client application. Secured calls to the pinned remote hosts will be checked for a public key match. Secured calls to other hosts containing other certificates will be rejected. Some mobile operating systems might cache the certificate validation check results. Your app must call the certificate pinning method before making a secured request. Calling this method a second time overrides any previous pinning operation.- Parameters:
certificateFileNames
- path to the certificates under the assets folder.- Throws:
java.lang.IllegalArgumentException
- ifcertificateFileNames
is null, not found or is not in DER format.
-
setHeartBeatInterval
public void setHeartBeatInterval(int newInterval)
Sets heart beat interval.- Parameters:
newInterval
- Interval value in seconds
-
isApplicationSentToBackground
public static boolean isApplicationSentToBackground(android.content.Context context)
-
registerChallengeHandler
public void registerChallengeHandler(BaseChallengeHandler challengeHandler)
You can use this method to register a Challenge Handler in the client.
You must use this method when you implement custom challenge handlers, or when you customize the Remote Disable / Notify Challenge Handler.
Important: you must call this method at the beginning of your application after you initializeWLClient
.Example 1: registering a customized Remote Disable / Notify Challenge Handler
To customize the Remote Disable / Notify
ChallengeHandler
, you must register an instance of typeWLChallengeHandler
in the client. When you create theChallengeHandler
, you must give it the specific realm name wl_remoteDisableRealm.// define class public class MyRemoteDisableCH extends WLChallengeHandler { . . . } // create new CH with appropriate realm MyRemoteDisableCH ch = new MyRemoteDisableCH("wl_remoteDisableRealm"); // register CH WLClient.getInstance().registerChallengeHandler(ch);
Example 2: customizing the Remote Disable / Notify Challenge Handler
To customize the Remote Disable / Notify Challenge Handler, you must extend
WLChallengeHandler
and implement the following methods:- public void handleSuccess(JSONObject success)
- public void handleFailure(JSONObject error)
- public void handleChallenge(JSONObject challenge)
public class MyRemoteDisableCH extends WLChallengeHandler { public MyRemoteDisableCH(String realm) { super(realm); } //@Override // this method is called after the challenge is answered successfully public void handleSuccess(JSONObject success) { } //@Override // this method is used to disable the application public void handleFailure(JSONObject error) { try { // get error message String message = error.getString("message"); // get download link String downloadLink = error.getString("downloadLink"); // create and show the disable dialog } catch (JSONException e) { // handle exception } } ] //@Override // this method is used to notify the application public void handleChallenge(JSONObject challenge) { try { // get message data from challenge String message = challenge.getString("message"); String messageId = challenge.getString("messageId"); // do something with the message // answer the challenge submitChallengeAnswer(messageId); } catch (JSONException e) { // handle exception } } }
Note: When the application is disabled, the behavior by default is to open a dialog that displays the appropriate message. You must implement this behavior by default in the method handleFailure of RemoteDisableChallengeHandler. The dialog can also display a link to download the new version of the application. After the user closes the dialog, the application continues to work offline. You must implement a similar behavior in the handleFailure code of the custom Remote Disable Challenge Handler.
- Parameters:
challengeHandler
- Custom challenge handler instance.
-
getPush
public WLPush getPush()
Gets the WLPush instance that exposes the methods that are required for push notifications.- Returns:
WLPush
-
getWLServerURL
protected java.lang.String getWLServerURL()
-
transmitEvent
public void transmitEvent(org.json.JSONObject event)
Equivalent totransmitEvent(event, false)
- Parameters:
event
- Event to be transmitted.
-
transmitEvent
public void transmitEvent(org.json.JSONObject event, boolean transmitImmediately)
Transmits a specified event object to the server.An event object is added to the transmission buffer. The event object is either transmitted immediately, if the immediate parameter is set to
true
, otherwise it is transmitted according to the transmission policy. For more information, seeWL.Client.setEventTransmissionPolicy
. One of the properties for the event object might be the device context, which comprises geo-location and WiFi data. If no device context is transmitted as part of the event, the current device context, as returned byWL.Device.getContext
, is added automatically to the event during the transmission process.- Parameters:
event
- Event object that is being transmitted. The event object is either a literate object, or a reference to an object.transmitImmediately
- Boolean flag that indicates whether the transmission should be immediate (true
), or should be based on the transmission policy's interval (false
). If immediate istrue
, previously buffered events are transmitted, as well as the current event. The default value isfalse
.
-
setEventTransmissionPolicy
public void setEventTransmissionPolicy(WLEventTransmissionPolicy policy)
Configures the transmission of events from the client to the server, according to the specified transmission policy.- Parameters:
policy
- Policy instance that will be used.
-
setServerUrl
public void setServerUrl(java.net.URL url)
Sets the MobileFirst Platform server URL to the specified URLChanges the MobileFirst Platform server URL to the new URL and cleans the HTTP client context. After calling this method, the application is not logged in to any server.
Notes:
- The responsibility for checking the validity of the URL is on the developer.
- This call does not clean the HTTP client context saved in JavaScript.
For hybrid applications, it is recommended to set the server URL by using the following JavaScript function:
WL.App.setServerUrl
. - If the app uses push notification, it is the developer's responsibility to unsubscribe from the previous server and subscribe to the new server.
For more information on push notification, see
WLPush
.
WLClient.getInstance().setServerUrl(new URL("http://9.148.23.88:10080/context"));
- Parameters:
url
- URL of the new server, including protocol, IP, port, and context.
-
getServerUrl
public java.net.URL getServerUrl()
Returns the current MobileFirst Platform server URL- Returns:
- MobileFirst Platform server URL
-
purgeEventTransmissionBuffer
public void purgeEventTransmissionBuffer()
Purges the internal event transmission buffer.The internal event transmission buffer is purged, and all events awaiting transmission are permanently lost.
-
obtainAccessToken
public void obtainAccessToken(java.lang.String scope, WLResponseListener responseListener)
Deprecated. Use WLAuthorizationManager API instead.
Obtains an oauth 2.0 access token from the MobileFirst Platform server. The token is required in order to send a request to an external server which uses this MobileFirst Platform authentication method.- Parameters:
scope
- Name of the security test protecting the external resource.responseListener
- Listener object whose callback methodsWLResponseListener.onSuccess(WLResponse)
andWLResponseListener.onFailure(WLFailResponse)
are called.
-
obtainAccessToken
public void obtainAccessToken(java.lang.String scope, WLResponseListener responseListener, WLRequestOptions requestOptions)
Deprecated. Use WLAuthorizationManager API instead.
Obtains an oauth 2.0 access token from the MobileFirst Platform server. The token is required in order to send a request to an external server which uses this MobileFirst Platform authentication method.- Parameters:
scope
- Name of the security test protecting the external resource.responseListener
- Listener object whose callback methodsWLResponseListener.onSuccess(WLResponse)
andWLResponseListener.onFailure(WLFailResponse)
are called.requestOptions
- RequestWLRequestOptions
options.
-
getLastAccessToken
public java.lang.String getLastAccessToken()
Deprecated. Use WLAuthorizationManager API instead.
Gets the last obtained access token (regardless of scope).- Returns:
- The access token, or
null
if no tokens were obtained.
-
getLastAccessToken
public java.lang.String getLastAccessToken(java.lang.String scope)
Deprecated. Use WLAuthorizationManager API instead.
Gets the last obtained access token for the given scope.- Parameters:
scope
- Scope of the requested token- Returns:
- The token, or
null
if no token was previously obtained for the requested scope.
-
getRequiredAccessTokenScope
public java.lang.String getRequiredAccessTokenScope(int status, java.lang.String header)
Deprecated. Use WLAuthorizationManager API instead.
Determines whether an access token is requested by the server, and returns the required scope.- Parameters:
status
- Status code of the response.header
- Value of theWWW-Authenticate
header of the response.- Returns:
- Scope requested by the server, or null if the response is not related to MobileFirst Platform access tokens.
-
getCookieStore
public org.apache.http.client.CookieStore getCookieStore()
Retrieves the cookie store that is used by the framework when communicating with the server.- Returns:
- The cookie store object
-
sendRequest
public void sendRequest(org.apache.http.client.methods.HttpUriRequest request, WLHttpResponseListener listener)
Executes the given HTTP request. The given listener'sWLHttpResponseListener.onSuccess(HttpResponse)
method will be called if a 2xx response will be received, and theWLHttpResponseListener.onFailure(HttpResponse, Exception)
method will be called if no response or a response with an error status (4xx/5xx) will be received. The listener's methods will be given an instance ofWLResponse
class.- Parameters:
request
- HTTP request to execute.listener
- Response listener.
-
sendRequest
public void sendRequest(org.apache.http.client.methods.HttpUriRequest request, WLResponseListener listener)
Executes the given HTTP request. The given listener'sWLHttpResponseListener.onSuccess(HttpResponse)
method will be called if a 2xx response will be received, and theWLHttpResponseListener.onFailure(HttpResponse, Exception)
method will be called if no response or a response with an error status (4xx/5xx) will be received. The listener's methods will be given the original HTTP response from the server.- Parameters:
request
- HTTP request to execute.listener
- Response listener.
-
setAllowHTTPClientCircularRedirect
public void setAllowHTTPClientCircularRedirect(boolean isSet)
Allow circular redirect for the HTTP client.- Parameters:
isSet
- set value
-
setFriendlyName
public void setFriendlyName(java.lang.String friendlyName, WLResponseListener responseListener)
Sets the display name ("friendly name") of the device in MobileFirst Server.- Parameters:
friendlyName
- The device display name to set.responseListener
- Listener whoseonSuccess
oronFailure
method is called upon request completion.
-
getFriendlyName
public void getFriendlyName(WLResponseListener responseListener)
Gets the display name ("friendly name") of the device from MobileFirst Server.- Parameters:
responseListener
- Listener whoseonSuccess
oronFailure
method is called upon request completion. The display name of the device is returned in theresponse
parameter of the listener'sonSuccess
method.
-
-