0% found this document useful (0 votes)
121 views51 pages

Using SAP Enterprise Messaging To Bridge The World of Sync and Async

jijJWOI

Uploaded by

Jagadish Babu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
121 views51 pages

Using SAP Enterprise Messaging To Bridge The World of Sync and Async

jijJWOI

Uploaded by

Jagadish Babu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Using SAP Enterprise Messaging to Bridge the

World of Sync and Async


CPL162

Exercises / Solutions
Speakers Name / Company

Las Vegas
Oliver Liemert / SAP SE
Tobias Griebe / SAP SE

Bangalore
Balakrishna Gottipati / SAP SE
Soumya Dey / SAP SE

Barcelona
Balakrishna Gottipati / SAP SE
Martin Bachmann / SEP SE
CPL162

TABLE OF CONTENTS
INTRODUCTION ..................................................................................................................................................... 3
BENEFITS ............................................................................................................................................................... 3
HANDS-ON SCENARIO ......................................................................................................................................... 3
GETTING STARTED ............................................................................................................................................... 4
CREATE INITIAL MESSAGING APPLICATION .................................................................................................... 5
DEPLOY AND CONFIGURE MESSAGING APPLICATION ON SAP CLOUD PLATFORM .............................. 19
CONFIGURE & TEST GITHUB WEBHOOK ........................................................................................................ 27
OPTIONAL: CHECK LOG ENTRIES .................................................................................................................... 32
CREATE SAP HANA DATABASE TABLE .......................................................................................................... 35
ENHANCE MESSAGING APPLICATION TO CONSUME MESSAGES FROM MESSAGING QUEUE............. 40
VERIFY END 2 END FLOW: GITHUB WEBHOOK TO SAP HANA DATABASE .............................................. 48

2
CPL162

INTRODUCTION

In the Hands-on session CPL162, you will get a better understanding of the SAP Enterprise Messaging service.
SAP Enterprise Messaging is a cloud-based messaging framework that enables you to connect applications,
services, and devices across different technologies, platforms, and clouds.
Scaling to millions of messages per second in real-time, you can send and receive messages reliably using open
standards and protocols. You can decouple application logic, develop microservices, and support event-driven
architectures.

BENEFITS
Fire-and-Forget Asynchronous Communication
You can free applications from the ties of synchronous communication using enterprise messaging service.

Heterogeneous Integration
You can connect different technology platforms using Java apps and SAP Enterprise Messaging service.

Communicate Reliably at Scale


SAP Enterprise Messaging provides reliable message delivery so that different applications, services, and devices
can send messages even when the receiver is temporarily unavailable. This decoupling of senders and receivers
reduces latency and increases throughput. You can manage and scale these connections easily.

Flexibility and Agility


You can switch seamlessly between architectures as environments adapt and shift from monolithic development
to microservice architectures.

HANDS-ON SCENARIO
In the course of this hands-on exercise you will be creating a simple messaging application. This will provide an
endpoint to be configured with GitHub’s webhook API. Every commit to be done on the configured GitHub
repository will be received in the SAP Cloud Platform, parsed and stored in a message queue provided by the
SAP Enterprise Messaging service. The scenario will be enhanced to asynchronously consume the messages out
of the queue and store them into a database table in the SAP Cloud Platform. You will use Eclipse to develop the
messaging application, implemented in Java. The application will be deployed from the SAP Cloud Platform
Cockpit and the SAP HANA Web-based Development Workbench will be used to create the needed database
tables.

3
CPL162

GETTING STARTED

In order to log on to the notebooks during the hands-on session you have to use the following user:

User: FAIR\student
Password: Welcome17

Each group will be provided with a temporary SAP Cloud Platform account. The accounts will be used to run the
messaging applications with the needed SAP Enterprise Messaging capabilities. Details will be handed out by
the presenter.

Please note that the provided accounts are meant to be used for the CPL162 hands-on session only. The
accounts will be deleted after the TechEd 2017 event.

4
CPL162

CREATE INITIAL MESSAGING APPLICATION

Overview
Estimated time: 20 minutes

Objective
The objective of this chapter is to implement and package the initial messaging java application, which is the
basis for the second chapter. The implementation will be done using Eclipse.

Exercise Description
You will use Eclipse to create a new Dynamic Web Project. Next you will adopt the build- and runtime-
dependencies and implement the java application based on a servlet. Finally, the project will be exported so it
can be deployed to the SAP Cloud Platform in the next step.

Explanation Screenshot

1. Click on the Search Windows button


(WIN+S) and type CPL162 into the
search field.

From the results list, click on the entry


ABAP in Eclipse – CPL162 – Neon

Eclipse is starting.

