SAP Cloud Foundry Tutorial – Connect a Java Servlet to a HANA hdi-shared Service Instance using an SAP Cloud Foundry Trial Account

The goals of this tutorial are to create a Java servlet that connects to a HANA hdi-shared service instance, deploy a WAR file to SAP Cloud Foundry in SAP Cloud Platform and launch the servlet in a browser.

The tutorial uses an SAP Cloud Foundry trial account, an SAP Cloud Platform non-trial account, Eclipse and the Cloud Foundry CLI tools.  It assumes you have worked within the SAP NEO environment, have an SAP Cloud Platform account, and have some familiarity with SAP HANA.

If you are new to SAP Cloud Foundry in the SAP Cloud Platform, and would like more information, see my earlier blog “Differences between SAP NEO and SAP Cloud Foundry in the SAP Cloud Platform“.

Steps to this tutorial:

  1. Create an SAP Cloud Foundry Trial Account in the SAP Cloud Platform
  2. Install the Cloud Foundry CLI tools (Command Line Interface)
  3. Create a Quota Plan
  4. Create a HANA hdi-shared service instance (for database connectivity)
  5. Develop a Java servlet in Eclipse
  6. Create an application in Cloud Foundry and deploy a WAR file
  7. Create a table in SAP HANA via the SAP WebIDE Fullstack tool connected to your SAP Cloud Foundry trial account – this step requires the SAP Cloud Platform account
  8. Launch the application in a browser and see results from a simple database query

Things you’ll need:

  1. Eclipse, Neon or Oxy versions
  2. An SAP Cloud Platform account in the NEO environment


I created this tutorial as part of evaluating the SAP Cloud Foundry environment in the SAP Cloud Platform.  For the past several years I have been working within the SAP NEO environment in the SAP Cloud Platform.  My only option to evaluate SAP Cloud Foundry at the time was to create a trial SAP Cloud Foundry account.

Since I was working within an SAP Cloud Platform Cloud Foundry trial account, the number of services available to me were limited – specifically regarding the SAP HANA service.  Using a trial account, you are limited to using the hdi-shared service plan which provides an HDI container on a HANA database.   SAP’s help and support sites provide information about the available service plans for SAP HANA for non-trial accounts. You can research this on your own starting with Deployment-Infrastructure Services in XS Advanced.

Step One: Create an SAP Cloud Foundry Trial Account

