Build applications with the IBM DataCache service

26 June 2014
PDF (376 KB)
Share:
Photo of Abelard Chow

Abelard Chow

Advisory Software Engineer, IBM

 

Photo of Paul Chen

Paul Chen

Senior Software Developer, IBM

 

Photo of Brian Martin

Brian Martin

Distinguished Engineer, Websphere XS/DataPower XC10 Chief Architect, IBM

 

Sign up for IBM Bluemix
This cloud platform is stocked with free services, runtimes, and infrastructure to help you quickly build and deploy your next mobile or web application.

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.

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 http://www.mybluemix.net/docs/BuildingWeb.jsp#install-cf 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 https://www.ibmdw.net/wasdev/downloads/.

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 https://www.ng.bluemix.net/docs/Liberty/Bind_datacache.html.

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

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 com.ibm.ws.xs.client_1.1.jar file.

Adding WebSphere Extreme Scale library

Click to see larger image

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>
    </body>
  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);
    }
    </script>
  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:

    Click to see code listing

    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;
    			document.getElementById('value').value=result;
            }
    	}
    	
    	ajaxRequest.open("GET", "cachesample.jsp?operation="+operation+"&key="+key+"&value="+value, true);
    	ajaxRequest.send(null); 
    }
    
    function getClicked() {
      sendRequest('get');
    }
    function putClicked() {
      sendRequest('put');
    }
    function deleteClicked() {  
      sendRequest('delete');
    }

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:

    Click to see code listing

    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");             							  
                 		endpoint=credentials.getString("catalogEndPoint");
                 		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;
                 		break;
                 	   }
                    	}
    		   }
    		} 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=ClientSecurityConfigurationFactory.getClientSecurityConfiguration();
    	  csc.setCredentialGenerator(new UserPasswordCredentialGenerator(username,password));
    	  csc.setSecurityEnabled(true);
    			
    	  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!");
     	  e.printStackTrace();
     	}
  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.
        retrievedValue=map.get(key);
    			      
        response.getWriter().write(retrievedValue==null?"null":retrievedValue.toString());
    			 
      } 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.
        map.upsert(key,newValue);
    			  
        response.getWriter().write("[PUT]");
    			  
      } else if("delete".equals(operation)) {
    				
        // Use the remove() method from the Object Map to 
        // remove key-value pair from the map.
        map.remove(key);			  
    			  
        response.getWriter().write("[DELETED]");			  
      }
    			
    } catch(Exception e) {
      System.out.println("Failed to perform operation on map");
      e.printStackTrace();
    }

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 -->
    <featureManager>
        <feature>webProfile-6.0</feature>
        <feature>eXtremeScale.client-1.1</feature>
        <feature>icap:appstate-1.0</feature>
    </featureManager>
       
    <application name="cacheServiceSample" context-root="/" location="../../../../../" type="war"/>
        		   
</server>

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 bluemix.net 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 https://api.mybluemix.net
  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
  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 http://www.ng.bluemix.net/docs/BuildingWeb.jsp#install-cf.

Step 4. Test the sample application

 

Navigate to bluemix.net, 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 bluemix.net 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.

Conclusion

 

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.


BLUEMIX SERVICE USED IN THIS TUTORIAL:Data Cache service improves the performance and user experience of web applications by retrieving information from fast, managed, in-memory caches

Add a comment

Note: HTML elements are not supported within comments.


1000 characters left

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Cloud computing
ArticleID=963805
ArticleTitle=Build applications with the IBM DataCache service
publish-date=06262014