Initializing an Application

Initialize the application when it starts the first time and subsequently.

Creating and Initializing the Client Connection

Create and initialize the ClientConnection class, which is part of Core Services library. The ClientConnection class declares the programmatic interface for an object that manages connection settings required for registering the user and fetching application settings from the server. You must initialize a ClientConnection object and set connection properties for it before you can perform user registration or fetch any application settings from the server. Initialize the application using the following example code, which returns an instance of ClientConnection class.

A ClientConnection object is required to set the parameters required for the registration or request-response with SAP Mobile Platform.

public class ClientConnectionUtility{ 
     public static Logger logger;
     public static Preferences pref;
     public static ConnectivityParameters param;
     public static RequestManager reqManagerObject;
     public static ClientConnection clientConnection;

     public ClientConnectionUtility( Context context){
          logger = new Logger();
          pref = new Preferences(context, logger);
          param = new ConnectivityParameters();      
          param.setUserName(<username>);
          param.setUserPassword(<password>);
          reqManagerObject = new RequestManager(logger, pref, param, 1);

          clientConnection = new ClientConnection(context, <application ID>, <domain>, <security configuration>, reqManagerObject);
          clientConnection.setConnectionProfile(<host:port>);
          clientConnection.setApplicationConnectionID(<ApplicationConnectionID>);   //(optional, it registers client with the server using this application connection ID.
     }
     
     public static ClientConnection getClientConnection(){
          return clientConnection;
     }
}

Registering the User

Register the user to the SAP Mobile Platform by invoking registerUser(boolean isSynchronous) method of UserManager class. The boolean parameter isSynchronous specifies whether the registration is synchronous or asynchronous. If asynchronous, implement and register SMPClientListeners.ISMPUserRegistrationListener to get a call back.
Note: The user name and password and other connectivity parameters should be set on ConnectivityParameter instance before calling registerUser method. Alternately, register and implement HttpChannelListeners.IAuthenticationChallengeListner to get a callback upon authentication challenge from the server.
For Asynchronous Registration

       public class SampleApplication extends Activity implements ISMPUserRegistrationListener
       {
           UserManager um;
           public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(<Your Layout>);
           um = new UserManager(clientConnection); //use the clientConnection initialized in the previous topic
           um.setUserRegistrationListener(SampleApplication.this);
           um.registerUser(false);
       }

       @Override
       public void onAsyncRegistrationResult(State registrationState, ClientConnection conn, int errCode, String errMsg) {
       if(registrationState == State.SUCCESS)
       {
          Log.i("RegistrationState Success",conn.getApplicationID());
       try
        {
           Log.i("RegistrationState Success","APPCID" + um.getApplicationConnectionId());
        } catch (SMPException e)
          {
              e.printStackTrace();
          }
        }
        if(registrationState == State.FAILURE)
        {
            Log.i("Registration State Failure",errCode+errMsg);
         } 

       }
}

For Synchronous Registration

public class SampleApplication extends Activity
{
    public void onCreate(Bundle savedInstanceState)
    {
       try
       { 
        UserManager userManager = new UserManager(clientConnection); //use the clientConnection initialized in the previous section
        userManager.registerUser(true); 
        String appCID = userManager.getApplicationConnectionId();
        } 
        catch (SMPException e){
        e.printStackTrace();
        }
     }
}

Handling Encryption Key

(Applicable to applications in offline mode) In offline mode, the application data can be encrypted and securely stored using EncryptionManager class. Hence, you must use getEncryptionKey and SetEncyptionKey APIs to generate and set the encryption key. The application must set the encryption key each time, it comes to foreground or is started.

Example to illustrate the usage of encryption key by the application:
String cipherKey = null;
/*fetch the cipherKey from Secure store like dataVault or android applications shared Preference.*/
if(<CipherKey is found in SecureStore>)
             
/*Should be set every time application is loaded*/
   EncryptionKeyManager.setEncryptionKey(cipherKey,getContext());
/*Store the cipherKey in Secure store like dataVault or android applications shared Preference.*/
   else(<Cipher Key is not yet generated>)
   cipherKey= EncryptionKeyManager.getEncryptionKey(getContext());

Enabling Single and Mutual SSL Authentication

In a single SSL connection, the client must trust the server certificate. You can set this up in one of these ways:
  • Install the CA certificate on the device trustStore that application uses while connecting to the HTTPS URL.
  • If the application does not provide the certificate, implement the ISSLChallengeListener. The application receives a callback to the isServerTrusted method. When the application receives the server certificate, it can choose to trust the certificate or not. Based on that, it returns the Boolean value as true or false.
  • Bundle the CA certificate in the application and invoke the setServerCertificate method to provide the certificate. SAP recommends using one of the other methods, as this one is available only for backward compatibility with Android versions earlier than 4.0.

