Build applications with the IBM DataCache service


This tutorial was written using a previous version of the IBM Bluemix® interface. Given the rapid evolution of technology, some steps and illustrations may have changed.

As software architects, we constantly juggle business requirements, available resources, and deadlines. Non-functional requirements, such as performance, are usually looked at later in the game. However, it is not as challenging to address non-functional requirements when the technical infrastructure is already in place.

Building applications in IBM Bluemix™ and using the IBM DataCache service allows us to improve our applications' performance as needed.

Get the codeRun the app

What you'll need to build a similar app

  • A basic knowledge of Javascript
  • A basic knowledge of Java Server Pages (JSP)
  • A basic knowledge of WebSphere® Extreme Scale APIs
  • The Eclipse IDE

Environment setup

To build an application that uses the IBM DataCache service you must set up the proper environment. You must install the Cloud Foundry client to deploy the data cache application in the IBM Cloud environment. For development, you will need to install WebSphere Application Server Liberty Profile and WebSphere Extreme Scale. You must also have the Eclipse IDE already installed.

Step 1. Install the Cloud Foundry client

Create a folder in your environment, for example, myWS.

Go to to download the cf command v6 into the folder you created. Run the downloaded file and follow the instructions to install the Cloud Foundry client into the same folder.

Step 2. Install Liberty Profile

Go to the Liberty Profile download page at

Download the WebSphere Application Server Liberty Profile into the folder you created (for example, myWS). Follow the instructions to install the Liberty Profile in the same folder. If you are asked for an installation location, press Enter to accept the default.

Step 3. Install WebSphere Extreme Scale

From the same Liberty Profile download page, download WebSphere eXtreme Scale for Developers Liberty Profile into the folder you created. Follow the instructions to install WebSphere eXtreme Scale in the same folder. If asked for the installation location, press Enter to accept default.

This is how the folder structure will look after installation:

Environment Setup Completed

Notice the wxs folder was created under the wlp folder after WebSphere eXtreme Scale was installed.

Build a sample application

Now the environment setup is complete and you can start building a data cache application. We assume you have Eclipse Java EE IDE for Web Developers installed in your environment. To load the sample code from DevOps Services, you can use the instructions found in "Setting up Eclipse, Git, and RTC Desktop Clients for use with DevOps Services."

There are two methods to build applications that run in Bluemix.

  • You can build applications that deploy as stand-alone WAR files
  • You can build applications that deploy via the Liberty buildpack

This article describes building a data cache application that is deployed as a stand-alone WAR file. For more information on building applications that deploy via the Liberty buildpack, see

Step 1. Create a project

Create a Dynamic Web Project by selecting File > New > Dynamic Web Project.

In the wizard, enter CacheServiceSample in the project name field. Click Next twice to go to the last page and check the check box Generate web.xml deployment descriptor. Click Finish to generate the project.

The following figure shows an example of how the project will now look:

Dynamic Web Project
Dynamic Web Project

Step 2. Add libraries

You must add two class libraries to the project: a JSON library and the WebSphere Extreme Scale library.

To add the JSON library, copy the json-org.jar file into the WebContent/WEB-INF/lib folder. The json-org.jar file can be found in the DevOps Services project.

To add the WebSphere Extreme Scale library, right-click on the project and select Properties to open the properties window. Select Java Build Path and switch to the Libraries tab. Click Add External JARs..., navigate to the myWS/wlp/dev/ibm-api directory, and select the file.

Adding WebSphere Extreme Scale library
Adding WebSphere Extreme Scale library