2. Once Eclipse is loaded, close the


Welcome Tab.

Click on File  New  Dynamic web


Project to create a new Project in
Eclipse.

5
CPL162

Explanation Screenshot

3. As Project Name provide:


CPL162_messaging_##

Click on Next.

Note: Replace ## with your group


number.

4. Leave all the default settings as is and


click on Next.

5. Leave the default values for Context


root and Content directory.

Select the option to Generate web.xml


deployment descriptor.

Click on Finish.

6
CPL162

Explanation Screenshot

6. The newly created project is displayed


in the Project Explorer.

You will add additional libraries that are


needed during build-time of the project.
The archives will already be available
on the SAP Cloud Platform during
runtime.

Select your project in the Project


Explorer and choose from the menu
Project  Properties.

7. In the search field provide java build to


filter the list of available project
properties.

Choose Java Build Path from the


selection.

Select the Libraries tab and click on the


Add External JARs button.

8. The needed libraries are available on


the Student (Share) that is linked on
your desktop.

In the files selection window, you can


provide the direct link to the needed files
available on the student share (copy &
paste):

\\students.fair.sap.corp\Studentshare\
CPL162\lib\javax.servlet-api-3.0.1.jar

\\students.fair.sap.corp\Studentshare\
CPL162\lib\slf4j-api-1.7.25.jar

You can select both libraries at the


same time.

Click on Open to close the close the


window and add the JAR files to the list.

7
CPL162

Explanation Screenshot

9. Close the project properties window by


clicking Apply and finally on OK.

In the Project Explorer you can see the


new entry under Referenced Libraries.

10. Minimize all windows and double click


on Student (Share) on the desktop to
access the central file share.

11. Navigate to CPL162  lib 


com.sap.messaging

Select all the files in the folder (Ctrl+A)


and copy to the clipboard (Ctrl+C).

Note: To make use of the Enterprise


Messaging capabilities we need to add
additional libraries needed during build-
and runtime. Those libs are not present
on the SAP Cloud Platform, we need to
add them to the project, so they get
deployed on SAP CP in parallel to the
actual application.

8
CPL162

Explanation Screenshot

12. Go back to Eclipse and expand your


Project: WebContent  WEB-INF 
lib

Paste (Ctrl+V) the copied JAR archives


from the clipboard into the lib folder.

13. The SAP Cloud Platform application will


be based on a Servlet.

In the toolbar click the little arrow next to


the New icon.

From the dropdown select Servlet.

A new wizard will open.

9
CPL162

Explanation Screenshot

14. Provide

Java package:
com.sap.teched.cpl162_##
Class Name:
GithubWebhookServlet

Click on Next.

Note: Replace ## with your group


number.

15. From URL mappings select the entry


/GithubWebhookServlet and click on
Edit.

10
CPL162

Explanation Screenshot

16. Provide /webhook as Pattern and click


on OK.

Complete the wizard by clicking Finish.

The GithubWebhookServlet.java class


will be opened in a new tab.

17. Select the complete implementation part


of the servlet (lines 15 – 39) and delete
the same.

18. The GithubWebhookServlet.java class


should now look similar to the
screenshot.

In the next steps you will use prepared


code snippets to implement the java
application.

19. Minimize all windows and double click


on Student (Share) on the desktop to
access the central file share.

11
CPL162

Explanation Screenshot

20. On the Student Share, navigate to


CPL162  exercises and open the file
01_GithubWebhookServlet.txt via
double-click.

Copy the complete code snippet, close


notepad, switch back to Eclipse and add
the code directly after the definition of
your Java class (line 15).

The issues reported by Eclipse will be


resolved with the following steps.

21. Replace the <queue name> with the private static final String QUEUE_NAME =<queue name>;
string "cpl162_##". This defines the
message queue that will be used to
exchange messages. The information is private static final String QUEUE_NAME = "cpl162_00";
needed in one of the coming steps of
this exercise.

Save your project: Ctrl+S

Note: Replace ## with your group


number.

22. The servlet container calls the init @Override


method exactly once after instantiating public void init() throws ServletException {
the servlet. The init method must try {
complete successfully before the servlet ConnectionFactory jmsConnectionFactory =
can receive any requests. (ConnectionFactory) new
InitialContext().lookup("java:comp/env/jms/" +
This will create a ConnectionFactory BINDING_NAME);
instance to use SAP Enterprise LOG.debug("Initialized JMS Connection Factory");
Messaging capabilities.
messagePublisher = new
Notice the BINDING_NAME which has MessagePublisher(jmsConnectionFactory);
been set to "default", as this will be
used in a later part of the script to } catch (Exception e) {
identify the destination of the Messaging LOG.error("Unexpected exception", e);
broker. throw new ServletException(e);
}
}