In mutual SSL connection, the server must trust the client certificate. The application must implement IMutualSSLChallengeListener, and invoke the getClientCertificate callback to request the client certificate. The client returns an X.509 certificate, and a private key, which together form an HttpClientCertInfo object.

Implement listeners for SSL callbacks.

public class LaunchActivity extends Activity implements ISSLChallengeListener, IMutualSSLChallengeListener {

		
	RequestManager srm;
	ILogger logger;
	IConnectivityParameters params;
	IPreferences prefer;
	String url="<Gateway URL>";
		
	public void mreg(View v){
		ClientConnection clientConnection;
		UserManager userManager;
		logger=new Logger();
		prefer=new Preferences(this, logger);
		params=new ConnectivityParameters();
		params.setLanguage("en");
		params.setUserName(<username>);
		params.setUserPassword(<password>);
		
		Context c = getApplicationContext();
	  	try{ InputStream certStream = c.getResources().openRawResource(<certificate>); 
CertificateFactory cf = CertificateFactory.getInstance("X509");
 Certificate cer= cf.generateCertificate(certStream);

	  	
          param.setServerCertificate(cer); //to place certificate in the devices less than 4.0 
          
          Log.i("tag", "In Set Server certificate API");
          
	  	}catch(Exception e){
	  		Log.i("tag", "set certificate from file failed" + e.getMessage());
	  		e.printStackTrace();
	  	}
            srm=new RequestManager(logger,prefer,params,1);
            /**
		* The set methods which should be called to register the listeners to the request manager
		 * 
		 */
            srm.setSSLChallengeListener(this);
		    srm.setMutualSSLChallengeListener(this);
            ClientConnection.initInstance(getApplicationContext(), "<application>", "<domain>", "<security configuration>", <request manager>);
		try {
			j=ClientConnection.getInstace();
			j.setConnectionProfile("<connection url>");
			UserManager.registerUser(true);
			}
         catch (SMPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		
	}

Send X.509 certificate and private key to the client as an HttpClientCertInfo object.
public HttpsClientCertInfo getClientCertificate() 
{
		InputStream inStream;
		String cert="<p12 certificate location>";
		 Context context=this.getApplicationContext();
		 try {

			
			 inStream = context.getResources().openRawResource(cert);
			 
			 /*following code loads the key store, and retrieves
			   The alias under which it is loaded. */

			 KeyStore ks = KeyStore.getInstance("PKCS12");
		        ks.load(inStream, "mobile".toCharArray());
		        Enumeration aliases=ks.aliases();
		        String keyname=(String)aliases.nextElement();
		  		    
		     /* using the alias stored in the variable “keyname”
			We get the Private Key and the X509  Certificate
			Which we use to return HttpClientCertInfo object.*/
			
		     PrivateKey pk=(PrivateKey)ks.getKey(keyname,"mobile".toCharArray());
		     X509Certificate xcer=(X509Certificate)(ks.getCertificate(keyname));
	           	  
		       
             return new HttpsClientCertInfo(xcer,pk);}
		 
		 catch(Exception e){
			 return null;
		 }

		
	}
    /*
	 * This is the callback which is invoked if
	 * 1) SSL is enabled,
	 * 2) The correct certificate is not installed on the device,in which case it   is required of the application to verify the server certificate.
	 */

@Override
	public boolean isServerTrusted(X509Certificate[] paramArrayOfX509Certificate) {
		// TODO Auto-generated method stub
		
		return true;
	}

}

Setting the Password Policy Using DataVault

(Optional) Use the DVPasswordPolicy (as defined in com.sybase.persistence.DataVault) which holds the information of the Password Policy.

(Applicable to On-Premise only) To make the password policy editable in the SAP Mobile Platform Server, set the application connection property "CapabilitiesPasswordPolicy" to true in the client application. To set the password policy, use the following example code:
AppSettings appSettings = new AppSettings(clientConnection); //use the clientConnection object initialized in the "Creating and Initializing the Client Connection" section.
DVPasswordPolicy passwordPolicy = appSettings.getPasswordPolicy();

(Optional) Initializing an Application Using Logon Manager

To initialize an application using Logon manager, see MAF Logon Task Flow.

Related reference
Managing Android Application Registration Using Client Hub