Step 3. Build the sample application

  1. Create a new file named index.html and put it in the WebContent folder. The index.html file is the welcome page when the sample application is being accessed. Below is an example of the file contents. The key content here is the link to cachesample.html, which we will create later.
    <title>Cache Service Example - Using ObjectGrid API</title>
    <body bgcolor="lightblue">
      <h3>Application Example: run cache operations using WebSphere Extreme Scale
    ObjectGrid API</h3>
      <a href="cachesample.html">cache sample</a>
  2. Create a new file named cachesample.html and put it in the WebContent folder. Add code to accept key and value. Also provide buttons to Get, Put, and Delete key-value pairs from the data cache. For example:
    <h3>Grid Operations:</h3> 
    	Key:&nbsp;&nbsp;&nbsp;<input id="key" type='text' name='key' /> <br>
    	Value:&nbsp;<input id='value' type="text" name='value' /><br><br>
    	<button id='get'>get</button>
    	<button id='put'>put</button>
    	<button id='delete'>delete</button><br>
  3. Now that you have added the three buttons, you will need to define listeners for them. In a <script> block, add a load() function to define listeners when the page is loaded. For example:
    <script language="javascript" type="text/javascript">
    function load(){	
      document.getElementById('get').addEventListener("click", getClicked, false);
      document.getElementById('put').addEventListener("click", putClicked, false);
      document.getElementById('delete').addEventListener("click", deleteClicked, false);
  4. In these listeners, when the buttons are clicked, the getClicked(), putClicked(), and deleteClicked() methods will be called, correspondingly. Following is a sample implementation inside the <script> block:
    function sendRequest(operation) {
    	var ajaxRequest;  
    	var key=document.getElementById('key').value;
    	var value=document.getElementById('value').value;
    	ajaxRequest = new XMLHttpRequest();
    	ajaxRequest.onreadystatechange = function(){
    		if(ajaxRequest.readyState == 4){
    			var result = ajaxRequest.responseText;
 "GET", "cachesample.jsp?operation="+operation+"&key="+key+"&value="+value, true);
    function getClicked() {
    function putClicked() {
    function deleteClicked() {  

The implementation of cachesample.html can be accessed from DevOps Services.

  1. The sendRequest() method above will be accessing a JSP— cachesample.jsp. You will create this file in the WebContent folder. Define a jspInit() method, which will be called when the JSP is initialized. For example:
    public void jspInit()
  2. Inside the jspInit() method, you can retrieve the information for connecting to the data cache service. You will get the list of service data from the system environment, then go through them to find the one that you will be using—"DataCache". To do this, add the following code in the method:
    Map<String, String> env = System.getenv();
     	String vcap=env.get("VCAP_SERVICES");
     	String username=null;
     	String password=null;
     	String endpoint=null;
     	String gridName=null;
          boolean foundService=false;
          if(vcap==null) {
          		System.out.println("No VCAP_SERVICES found");
          } else {
                try {
                	   JSONObject obj = new JSONObject(vcap);
                    String[] names=JSONObject.getNames(obj);
                    if (names!=null) {
    			for (String name:names) {
                          if (name.startsWith("DataCache")) {
                  		JSONArray val = obj.getJSONArray(name);
                 		JSONObject serviceAttr = val.getJSONObject(0);
                 		JSONObject credentials = serviceAttr.getJSONObject("credentials");
                 		username = credentials.getString("username");
                 		password = credentials.getString("password");             							  
                 		gridName= credentials.getString("gridName");
                 		System.out.println("Found configured username: " + username);
                 		System.out.println("Found configured password: " + password);
                 		System.out.println("Found configured endpoint: " + endpoint);
                 		System.out.println("Found configured gridname: " + gridName);		
                 		foundService = true;
    		} catch(Exception e) {}

For more information, see the IBM DataCache service documentation.

  1. After you get the connection information, use it to connect to the data cache service and create a session using WebSphere Extreme Scale APIs. Add the following code in the method:
    try {
    	  ObjectGridManager ogm = ObjectGridManagerFactory.getObjectGridManager();
    	  ClientSecurityConfiguration csc=null;
    	  csc.setCredentialGenerator(new UserPasswordCredentialGenerator(username,password));
    	  ClientClusterContext ccc = ogm.connect(endpoint, csc, null);
    	  ObjectGrid clientGrid = ogm.getObjectGrid(ccc, gridName);
    	  ogSession = clientGrid.getSession();
     	} catch(Exception e) {
     	  System.out.println("Failed to connect to grid!");
  2. Now, you are ready to add the code that will be executed when the sendRequest() method is called. Use WebSphere Extreme Scale APIs to get, update, and delete key-value pairs based the on operation the user has selected. Add the following code to the JSP file:
    try {
      // Use the getMap() method to return a ObjectMap obejct.
      // Once we have this object, we will be able to perform
      // key-value operations on the map.
      ObjectMap map=ogSession.getMap("sample.NONE.P");
      String key = request.getParameter("key");			
      String operation=request.getParameter("operation");
      Object retrievedValue;
      if("get".equals(operation)) {
        // Use the get() method from the ObjectMap to 
        // retrive corresponding value using the given key.
      } else if("put".equals(operation)) {
        String newValue = request.getParameter("value");
        // Use the upsert() method from the ObjectMap to 
        // update or insert key-value pair into the map.
        // If key-value pair already exist, update operation
        // will be performed instead of insert.
      } else if("delete".equals(operation)) {
        // Use the remove() method from the Object Map to 
        // remove key-value pair from the map.
    } catch(Exception e) {
      System.out.println("Failed to perform operation on map");

Implementation of the cachesample.jsp can be accessed from DevOps Services.

Step 4. Add server configuration

You have now completed the implementation of the data cache application. Because this application will be using the data cache service in Bluemix, you will need to perform some configuration.

Create a new file named server.xml in the WebContent folder. This is the content of the file:

<server description="Cache Service Sample Server">

    <!-- Enable features -->
    <application name="cacheServiceSample" context-root="/" location="../../../../../" type="war"/>

This file can be accessed from DevOps Services as well.

Deploy and run the sample applications

Step 1. Register with Bluemix

Before you deploy your application in Bluemix, you will need to register. Go to and click Login. Follow the instructions to register or manage your account.

Step 2. Export the WAR file

Create a folder in the CloudFoundry folder (for example, samples).

In Eclipse, right-click on the project. Select Export > WAR file. Follow the instructions to export the WAR file to the newly created samples folder. Name the WAR file csSample.war.

Step 3. Deploy the WAR file

  1. Change to the newly created samples folder. Use the following command to connect to the IBM Cloud Environment,

    cf api
  2. Log in using the cf login command. Follow the instructions and enter your user ID and password.

    cf login
  3. Now, use the following command to deploy the WAR file,

    cf push <app name> -p csSample.war
    Where <app name> is a unique application name.

You should see similar messages when the push command is executed successfully and the application is running,

Push successfully
Push successfully
  1. The next step is to create an IBM DataCache service instance for the application. Use the following command to create the service instance,

cf create-service DataCache free <service instance name>

Where "free" is the service plan name and <service instance name> is a unique name for the service instance.

  1. With the application deployed and service instance available, you can bind them together using the following command,

cf bind-service <app name in step 3> <service instance name in step 4>

  1. After the binding is complete, it asks you to push the application again. Execute the command in step 3 again.

For more information, see

Step 4. Test the sample application

Navigate to, and log in.

You should see your sample application deployed. Click the link in the middle of the application icon to access the application.

Step 5. (Optional) Remove sample application and service

  1. Go to and click Dashboard at the top of the screen.
  2. Click the setting icon in the upper right corner of your application box and select Stop App.
  3. Click the setting icon in the upper right corner of your application box and select Delete App.
  4. In the window, check the boxes for your application and service in the SERVICES tab and ROUTES tab. Click OK to delete the sample application and service.


In this article, we have shown you how to develop and deploy an application that uses the IBM DataCache service on the IBM Cloud environment. We have found that building an application that runs on the IBM Cloud is very similar to building an application that runs on an application server, except the data cache service is already available from the infrastructure to help improve the application's performance when needed.

Downloadable resources

Related topic


Sign in or register to add and subscribe to comments.

Zone=Cloud computing
ArticleTitle=Build applications with the IBM DataCache service