12
CPL162

Explanation Screenshot

23. The doPost is called by the server (via protected void doPost(HttpServletRequest request,
the service method) to allow a servlet to HttpServletResponse response) throws ServletException,
handle a POST request. The HTTP IOException {
POST method allows the client to send
data of unlimited length to the Web response.setContentType("application/json");
server a single time. PrintWriter responseWriter = response.getWriter();

This is called by the Github webhook try {


whenever there is a change in the // Read request body (GitHub push event)
Github project. The details are part of String json = requestBodyToString(request);
the request body. LOG.debug("Raw event from GitHub: {}", json);

The payload is parsed, as not all // Parse GitHub push event into an Object
information send by GitHub is used in CommitLog commitLog =
this exercise. gitHubEventParser.parsePushEvent(json);

String commitLogJson = gson.toJson(commitLog);


LOG.debug("Parsed GitHub event: {}",commitLogJson);
responseWriter.println("Received GitHub event.
Summary: " + commitLogJson);

Finally a new message is created with // Publish to queue


messagePublisher.publishMessageToQueue(QUEUE_NAME,
the parsed data and this is sent to a
specific queue on the messaging commitLogJson);
responseWriter.println("Published message to queue:
broker.
" + QUEUE_NAME);
} catch (Exception e) {
The messagePublisher object will be
LOG.error("Unexpected exception", e);
explained in the following steps.
responseWriter.println(e.toString());
}

24. You are now adding the missing classes


to the project.

In the Project Explorer, right-click on


the Java Resources node and select
New  Class

13
CPL162

Explanation Screenshot

25. As Name provide


CommitLog

Click Finish.

The newly created class


CommitLog.java will be opened in the
editor.

26. On the Student Share navigate to


CPL162  exercises and open the file
02_CommitLog.txt via double-click.

Copy the complete code snippet, close


notepad, switch back to Eclipse and add
the same directly after the definition of
your CommitLog.java class (line 4).

Save your project: Ctrl+S.

14
CPL162

Explanation Screenshot

27. The CommitLog.java class defines the


fields and interfaces we want to be able
to access from the events that we
receive from GitHub.

28. Create a new class


GitHubEventParser.

Copy the complete content of Student


Share  CPL162  exercises 
03_GitHubEventParser.txt and paste it
directly after the definition of your
GitHubEventParser.java class (line 4).

Save your project: Ctrl+S.

29. To resolve the issues reported by


Eclipse you need to fix the imports of
your GitHubEventParser.java.

Push Ctrl+Shift+O to start the


Organize Imports wizard. This will
automatically add the required imports.

Save the project (Ctrl+S).

15
CPL162

Explanation Screenshot

30. Create one more class called


MessagePublisher.

Copy the complete content of Student


Share  CPL162  exercises 
04_ MessagePublisher.txt and paste it
directly after the definition of your
MessagePublisher.java class (line 4).

Save your project: Ctrl+S.

31. To resolve the issues reported by


Eclipse we need to fix the imports of our
MessagePublisher.java.

Push Ctrl+Shift+O to start the


Organize Imports wizard. Select the
javax.jms options wherever applicable:

javax.jms.Message
javax.jms.Connection
org.slf4j.Logger
javax.jms.Queue
javax.jms.Session

Click Finish.

Save the project (Ctrl+S).

32. Select the


GithubWebhookServlet.java tab again
in the editor pane.

Push Ctrl+Shift+O to start the


Organize Imports wizard. Select
org.slf4j.Logger from the selection.

Click Finish.

Save the project (Ctrl+S).

16
CPL162

Explanation Screenshot

33. Now all classes should be in saved


state without any issues reported by
Eclipse.

34. Navigate to WebContent  WEB-INF


and open the file web.xml via double-
click.

A new tab will open. On the bottom of


the tab, change the display type to
Source, to see the XML structure.

Select the whole <welcome-file-list>


tag and delete it. It’s not needed as our
application doesn’t contain any UI files.

35. On the Student Share navigate to


CPL162  exercises and open the file
05_web_xml.txt via double-click.

Copy all its content (Ctrl+A and Ctrl+C)


and insert it into the web.xml right
before the closing </web-app> tag.

Save the project (Ctrl+S).

36. Right-click on the on the project name


and select Export  WAR file from the
menu.

The Export wizard will display.

17
CPL162

Explanation Screenshot

37. Provide

D:\Files\Session\CPL162\
CPL162_messaging_##.war

in the Destination field.

Click on Finish.

Note: Replace ## with your group


number.

Summary
Using Eclipse, you have now created an application that can receive incoming messages on the /webhook
endpoint, transform and send those messages to a queue on the messaging host. The application has been
exported so it can be deployed to the SAP Cloud Platform in the next step.
You are now able to:
• Create a simple SAP Enterprise Messaging implementation using Eclipse
• Configure the needed library dependencies for build- and runtime
• Export the application for deployment on SAP Cloud Platform

18
CPL162

DEPLOY AND CONFIGURE MESSAGING APPLICATION ON SAP CLOUD PLATFORM

Overview
Estimated time: 15 minutes

Objective
The objective of this chapter is to deploy and configure the previously created java messaging application on the
SAP Cloud Platform. Once the configuration is completed you will run the same and check the successful
execution.

Exercise Description
You will log on to the SAP Cloud Platform with the user handed out by the presenter. You will have access to a
SAP Cloud Platform account that has the SAP Cloud Platform Enterprise Messaging service already enabled.
After deploying your application, it needs to be bound to the messaging host. You will initially test the servlet with
a simple call from the browser.

19
CPL162

Explanation Screenshot

1. Open SAP Cloud Platform Cockpit


https://hana.ondemand.com

Click on Log On.

Username and Password will be


handed out by the presenter.

2. In case of getting the page to Upgrade


Your Account for SAP Cloud
Platform:

- leave the default values


- check the acknowledgement
- click Register

Close the News and Announcements


infobox.

20
CPL162

Explanation Screenshot

3. In case you are getting the message,


that your user does not have any
accounts in this region, please ask
your presenter which region to choose.

4. Once logged on, click the TechEd2017


tile present on the screen.

This is the only Global Account where


your user has permissions. Global
Account can contain several
Subaccounts.

5. Again you will see only one


Subaccount called TechEd2017. This
is the only Subaccount where your
user has access to.

One Subaccount is shared by several


participants.

Click TechEd2017 tile.

21
CPL162

Explanation Screenshot

6. The Overview page shows the status


of the main SAP Cloud Platform
services and resources accessible in
this subaccount.

In the following steps will further


explore some of the features in the
Applications and Services section.

7. From the navigation bar expand the


Applications entry.

Click on Java Applications.

Note: Your screen might differ from the


screenshot, as the subaccount is
shared among several participants,
who might have already deployed
some applications.

22
CPL162

Explanation Screenshot

8. Click on Deploy Application.

Browse the path of war file and select


D:\Files\Session\CPL162\
CPL607_messaging_##.war

The default application name is


changed, removing the “_”:
cpl162messaging##

Select the runtime name:


Java Web Tomcat 8

Click on Deploy.

Note: Replace ## with your group


number.

9. After Deployment has finished click on


Start.

10. Now you can see your messaging


application is deployed, after some
time the status will change to Started.

23
CPL162

Explanation Screenshot

11. From the navigation pane select the


Services entry.

Either use the search field in the upper


right corner, or scroll down to find the
Enterprise Messaging tile in the
Integration section.

Click Enterprise Messaging.

12. From the navigation pane, select


Application Bindings.

Click Create Application Binding.

Note: Your screen might differ from the


screenshot, as the subaccount is
shared among several participants,
who might have already create some
application bindings.

13. Select your own cpl162messaging##


application from the Java Application
dropdown.

Messaging Host is defaulted to


demomsghost, as there is only one
host assigned to this account.

Provide default as the Application


Binding. This has to match the binding
name provided in step 22. With this the
java application can make use of the
SAP Enterprise Messaging service.

Click Save to proceed.


private static final String BINDING_NAME = "default";

24
CPL162

Explanation Screenshot

14. From the navigation pane select


Messaging Hosts.

The page displays an overview of the


available Messaging Hosts available
for this account including current
Connections and amount of
Messages.

Click on demomsghost entry to


display further information and options.

15. You are presented with further details


of the selected Messaging Host.

Select Queues from the navigation


pane.

Click to create
a new queue.

16. Provide

Queue Name: cpl162_##


Access Type: Exclusive

Click on Save.

Note: The queue name needs to be


identical to the queue name provided in
step 21 of the implementation.

private static final String QUEUE_NAME = "cpl162_00";

17. From the breadcrumbs select the


subaccount TechEd2017.

Select Java Applications from the


navigation pane.

25
CPL162

Explanation Screenshot

18. Search your own messaging


application from the list of available
Java applications.

Click on your application’s name:


cpl162messaging##

Note: Replace ## with your group


number.

19. Further details of your application are


being displayed.

Click on the Application URL.

20. You will be presented with a HTTP


Status [404] – [Not Found] error
page.

You need to add /webhook to the end


of your URL as this was defaulted
endpoint in the
GithubWebhookServlet.java class of
the implementation.

21. Opening the full URL (including


/webhook) will call the doGet() method
of the servlet implementation.

This URL will be needed in the


following steps.

Summary
You have now deployed your messaging application on the SAP Cloud Platform and bound the same to the SAP
Enterprise Messaging host. Furthermore, you have defined the queue that is holding the messages.
You are now able to:
• Logon to SAP Cloud Platform and deploy messaging application
• Bind application to messaging host
• Define queue on messaging host

26
CPL162

CONFIGURE & TEST GITHUB WEBHOOK

Overview
Estimated time: 10 minutes

Objective
The objective of this chapter is to do the necessary configuration on GitHub in order to connect to the SAP Cloud
Platform application created in the previous steps. At the end of this chapter you will receive new messages
inside the defined queue for each new commit on the GitHub repository.

Exercise Description
You will logon to GitHub, create a new repository or re-use an existing repository. In the setting of this repository
the webhook endpoint of the SAP Cloud Platform application will be provided. Webhooks allow external services
to be notified when certain events happen within your repository. When the specified events happen, we’ll send
a POST request to each of the URLs you provide. At the end you will commit changes to the GitHub repository
and you will check, that these events will create messages in the defined messaging queue.

Explanation Screenshot

1. Log on to GitHub with your personal


user, or sign up for a new account.

You will need a valid email address as


a verification email will be sent to the
same.

2. From the Create new… menu on the


top right corner, select New repository

Note: You can also use any existing


repository inside your account.

27
CPL162

Explanation Screenshot

3. Provide a repository name like


CPL162_##.

Select Public as the type of the


repository

Check Initialize this repository with a


README, this file will be used to
commit changes.

Click Create repository.

Note: Replace ## with your group


number.

4. The newly create repository is being


displayed including the initial
README.md file.

Click on Settings.

5. From the setting menu choose


Webhooks.

In the upper right corner select


Add webhook.

28
CPL162

Explanation Screenshot

6. If needed, provide the password for


your GitHub user again.

7. As the Payload URL provide the


endpoint of the servlet created in the
previous steps (see previous chapter
step 21). This includes the /webhook
part of the URL.

As the Content type select


application/json. The parser
(GitHubEventParser.java) for the
messages has been designed to
consume payloads in JSON format.

Leave the provided default for the


remaining options.

Click Add webhook.

Note: more details on GitHub’s


webhook events can be found here:
https://developer.github.com/webhooks

29
CPL162

Explanation Screenshot

8. The webhook has been successfully


added.

Click on <> Code to get back to the


content of your repository.

9. Click on the README.md file to edit


the same.

10. Set the file into edit mode.

11. Add some new text to the


README.md file:

**Welcome to SAP TechEd 2017**

Leave all other values as defaulted and


click Commit changes.

30
CPL162

Explanation Screenshot

12. On the SAP Cloud Platform Cockpit,


navigate back to the overview of
available queues on the given
messaging host (see previous chapter
steps 11ff).

Services  Enterprise Messaging 


Messaging Hosts

Select messaging host


demomsghost  Queues

Search for the queue


(cpl162_##) assigned to your
messaging application in the previous
chapter step 16.

With each new commit on the GitHub


repository you can see that the number
of messages on the queue is
increasing.

Summary
You have now configured the GitHub repository to send events to the webhook exposed by the previously
created SAP Cloud Platform application. The success can be seen by the messages in the messaging queue.

You are now able to:


• Add webhook to GitHub repository configuration
• Do changes on the repository and commit them
• Check the status of the queue

31
CPL162

OPTIONAL: CHECK LOG ENTRIES

Overview
Estimated time: 5 minutes

Objective
The objective of this chapter is to configure the logging mechanism for your SAP Cloud Platform application

Exercise Description
You will change the logging setting for your java application. Specific loggers will be set to DEBUG mode, to see
the logs written by your implementation.

32
CPL162

Explanation Screenshot

1. Switch back to the tab/window


showing your messaging application
details.

From the navigation pane expand


Monitoring and select Logging.

2. Click Configure Loggers.

As Filter provide: com.sap.teched

Set log level of all loggers in the list to:


DEBUG

Click Set.

Click Close.

33
CPL162

Explanation Screenshot

3. In your GitHub repository change the


README.md file again and
Commit the change.

4. Back in the SAP Cloud Platform


Dashboard, under Default Traces
click on the Display icon to see the
logs.

5. From the logs you can see that an


event has been received from GitHub
and a message has been published to
the queue.

Especially for the Raw GitHub event


you can display the details by clicking
the icon in the respective row.
This will show the whole payload that
has been received.

Summary
You have configured the logs to show debug information, to verify that your messaging application is working
properly.
You are now able to:
• Configure logs on SAP Cloud Platform
• Verify a SAP Enterprise Messaging application is working properly

34
CPL162

CREATE SAP HANA DATABASE TABLE

Overview
Estimated time: 10 minutes

Objective
The objective of this chapter is to create a table on the SAP HANA database. The database will be bound to the
java application, so it can be used during runtime.

Exercise Description
You will use the SAP HANA Web-based Development Workbench to create a new table on the SAP HANA
database. This table will be used to store the messages being sent to the messaging queue. This chapter will be
completed by checking the content of the table and binding the database to your java application, so it can be
accessed during runtime.

Explanation Screenshot

1. From the breadcrumbs select the


subaccount TechEd2017.

From the navigation pane expand


SAP HANA / SAP ASE and select the
entry Databases & Schemas.

There is only one DB/Schema ID


assigned to this account. Click on the
hanaxs01 entry.

2. The Overview page for the selected


database is being displayed.

Click on the SAP HANA Web-Based


Development Workbench link.

35
CPL162

Explanation Screenshot

3. Provide

username: the p-user handed out to


you by the presenter

password: Welcome2TechEd17

The password must be changed on


first logon.

4. Click on the Catalog tile.

Catalog is a tool providing the function


of developing and maintaining the
runtime objects.

5. The Catalog is loaded in a new tab.

From the menu bar open the SQL


Console (Ctrl+Alt+C).

36
CPL162

Explanation Screenshot

6. In the SQL tab provide the statement:

CREATE COLUMN TABLE


GITHUB_PUSH_LOG (
MSG VARCHAR(255),
COMMITTED_ON TIMESTAMP,
COMMITTER VARCHAR(255) );

Execute the statement by pressing


F8.

The log is indicating that the creation


was successfully executed.

7. In the tree on the left side expand


Catalog  <P-User>  Tables

Right-click on the
GITHUB_PUSH_LOG table and
select Open Content from the menu.

Note: replace <P-User> with the


p-user handed out to you by the
presenter.

37
CPL162

Explanation Screenshot

8. Initially the table is still empty as it has


just been created.

Leave the tab open in the browser,


you will check again after doing
additional commits on the GitHub
repository.

9. Switch back to the SAP Cloud


Platform Cockpit and select the
overview page for your messaging
application.

From the navigation panel expand


Configuration and select Data
Source Bindings.

Click on New Binding.

38
CPL162

Explanation Screenshot

10. Leave the Data Source name as


<default>.

The DB/Schema ID is set to


hanaxs01, as this is the only one
assigned to this account.

Enter the custom logon details:

Database user: the p-user handed


out to you by the presenter

Password: The specified database


user’s password.

Select the checkbox Verify


credentials to verify the validity of the
custom logon data.

Click Save.

Note: The initial password of this


database user needs to be changed
before binding the application to an
SAP HANA database, since the
application will otherwise throw an
exception.

Summary
Using the SAP HANA Web-based Development Workbench you have created a new table on the database via
SQL script. You know how to check the content of the table and how to bind the database to your java
application.

You are now able to:


• Use SAP HANA Web-based Development Workbench
• Create a new table on the database
• Check the content of a table
• Bind the database to your application for runtime usage

39
CPL162

ENHANCE MESSAGING APPLICATION TO CONSUME MESSAGES FROM MESSAGING QUEUE

Overview
Estimated time: 20 minutes

Objective
The objective of this chapter is to enhance the existing messaging application to consume the messages from
the queue and store them into the table inside the HANA database.

Exercise Description
You will enhance the implementation of the messaging application. In Eclipse you will add classes that provide
the capabilities to consume messages from the messaging queue, transform them to store them in the SAP
HANA database via SQL insert.

Explanation Screenshot

1. Switch back to Eclipse and open the


GithubWebhookServlet.java class in
the editor.

In the following steps you are going to


enhance the implementation to
consume the messages put into the
queue and write it into the previously
created table on a HANA database.

2. On the Student Share navigate to


CPL162  exercises and open the file
06_GithubWebhookServlet.txt via
double-click.

Copy the complete code snippet and


add the same inside the init() method
directly after the line

messagePublisher =
new MessagePublisher
(jmsConnectionFactory);

and before

} catch (Exception e) {

inside GithubWebhookServlet.java
class.

Save your project: Ctrl+S.

40
CPL162

Explanation Screenshot

3. Create a new class CommitLogDao.

Copy the complete content of Student


Share  CPL162  exercises  07_
CommitLogDao.txt and paste it
directly after the definition of your
CommitLogDao.java class (line 4).

Save your project: Ctrl+S.

4. To resolve the issues reported by


Eclipse we need to fix the imports of
the CommitLogDao.java class.

Push Ctrl+Shift+O to start the


Organize Imports wizard. Select the
java(x).sql options wherever
applicable:

java.sql.Connection
org.slf4j.Logger
javax.sql.DataSource

Click Finish.

Save the project (Ctrl+S).

41
CPL162

Explanation Screenshot

5. Let’s have a closer look at the public void insertInDb(CommitLog commitLog) throws
implementation of SQLException, NamingException {
CommitLogDao.java:
Connection connection = datasource.getConnection();
The datasource (in this case the
connection to the HANA database) is try {
passed during initialization of the PreparedStatement pstmt =
object. connection.prepareStatement("INSERT INTO
GITHUB_PUSH_LOG (MSG, COMMITTED_ON, COMMITTER)
An SQL statement is prepared to insert VALUES (?, ?, ?)");
the details sent by the GitHub webhook pstmt.setString(1, commitLog.getMessage());
event into the HANA database. pstmt.setString(2, commitLog.getTimestamp());
pstmt.setString(3, commitLog.getCommitter());
The values will be inserted in a table pstmt.executeUpdate();
called GITHUB_PUSH_LOG. LOG.debug("Record inserted in database: {}", commitLog);
} finally {
if (connection != null) {
connection.close();
}
}
}

6. Create a new class MessageReceiver.

Copy the complete content of Student


Share  CPL162  exercises 
08_MessageReceiver.txt and paste it
directly after the definition of your
MessageReceiver.java class (line 4).

Save your project: Ctrl+S.

42
CPL162

Explanation Screenshot

7. To resolve the issues reported by


Eclipse we need to fix the imports of
our MessagePublisher.java.

Push Ctrl+Shift+O to start the


Organize Imports wizard. Select the
javax.jms options wherever applicable:

javax.jms.Message
javax.jms.Connection
org.slf4j.Logger
javax.jms.Queue
javax.jms.TextMessage
javax.jms.Session

Click Finish.

Save the project (Ctrl+S).

8. Inside the MessagePublisher.java public void startQueueListener(String queueName) throws


class the most interesting part is the JMSException, NamingException {
startQueueListener(String Connection con = jmsConnectionFactory.createConnection();
queueName) method.
// Start connection
A connection to the messaging host is con.start();
established by using the
jmsConnectionFactory. Session session = con.createSession(false,
Session.AUTO_ACKNOWLEDGE);
With the registered Queue q = session.createQueue(queueName);
MessageConsumer the onMessage()
method is executed whenever a new MessageConsumer c = session.createConsumer(q);
message arrives on the specified c.setMessageListener(new MessageListener() {
queue. With that the message gets public void onMessage(Message message) {
consumed, transformed in the correct try {
format and will be inserted into the String json = ((TextMessage) message).getText();
HANA database via the LOG.debug("Message received in queue: {}", json);
CommitLogDao object explained in
the previous steps. // Insert in database
CommitLog commitLog = gson.fromJson(json,
CommitLog.class);

commitLogDao.insertInDb(commitLog);

} catch (Exception e) {
LOG.error("Unexpected exception", e);
}
}
});

LOG.debug("Started queue listener");


}

43
CPL162

Explanation Screenshot

9. Select the
GithubWebhookServlet.java tab
again in the editor pane.

Push Ctrl+Shift+O to start the


Organize Imports wizard. Select
javax.sql.DataSource from the
selection.

Click Finish.

Save the project (Ctrl+S).

10. Having a closer look at the changes


inside the init() method of
GithubWebhookServlet.java.
Remember the init() method is
executed when starting the messaging
application on SAP Cloud Platform.

datasource is assigned the information DataSource datasource = (DataSource) new


of the default database for this account. InitialContext().lookup("java:comp/env/jdbc/DefaultDB");
This is needed to access the database.
The binding was done in the previous LOG.debug("Initialized HANA Data Source");
chapter step 10.

The messageReceiver is initiated with MessageReceiver messageReceiver = new


information how to access the MessageReceiver(jmsConnectionFactory, new
messaging provider, as well as how to CommitLogDao(datasource));
write to the database.

Finally it starts listening to incoming messageReceiver.startQueueListener(QUEUE_NAME);


messages on the defined messaging
queue.

44
CPL162

Explanation Screenshot

11. Right-click on the on the project name


and select Export  WAR file from
the menu.

The Export wizard will display.

12. Provide

D:\Files\Session\CPL162\
CPL162_messaging_##.war

in the Destination field.

Check the option to


Overwrite existing file.

Click on Finish.

Note: Replace ## with your group


number.

13. Switch back to the SAP Cloud


Platform Cockpit and select the
overview page for your messaging
application.

Click on the Update button.

45
CPL162

Explanation Screenshot

14. Browse the path of war file and select


(D:\Files\Session\CPL162\
CPL162_messaging_##.war)

Leave defaulted values for all


remaining options.

Click on Update.

15. You’ll get the information that the


updated application needs to be
restarted.

Click Done.

46
CPL162

Explanation Screenshot

16. In the overview page for your


messaging application, scroll all the
way down to the bottom.

In the Processes section you’ll find the


action to restart your application.

Alternatively, you can Stop and Start


your application.

Summary
Using Eclipse, you have enhanced the messaging application to consume messages from a queue on the
messaging host. The application has been updated on the SAP Cloud Platform and has been restarted.

You are now able to:


• Create a simple SAP Enterprise Messaging consumer application
• Update an existing application on SAP Cloud Platform
• Restart a java application on SAP Cloud Platform

47
CPL162

VERIFY END 2 END FLOW: GITHUB WEBHOOK TO SAP HANA DATABASE

Overview
Estimated time: 10 minutes

Objective
The objective of this chapter is to test the scenario end to end: Commit changes on GitHub and store the
information inside the SAP HANA database.

Exercise Description
You will commit changes on the configured GitHub repository and verify that messages are stored in the SAP
HANA database by using the SAP HANA Web-based Development Workbench.

Explanation Screenshot

1. Once your messaging application


has been restarted, switch back to
your GitHub repository, do another
change to the README.md and
commit the same.

2. Back in the SAP HANA Web-based


Development Workbench, refresh
the content of your
GITHUB_PUSH_LOG table.

You should see a new entry for


each new commit on your GitHub
repository.

48
CPL162

Explanation Screenshot

3. Switch back to the tab/window


showing your messaging application
details and from the navigation pane
expand Monitoring and select
Logging.

Note: If you have completed the


optional exercise on checking log
entries, you can skip to step 5.

4. Click Configure Loggers.

As Filter provide: com.sap.teched

Set log level of all loggers in the list


to: DEBUG

Click Set.

Click Close.

5. Under Default Traces click on the


Display icon to see the logs.

Note: there might exist several


trace files. Select the latest file on
top of the list.

49
CPL162

Explanation Screenshot

6. From the logs you can see the


sequence of events implemented in
this complete exercise:

Initialized JMS Connection Fact…


Initialized HANA Data Source
Started queue listener
Raw event from GitHub: {…}
Published message to queue: …
Message received in queue: {…}
Record inserted in database: …

Especially for the Raw event from


GitHub you can display the details
by clicking the icon in the
respective row. This will show the
whole payload that has been
received.

Summary
Using the SAP HANA Web-based Development Workbench, as well as the logging entries, you have verified
that GitHub events are stored inside the SAP HANA database.

You are now able to:


• Check the content of a table
• Configure logs on SAP Cloud Platform
• Verify a SAP Enterprise Messaging application is working properly

50
www.sap.com/contactsap

© 2017 SAP SE or an SAP affiliate company. All rights reserved.


No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP SE or an SAP affiliate company.

The information contained herein may be changed without prior notice. Some software products marketed by SAP SE and its distributors contain proprietary software components of other software vendors.
National product specifications may vary.

These materials are provided by SAP SE or an SAP affiliate company for informational purposes only, without representation or warranty of any kind, and SAP or its affiliated companies shall not be liable
for errors or omissions with respect to the materials. The only warranties for SAP or SAP affiliate company products and services are those that are set forth in the express warranty statements
accompanying such products and services, if any. Nothing herein should be construed as constituting an additional warranty.

In particular, SAP SE or its affiliated companies have no obligation to pursue any course of business outlined in this document or any related presentation, or to develop or release any functionality
mentioned therein. This document, or any related presentation, and SAP SE’s or its affiliated companies’ strategy and possible future developments, products, and/or platform directions and functionality are
all subject to change and may be changed by SAP SE or its affiliated companies at any time for any reason without notice. The information in this document is not a commitment, promise, or legal obligation
to deliver any material, code, or functionality. All forward-looking statements are subject to various risks and uncertainties that could cause actual results to differ materially from expectations. Readers are
cautioned not to place undue reliance on these forward-looking statements, and they should not be relied upon in making purchasing decisions.

SAP and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP SE (or an SAP affiliate company) in Germany and other
countries. All other product and service names mentioned are the trademarks of their respective companies. See http://www.sap.com/corporate-en/legal/copyright/index.epx for additional trademark
information and notices.

You might also like