com.worklight.wlclient.api

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.
    • 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 of WLClient.
      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 of WLClient.
      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 URL
      protected java.util.Map getUserPreferencemap() 
      WLDevice getWLDevice()
      Gets the WLDevice instance
      protected java.lang.String getWLServerURL() 
      void init(WLResponseListener responseListener)

      @deprecated - use WLClient.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 to JavaScript 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 URL
      void transmitEvent(org.json.JSONObject event)
      Equivalent to transmitEvent(event, false)
      void transmitEvent(org.json.JSONObject event, boolean transmitImmediately)
      Transmits a specified event object to the server.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • 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 of WLClient.

        Note: This method is the first WLClient method that you use.
        It must be called before subsequent calls to getInstance.
        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 the WLClient object.
        Returns:
        WLClient

      • getInstance

        public static WLClient getInstance()
        This method gets the singleton instance of WLClient.
        Returns:
        WLClient
      • getConfig

        @Deprecated
        public WLConfig getConfig()
        Deprecated. 
      • releaseInstance

        protected static void releaseInstance()
      • init

        public void init(WLResponseListener responseListener)

        @deprecated - use WLClient.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
      • 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 to
        listener - Implements WLRequestListener protocol (which has onSuccess and onFailure methods)
        options - WLRequestOptions instance
        Throws:
        IllegalArgumentException, - if realmName or listener 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 to
        listener - Implements WLRequestListener protocol (which has onSuccess and onFailure methods)
        Throws:
        IllegalArgumentException, - if realmName or listener 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 from
        listener - Implements WLRequestListener protocol (which has onSuccess and onFailure methods)
        options - WLRequestOptions instance
        Throws:
        IllegalArgumentException, - if realmName or listener 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 from
        listener - Implements WLRequestListener protocol (which has onSuccess and onFailure methods)
        Throws:
        java.lang.IllegalArgumentException - if realmName or listener 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 header
        value - 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)
        Invokes an adapter procedure (similar to JavaScript 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 - if certificateFilename 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 - if certificateFileNames 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 initialize WLClient.

        Example 1: registering a customized Remote Disable / Notify Challenge Handler

        To customize the Remote Disable / Notify ChallengeHandler, you must register an instance of type WLChallengeHandler in the client. When you create the ChallengeHandler, 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()
      • getWLDevice

        public WLDevice getWLDevice()
        Gets the WLDevice instance
        Returns:
        WLDevice
      • transmitEvent

        public void transmitEvent(org.json.JSONObject event)
        Equivalent to transmitEvent(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, see WL.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 by WL.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 is true, previously buffered events are transmitted, as well as the current event. The default value is false.
      • 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 URL

        Changes 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.
        Example

        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 methods WLResponseListener.onSuccess(WLResponse) and WLResponseListener.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 methods WLResponseListener.onSuccess(WLResponse) and WLResponseListener.onFailure(WLFailResponse) are called.
        requestOptions - Request WLRequestOptions 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 the WWW-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,
                       WLResponseListener listener)
        Executes the given HTTP request. The given listener's WLHttpResponseListener.onSuccess(HttpResponse) method will be called if a 2xx response will be received, and the WLHttpResponseListener.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 whose onSuccess or onFailure 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 whose onSuccess or onFailure method is called upon request completion. The display name of the device is returned in the response parameter of the listener's onSuccess method.


© Copyright IBM Corp. 2006, 2015. All Rights Reserved.