First, sign up for a free trial account in the Cloud Foundry environment. If you already have a trial account, open the cockpit, navigate to your subaccount and to the space in which you’d like to deploy the application and continue with step 3.

  1. Go to the SAP Cloud Platform Home page(
  2. You need to register before you can create a trial account. To do so, proceed as follows:
    • Choose Register.
    • Enter the required data.
      You’ll receive a confirmation e-mail with instructions for activating your trial account.
    • Click the link in the e-mail to confirm your address and activate your trial account.
    • Choose Continue and log on with your credentials.
  3. Choose Cloud Foundry Trial.
  4. For the purposes of these instructions based on the evaluation, select the Europe (Frankfurt) region.


A global account, subaccount, org, and space are automatically created for you.

5.  You should see the below. Choose Go to Space.


Getting to your Cloud Foundry Trial Account after its been created

  1. Go to the SAP Cloud Platform Home page (
  2. Select Cloud Foundry Trial
  3. Select your subaccount
  4. Select your space


Alternatively, if you want to see all your spaces, select Spaces from the left-hand pane.


Then select your space.


Step Two: Install the Cloud Foundry CLI Tools

Download and Install the CLI Tools

  1. Go to and download the installer for your system. Alternatively, the installation can be found here:
  2. Once downloaded, extract the files and execute the installer executable.

To test the installation, open a Command Terminal and type “cf” at the command line.  Information such as the “cf” version and command line options are displayed.

Login to Cloud Foundry

When you created your SAP Cloud Foundry trial, your email address associated with your SAP S-Id is the login id to be used to login in to Cloud Foundry.

The syntax to login is

$ cf login [-a API_URL] [-u USERNAME] [-p PASSWORD] [-o ORG] [-s SPACE]

API_URL is the API endpoint.  You can find the endpoint name by navigating to your trial account’s subaccount and select the Overview.


Once you successfully login, you’ll be prompted to select an Organization if your email is associated with more than one.

The expected output is similar to what is below:


Step Three: Create a Quota Plan

Before you can create the hdi-shared service, you will need to create a Quota Plan within your trial.  Once created, you will have a set number of services that you can add to your subaccount.

  1. Navigate to your “trial” subaccount
  2. Select “Quota Plans” in the left-hand pane
  3. Select “New Plan”

A similar screen will be displayed where you can enter the “Name” of the plan and enter the amount of memory of 2048 (which is the default total for the Organization).


4. Save the new plan

In this same screen, you’ll assign your space to this new plan.

  1. In the “Plan Assignment” section of the screen, you’ll your new space called “dev”. Select the new Quota Plan from the drop down.


Alternatively, a Quota Plan can be created using the CLI tools –

Step Four: Create an hdi-shared service (HANA)

First, you can check to see if you have the appropriate Entitlement for HANA.

  1. Using the SAP Cloud Platform Cockpit, navigate to your trial account.


2. Select “Entitlements” from the left-hand pane.

3. Scroll down the page and you will see the section labeled “HANA”. Before you create the hdi-shared service, the assignment may read “0 of 1 assigned”.  Once you create the service instance, you will see:


Add the hdi-shared service instance from “SAP HANA Schemas & HDI Containers” from within the Service Marketplace.

  1. Using the SAP Cloud Platform Cockpit, navigate to your space.
  2. Select “Service Marketplace” from the left-hand pane.
  3. Scroll down the page, and select “SAP HANA Schemas & HDI Containers”


4. Select “Instances” from the left-hand pane.

5. Select the “New Instance” button

6. In the drop-down, select “hdi-shared”. This will be your only option when using the trial SAP Cloud Foundry account.


7. Click “Next” through the next few screens until you reach the last page. Enter the name myhana in the “Name” for the instance and select “Finish”.

IMPORTANT: The name of the hdi-shared service is used when the application is deployed to Cloud Foundry.  It is included in the file manifest.yml.  If you use a different name for your hdi-shared service instance, be sure to use this name in the manifest.yml file when creating the Java project in Eclipse.  If you use the pre-packaged application and choose to import the project, the name of the hdi-shared service instance is already set to “myhana”.

8. When you see the below screen, select “OK”


9. When the hdi-shared service creation has completed, you should see the following screen.


NOTE:  If you already have an application, you can bind the service instance to the application at the same time you create the service instance.

Alternatively, a service instance can be created using the CLI tools –


An example of the output using the CLI command “cf create-service” is as follows:


Once created, you can look to see all the services by using the command “cf services” which provides the following:


Or if you want to just look at the status of one service, you can use the command “cf service ” which provides the following:


Step Five: Develop a Java servlet in Eclipse

This step method assumes you have a comfortable working knowledge of creating Java projects in Eclipse so that you can use the sample code as a guideline.

A key element to building a Java application that will connect to HANA in Cloud Foundry is retrieving the VCAP_SERVICES environment variable and using the database connectivity values to work with the hdi-shared instance.

Cloud Foundry will be looking for a file called manifest.yml.  This configuration file tells Cloud Foundry how to package the application and which buildpacks and services are required.

The result of this step is to produce a WAR file that will be deployed to Cloud Foundry that will use it create the application.

Sample code included below.

Steps to create your own project:

  1. Create a local folder named c:\cf\war to be used later
  2. Create a new “Dynamic Web Project” in Eclipse called “SimpleServlet”.
  3. Download the Argo Jdom library from Select “Download argo (3.39)”. Unzip the download file.
  4. Copy the argo-3.39.jar file to your project WEB-INF/lib folder. Configure your Java Build Path to include the argo-3.39.jar file as an External JAR.
  5. In the Java Resources, create a new Servlet. Use the package name “cf.apps.servlet” and the class name SimpleServlet.  Use the web servlet URL “/hello”.
  6. Replace the code in with the code from below. There will be errors until the new additional Java classes are created.
  7. In the Java Resources, in the “src” folder under the package “cf.apps.servlet”, create a new Java Class called HDIEnvironment. Replace the code in with the code from below.
  8. In the Java Resources, in the “src” folder under the package “cf.apps.servlet”, create a new Java Class called HDIQueryTests. Replace the code in with the code from below.
  9. At the main project folder “SimpleServlet”, create a file named “manifest.yml”. Copy the code from manifest.yml below.
  10. Export the project to the WAR file war at the c:\cf\war folder location.

package cf.apps.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.List;
 * Servlet implementation class SimpleServlet
 * Database credentials are obtained from the class HDIEnvironment which retrieves and
 * parses the environment variable VCAP_SERVICES. The contents of VCAP_SERVICES are 
 * displayed.
 * <p>
 * A sample database query is made using the class HDIQueryTests which will use the
 * HDIEnvironment class for database credentials. 

public class SimpleServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

     * Default constructor. 
    public SimpleServlet() {
        // TODO Auto-generated constructor stub

    public void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {

         // Set response content type
         PrintWriter out = response.getWriter();
         Statement stmt = null;
         Connection conn = null;
         String docType =
            "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
         out.println(docType +
            "<html>\n" +
            "<head><title>Cloud Foundry Database Tests</title></head>\n" +
            "<body bgcolor = \"#f0f0f0\">\n" +
            "<h1 align = \"center\">Database Connection Tests</h1>\n");

         try {
            HDIEnvironment ev = new HDIEnvironment();
            out.println("<h3>Environment info from VCAP_SERVICES</h3>\n");            
            out.println("<p>URL: " + ev.getUrl());
            out.println("<p>User: " + ev.getUser());
            out.println("<p>Password: " + ev.getPassword());
            out.println("<p>Port: " + ev.getPort());
            out.println("<p>VCAP_SERVICES: " + ev.getVcap_services());  

            HDIQueryTests hsc = new HDIQueryTests(response);
            out = response.getWriter();
            out.println("<h3>Query results</h3>\n");             
            out.println("<p>Query: " + hsc.getSQL());
            List<String> results = hsc.getResults();

      for (String str : results) {
      out.println("<p>Result: " + str);


         catch(Exception e) {
            //Handle errors for Class.forName
         } finally {
            //finally block used to close resources
           try {
            } catch(SQLException se2) {
            } // nothing we can do
            try {
            } catch(SQLException se) {
            } //end finally try
         } //end try

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);



package cf.apps.servlet;

import argo.jdom.JdomParser;
import argo.jdom.JsonNode;

 * The class HDIEnvironment retrieves the JSON node VCAP_SERVICES from the environment.
 * The node is parsed, and values such as user, passowrd, url and port can be used
 * to establish a JDBC connection in order to perform queries.
public class HDIEnvironment {

    private String vcap_services = "";
    private String host = "";
    private String dbname = "";
    private String user = "";
    private String password = "";
    private String port = "";
    private String url = "";
    private String schema = "";

public HDIEnvironment() {

   try {
       vcap_services = System.getenv("VCAP_SERVICES");
            //for cloud config
       if (vcap_services != null && vcap_services.length() > 0) {
           JsonNode root = new JdomParser().parse(vcap_services);
           JsonNode mysqlNode = root.getNode("hanatrial");
           JsonNode credentials = mysqlNode.getNode(0).getNode(
           host = credentials.getStringValue("host");
           user = credentials.getStringValue("hdi_user");
           password = credentials.getStringValue("hdi_password");
           port = credentials.getStringValue("port");
           url = credentials.getStringValue("url");
           schema = credentials.getStringValue("schema");
   } catch (Exception e) {

public String getVcap_services() {
return vcap_services;

public String getHost() {
return host;

public String getDbname() {
return dbname;

public String getUser() {
return user;

public String getPassword() {
return password;

public String getPort() {
return port;

public String getUrl() {
return url;

public String getSchema() {
return schema;


package cf.apps.servlet;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

public class HDIQueryTests {
    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "";  
    private String url ="";

    //  Database credentials
    private String user = "";
    private String password = "";
    private String sql;
    private List<String> results = new ArrayList<>();
    public HDIQueryTests(HttpServletResponse response) {
    Statement stmt = null;
    Connection conn = null;
    HDIEnvironment ev = new HDIEnvironment();

    url = ev.getUrl();
    user = ev.getUser();
    password = ev.getPassword();
        // Register JDBC driver
     try {


       // Open a connection
       conn = DriverManager.getConnection(url, user, password);
       // Execute SQL query
       stmt = conn.createStatement();
       ResultSet rs = null;
       sql = "SELECT NAME FROM TABLE1";
       rs = stmt.executeQuery(sql);
       // Extract data from result set
       // Clean-up environment
     } catch (ClassNotFoundException e1) {
     } catch (SQLException e) {

   public String getSQL() {
    return sql;

   public List<String> getResults() {
    return results;


- name: mytomcat
buildpack: sap_java_buildpack
- myhana


The additional library used to traverse the JSON structure is argo.jdom.JdomParser and argo.jdom.JdomNode for simplicity.  If you are using Maven and a pom.xml, the example code provides the Maven dependency information to be included.  You may have a preferred set of libraries to work with JSON – for this example the Argo libraries were simple enough.

The manifest.yml file needs to be at the root of the project.  The contents of this file shown below provides Cloud Foundry the parameters needed to build and deploy the WAR file.  The name of the application is “mytomcat”.  The buildpack value tells CF to use the Java buildpack to construct the application.  Since this example application is to be bound to the hdi-shared container named “myhana”, the name of the service instance “myhana” is place under the services section.  If the name of your hdi-shared service instance is difference, use the name you provided when you created the service.

Step Six: Create application in Cloud Foundry and deploy WAR File

After creating the Java project and exporting the WAR file, you’ll “push” the servlet.war file up to Cloud Foundry.

The CLI command is as follows:  cf push <appName> -p <warfile.war> -b sap_java_buildpack

  1. Open a CMD window
  2. Login to Cloud Foundry “cf login”
  3. Navigate to the c:\cf\war folder
  4. Enter the command cf push mytomcat -p servlet.war -b sap_java_buildpack

You should see a whole series of commands and steps issued during the process.  The last of which will show the status.  To see the status after the application has been deployed, you can use the command cf app mytomcat which will display the below:


Once the application has been pushed to Cloud Foundry, you’ll bind the hdi-shared service instance to the new application.

  1. In the CMD window, enter cf bind-service mytomcat myhana. The syntax for this command is:

cf bind-service <appName> <serviceName>

  1. To verify the binding, you can enter cf services. This should list your “myhana” and show under “bound apps” the “mytomcat” application.


  1. Once the binding is complete, you should use the “restage” command to ensure the environment variables are updated. Enter the following command to restage the application: cf restage mytomcat.
  2. To view/examine the environment variables, especially the VCAP_SERVICES variable, you can enter the command cf env mytomcat.

Step Seven: Create a table using the SAP Web IDE Full-Stack tool

To perform this step, you will need an SAP Cloud Platform NEO account in the EU landscape to enable the SAP Web IDE Full-Stack tool.

First, enable the Web IDE Full-Stack tool:

  1. Login in to the SAP Cloud Platform NEO Cockpit and navigate to your NEO subaccount.
  2. Select “Services” in the left-hand pane
  3. Scroll down the page, and select “SAP Web IDE Full-Stack”
  4. Select “Enable”
  5. Select “Go to Service”


Next you will need to enable “Principal Propagation”.  This will allow the Web IDE to communicate with Cloud Foundry:

  1. Navigate to the subaccount in your NEO environment
  2. Under the section “Security” in the left-hand pane, select “Trust”
  3. In the “Local Service Provider” tab, select the “Edit” button
  4. Select “Enabled” from the drop-down box next to “Principal Propagation”
  5. Select “Save”


Now, you will launch the Web IDE and create a sample project.  The project will not be used for anything other than getting to a SQL interface where you can create a table within your Cloud Foundry hdi-shared schema.

  1. Navigate to the subaccount in your NEO environment
  2. Select “Go to Service” from the “SAP Web IDE Full-Stack” icon on the “Services” page
  3. You may be prompted to connect the Web IDE to Cloud Foundry. Once you have initialized the Web IDE to use Cloud Foundry, it will prompt you reconnect.  If so:
    • Under the Cloud Foundry API Endpoint, select the appropriate endpoint. If you are using the trial CF account, select “
    • Just above the entry, select “Connect”
  4. From the Home page, select “New Project from Template”
  5. Select “Multi-Target Application”, then “Next”
  6. Enter a Project Name, for example mytestproject, and select “Next”
  7. Select “Finish”
  8. The screen should default to the “Development” screen. This screen can be displayed by selecting the icon that looks like : development
  9. Select the main project folder by its name, right click on the name and choose “New” -> “SAP HANA Database Module”.
  10. Enter a name, for example myhanamodule, and select “Next”
  11. On the next screen, select “Finish”

Once you add the “SAP HANA Database Module” you can enable the SAP HANA Database Development tools.

To add the SAP HANA Database Module:

  1. On the left-hand pane you’ll see a “gear” symbol – this is for Settings. Select the “gear” symbol icon that looks like: settings
  2. Select the “Features” option
  3. Enter “HANA” in the search bar.
  4. You should see the icon for “SAP HANA Database Development Tools”. Turn this feature “ON”.
  5. You will also see “SAP HANA Database Explorer”. Turn this feature “ON”.
  6. Select “Save”
  7. In the upper right-hand corner, a status window will pop up telling you your new preferences have been saved.

Now that the Database Development Tools and Database Explorer features are enabled, you will see a new icon in the left-hand pane like:  database

To link your project to Cloud Foundry:

  1. On the left-hand pane, select the “gear” symbol to enter the Settings
  2. Under the “Workspace Preferences”, select the “Cloud Foundry” section
  3. If you created your Cloud Foundry trial in a European landscape, select the API Endpoint as
  4. Select the Organization as your trial account, for example Sxxxxxxxxtrial_trial
  5. Select the Space for your trial account, for example dev
  6. Select Save

To connect the Database Development tools to your Cloud Foundry account:

  1. Select the Database Development icon
  2. This should bring up the below screen.
  3. If the Cloud Foundry API Endpoint is not populated with the correct value, select
  4. Select “Connect”

Finally, you can use the Database Development Tools to connect to your hdi-shared container and create your table.

  1. Select the Database Development Icon
  2. Select the “+” plus symbol to add a connection
  3. Select “HDI Container” as the “Database Type”
  4. Select the name of your hdi-shared service instance under the column “Name”
  5. Select OK

You should now see your hdi-shared service instance in the window.  If you expand the schema, you should see all the database object classes.



To create the table:

  1. Before using SQL, you will need the “hdi_user” account name associated with your hdi-shared service instance.
    1. Open a CMD window, and login in to Cloud Foundry, “cf login”
    2. Enter the command “cf env myAppName” where myAppName is the name of your application. This will display in the CMD window all the environment variables associated with your application.
    3. Copy all the output from this command and paste in to Notepad.
    4. In Notepad, look for the key “hdi_user”. You will use this user name in your SQL GRANT command below.  This name may begin with “SBSS….”.
  2. In the Web IDE, right click on the database name, and select “Open SQL Console”
  3. Copy and paste the below commands in to the SQL Console.
create column table table1 (name nvarchar(80) null);

insert into table1 (name) values ('my name is Mud');

GRANT SELECT, INSERT, UPDATE, DELETE ON table1 TO (copy in your SBSS user name, no quotes);
  1. Replace the user name SBSS… with your hdi_user name that you copied in the previous step. Paste it in the command where indicated.

The purpose of doing this is to ensure that your hdi_user account can work with the hdi-shared service instance.  Since you are using a trial account, you do not have the ability to create tables, or see existing tables even though you previously created the service instance.  These steps are a work-around to allow you to fully interact with the examples and to ensure your web application can query a table.  In a non-trial environment, we would be using a SCHEMA instance and not HDI-Shared and we would not need to perform this GRANT operation.  The trial is expected to include SCHEMAs in early Q1 2019.

  1. Execute these statements (once you have copied/pasted in your hdi_user account name in the commands) by selecting the green arrow in the SQL window.

The output should look like the below:

Statement 'create column table table1 (name nvarchar(80) null)'
executed in 4 ms.

Statement 'insert into table1 (name) values ('my name is Mud')'
executed in 3 ms - Rows Affected: 1

executed in 4 ms.

Step Eight: Launch the application in a browser

Once the application has been pushed to Cloud Foundry, you can launch the application in a browser by entering its URL.

To locate the URL, you can open a CMD window and type “cf app appName” where appName is the name of your application.  This will display the “route” of your application.


IMPORTANT:  If you are using the Java examples provided in this document, the servlet URL to see the database query uses the extension /hello at the end of the URL.  For example, the full URL to see the database connection take place will be “”.

For a full guide describing how to use the SAP HANA service in the Cloud Foundry environment in SAP and Microsoft Azure regions, see:

For information about the SAP HANA service features that are available in the SAP Cloud Platform, see:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s