CL 201

Download as pdf or txt
Download as pdf or txt
You are on page 1of 126

CLD200

SAP Extension Suite

.
.
EXERCISES AND SOLUTIONS
.
Course Version: 20
Course Duration: 5 Hours 20 Minutes
Material Number: 50159340
SAP Copyrights, Trademarks and
Disclaimers

© 2022 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.
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. Please see https://www.sap.com/corporate/en/legal/copyright.html for additional
trademark information and notices.
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 may have been machine translated and may contain grammatical errors or
inaccuracies.
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 SE or its affiliated companies shall not be liable
for errors or omissions with respect to the materials. The only warranties for SAP SE 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, which speak
only as of their dates, and they should not be relied upon in making purchasing decisions.

© Copyright. All rights reserved. iii


Typographic Conventions

American English is the standard used in this handbook.


The following typographic conventions are also used.

This information is displayed in the instructor’s presentation

Demonstration

Procedure

Warning or Caution

Hint

Related or Additional Information

Facilitated Discussion

User interface control Example text

Window title Example text

© Copyright. All rights reserved. iv


Contents

Unit 1: SAP Business Technology Platform (BTP)

No exercises

Unit 2: Development Environment and CAP-Project

1 Exercise 1: Create a Dev Space for Business Applications


4 Exercise 2: Create a CAP-Based Service

Unit 3: User Interface and Business Logic

15 Exercise 3: Generate a User Interface Using SAP Fiori Elements


31 Exercise 4: Add Custom Business Logic to Your Application

Unit 4: External Services

36 Exercise 5: Add an External Service

Unit 5: Manual Deployment

51 Exercise 6: Deploy SAP BTP Cloud Foundry Applications Manually

Unit 6: Authorization and Trust Management

67 Exercise 7: Define Restrictions and Roles in CDS


73 Exercise 8: Set Up SAP Authorization and Trust Management
78 Exercise 9: Create an Application Router
82 Exercise 10: Add Approuter to MTA
86 Exercise 11: Assign Role Collections

Unit 7: Automated Deployment

91 Exercise 12: Create and Connect a GitHub Repository


96 Exercise 13: Enable SAP Continuous Integration and Delivery
104 Exercise 14: Configure a CI/CD Job
109 Exercise 15: Configure the Stages of a CI/CD Pipeline
112 Exercise 16: Verify Build Success

Unit 8: Connection of an SAP S/4HANA Cloud System as an External


Service for CAP

No exercises

Unit 9: Case Study (ILT Only)

115 Exercise 17: Case Study: Create an Application for the Orders of a
Retail Store

© Copyright. All rights reserved. v


© Copyright. All rights reserved. vi
Unit 2
Exercise 1
Create a Dev Space for Business Applications

Business Scenario
In this exercise, you will access the training landscape and create a dev space for business
applications -- a preconfigured development environment with the required tools and
extensions for a specific scenario.
In the second task of this exercise, you will perform the steps from the following tutorial:
https://developers.sap.com/tutorials/appstudio-devspace-create.html

Task 1: Log On to the Training System and Access SAP Business Application Studio

1. Logon to the training system with the credentials given by your instructor.

2. In the training environment start the Chrome Browser.

3. Access the SAP BTP Cockpit and sign in to your subaccount.

4. Start the application SAP Business Application Studio.

Task 2: Configure Your Preconfigured dev Space

1. Configure your preconfigured dev space.

© Copyright. All rights reserved. 1


Unit 2
Solution 1
Create a Dev Space for Business Applications

Business Scenario
In this exercise, you will access the training landscape and create a dev space for business
applications -- a preconfigured development environment with the required tools and
extensions for a specific scenario.
In the second task of this exercise, you will perform the steps from the following tutorial:
https://developers.sap.com/tutorials/appstudio-devspace-create.html

Task 1: Log On to the Training System and Access SAP Business Application Studio

1. Logon to the training system with the credentials given by your instructor.
a) Your trainer will show you, how you can access the training landscape.

2. In the training environment start the Chrome Browser.


a) Choose Windows → Google Chrome.

3. Access the SAP BTP Cockpit and sign in to your subaccount.


a) In the browser enter the URL cockpit.eu10.hana.ondemand.com

b) Sign in to the BTP Cockpit with user and password given by your instructor.

c) In the Account Explorer, under Directories and Subaccounts, click on the subaccount to
access your subaccount.

4. Start the application SAP Business Application Studio.


a) On subaccount level, in the left navigation bar, choose Services → Instances and
Subscriptions.

b) Under Subscriptions click on the Application SAP Business Application Studio to open
it.

Task 2: Configure Your Preconfigured dev Space

1. Configure your preconfigured dev space.


a) In SAP Business Application Studio, choose Create Dev Space.

b) Choose a name for your dev space.

© Copyright. All rights reserved. 2


Solution 1: Create a Dev Space for Business Applications

c) As the Application Type choose Full Stack Cloud Application.

Note:
By selecting SAP Cloud Business Application, your dev space comes with
several extensions out-of-the-box that you need to develop CAP
applications. For example, CDS tools, Java Tools, and MTA Tools.

d) Choose Create Dev Space.

Note:
The creation of the dev space takes a while. You see that the status for
your dev space will change from STARTING to RUNNING.

e) Once the dev space is running, click the dev space name to open it.

© Copyright. All rights reserved. 3


Unit 2
Exercise 2
Create a CAP-Based Service

Business Scenario
You will create a new SAP Cloud Application Programming Model (CAP) project. This project
provides the basis for your risk-management extension that comprises:
● A database that stores application data.
● A service that exposes the application data from the database via application
programming interfaces (APIs).
● A user interface that consumes the application data from the service and presents it to the
end users.

In this part of the course, you create:


● A data model
● A service definition

The data model defines what kind of data your application contains, how it is structured, and
how it will be stored in the database.
The service definition defines which part of your data should be exposed as a service via APIs.

Task Flow
In this exercise, you will perform the following tasks:
● Create an SAP CAP project from our provided template on GitHub.
● Describe the role of a data model.
● Describe the purpose of a service definition.
● Add a data model to a project.
● Create a service definition.
● Add an OData service definition to a project.
● Provide Mock data in a CSV file for the project.

Prerequisites
You have successfully accessed your SAP BTP subaccount.
You have added and opened your Dev Space for Business Applications in SAP Business
Application Studio.

Task 1: Create and Initialize the Project

1. Create and Initialize the Project.

© Copyright. All rights reserved. 4


Exercise 2: Create a CAP-Based Service

Task 2: Add a Data Model to the Project


Now, you create a data model using the Core Data Services (CDS) format from CAP.

1. Add a Data Model to the Project.

Task 3: Add a Service to the Project


In this part you will create a new service with two entities. Both are projections of the data
models that we created in the chapter before. A service provides an interface to the
application. It enables other applications and users outside of the application to interact with
it. In this case, the service let's us interact with the Risksand Mitigationsentities, thus the
data within the application.

1. Add a Service to the Project.

Task 4: Provide Mock Data for the Service


In CAP there is a way to provide mock data for the created entities. The data is stored in a
local database called SQLite that CAP invokes behind the scenes. CAP makes it easy to add
such test data to a service. All it needs is a Comma Separated Values (CSV) file that contains
the entities' elements as column headers. Note that the separation of values in this case has
to be done using semicolons (;) by convention.

1. Provide Mock Data for the Service.

You have added a data model, data, and a service definition to your project. Next, you will
create a UI for your application.

© Copyright. All rights reserved. 5


Unit 2
Solution 2
Create a CAP-Based Service

Business Scenario
You will create a new SAP Cloud Application Programming Model (CAP) project. This project
provides the basis for your risk-management extension that comprises:
● A database that stores application data.
● A service that exposes the application data from the database via application
programming interfaces (APIs).
● A user interface that consumes the application data from the service and presents it to the
end users.

In this part of the course, you create:


● A data model
● A service definition

The data model defines what kind of data your application contains, how it is structured, and
how it will be stored in the database.
The service definition defines which part of your data should be exposed as a service via APIs.

Task Flow
In this exercise, you will perform the following tasks:
● Create an SAP CAP project from our provided template on GitHub.
● Describe the role of a data model.
● Describe the purpose of a service definition.
● Add a data model to a project.
● Create a service definition.
● Add an OData service definition to a project.
● Provide Mock data in a CSV file for the project.

Prerequisites
You have successfully accessed your SAP BTP subaccount.
You have added and opened your Dev Space for Business Applications in SAP Business
Application Studio.

Task 1: Create and Initialize the Project

1. Create and Initialize the Project.

© Copyright. All rights reserved. 6


Solution 2: Create a CAP-Based Service

a) In the Business Application Studio, click on Terminal → New Terminal.


A new terminal opens in the lower right part of the Business Application Studio screen.

b) Enter the following commands to clone the starter template from GitHub and press
Enter after each command.
mkdir ~/projects/risk-management
cd ~/projects/risk-management/
git clone https://github.com/SAP-samples/extension-suite-learning-
journey ./

The output in the terminal should then look similar to the following. (Currently there
are 23 files in the repository. In the future this could differ).

So the template from GitHub has been cloned successfully. Next, open it in the project
explorer.

c) On the Welcome page, click on Files & Folders.

d) Now select the risk-management folder in the projects folder and click on Open. The
SAP Business Application Studio will now reload to open the folder.

© Copyright. All rights reserved. 7


Unit 2: Development Environment and CAP-Project

e) On the left side you will now see the content of the risk-management folder:

f) In Business Application Studio choose Terminal → New Terminal from its menu.
A new terminal opens in the lower right part of the Business Application Studio screen.

g) In the terminal, run the command


npm ci
This might take a while. It installs all the dependencies of your project, which are listed
in the package.json and package-lock.jsonfile, into a new folder called
node_modules within the root of your project. If you encounter messages about
Deprecateddependencies ignore them for now, as long as there are no errors in the
log.

h) In the terminal, start a CAP server by typing:


cds watch
The CAP server serves all the CAP sources from your project. It also “watches” all the
files in your projects and conveniently restarts the server whenever you save a file.
Changes you've made will immediately be served without you having to do anything.

i) The terminal now looks like this:

© Copyright. All rights reserved. 8


Solution 2: Create a CAP-Based Service

cds watch tells you that there’s no model yet that it can serve. You add one in the
next steps.
In general, you can keep cds watch running in a terminal for the whole exercise.
There is no need to restart it or try to add a second instance of it (in fact, if you do this,
you get an error, described here). In the follow-up chapters, you will open a new
browser tab to see the results of cds watch. You can just keep this open and refresh
it each time there is a change. cds watch notices any file change and makes sure you
get the new results after a refresh in the browser.

Task 2: Add a Data Model to the Project


Now, you create a data model using the Core Data Services (CDS) format from CAP.

1. Add a Data Model to the Project.


a) In the project, go to folder db, representing the data model on the database. In the
context menu, select New File.

b) Enter schema.cds as a name.

c) Click on the new file in the explorer.


An editor opens.

d) Enter the following lines into the editor


namespace riskmanagement;
using { managed } from '@sap/cds/common';

entity Risks : managed {


key ID : UUID @(Core.Computed : true);
title : String(100);
owner : String;
prio : String(5);
descr : String;
miti : Association to Mitigations;
impact : Integer;
//bp : Association to BusinessPartners;
// You will need this definition in a later step
criticality : Integer;
}

entity Mitigations : managed {


key ID : UUID @(Core.Computed : true);
descr : String;
owner : String;
timeline : String;
risks : Association to many Risks on risks.miti = $self;
}

e) Save the file


You are using the namespace1 riskmanagement. A namespace is optional. It is helpful
to use short unique names without bloating the code with fully qualified names.

© Copyright. All rights reserved. 9


Unit 2: Development Environment and CAP-Project

Essentially, namespaces are just prefixes that are applied to all relevant names in a file
automatically.
The code creates 2 entities in the namespace riskmanagement, Risks, and
Mitigations. Each of them has a key called ID and several other properties. A Risk
has a mitigation and therefore, the property miti has an association to exactly one
Mitigation. A Mitigation in turn can be used for many Risks, so it has a “to
many” association. The key is automatically filled by CAP, which is exposed to the user
of the service with the annotation @(Core.Computed : true).
At this point, you can ignore the commented property bp (as well as the other
commented lines further down in the file and in subsequent files and chapters). You
will use the commented lines at a later stage of the project.
The screen now looks like this:

Notice how cds watch reacted to dropping the file. It now tells you that it has a model
but there are no service definitions yet and thus it still can’t serve anything. So, you will
add a service definition.

Task 3: Add a Service to the Project


In this part you will create a new service with two entities. Both are projections of the data
models that we created in the chapter before. A service provides an interface to the
application. It enables other applications and users outside of the application to interact with
it. In this case, the service let's us interact with the Risksand Mitigationsentities, thus the
data within the application.

1. Add a Service to the Project.


a) In the project, go to folder srv/, representing the service. In the context menu, select
New File.

b) Enter risk-service.cds as a name.

c) Click on the new file in the explorer.


An editor opens.

© Copyright. All rights reserved. 10


Solution 2: Create a CAP-Based Service

d) Enter the following lines into the editor:


using { riskmanagement as rm } from '../db/schema';

@path: 'service/risk'
service RiskService {
entity Risks as projection on rm.Risks;
annotate Risks with @odata.draft.enabled;
entity Mitigations as projection on rm.Mitigations;
annotate Mitigations with @odata.draft.enabled;
//@readonly entity BusinessPartners as projection on
rm.BusinessPartners;
}

This creates a new service RiskService in the namespace riskmanagement. The


annotation @path: 'service/risk' tells the CAP framework to expose the
RiskService at URL path service/risk. The service exposes two entities (again,
just ignore the commented part for the business partner), Risks and Mitigations,
which are both just exposing the entities of the database schema you’ve created in the
step before. The @odata.draft.enabled annotation enables edit sessions with draft
states2 stored on the server for the UI, that will be added in a later step.
If you again look at the terminal, you see that cds watch has noticed the new file and
now tells us that it serves something:

e) Press the Open in New Tab button in the lower right corner.

f) If you are asked to enter a name - just press return.


You now see this screen:

© Copyright. All rights reserved. 11


Unit 2: Development Environment and CAP-Project

g) Click the $metadata link:


The service already exposes a full-blown OData metadata document.

h) Go back and click on the Risks link.


This exposes the data for the Risks entity. Since there are already files in the db/
datadirectory containing mock data for the database, you will already see data here.

Note:
To see the JSON data in a structured way as shown in the screenshot, you
require a browser extension. Without such an extension, the data will just
be displayed as plaintext without indentations etc.

Note:
There are a few additional fields like createdAt or modifiedBy which you
did not actively define in the entity itself. These were added by CAP,
because you added the managed aspect in the entity definition:
entity Risks : managed{
...
}

Don't close the window, you will need it again.

© Copyright. All rights reserved. 12


Solution 2: Create a CAP-Based Service

Task 4: Provide Mock Data for the Service


In CAP there is a way to provide mock data for the created entities. The data is stored in a
local database called SQLite that CAP invokes behind the scenes. CAP makes it easy to add
such test data to a service. All it needs is a Comma Separated Values (CSV) file that contains
the entities' elements as column headers. Note that the separation of values in this case has
to be done using semicolons (;) by convention.

1. Provide Mock Data for the Service.


a) In the project, go to folder db/ and then into the data/ folder

b) There is one file called riskmanagement-Risks.csv:


ID;createdAt;createdBy;title;owner;prio;descr;miti_id;impact;
20466922-7d57-4e76-b14c-e53fd97dcb11;2019-10-24;SYSTEM;CFR non-
compliance;Fred Fish;3;Recent restructuring might violate CFR code
71;20466921-7d57-4e76-b14c-e53fd97dcb11;10000;
20466922-7d57-4e76-b14c-e53fd97dcb12;2019-10-24;SYSTEM;SLA violation
with possible termination cause;George Gung;2;Repeated SAL violation
on service delivery for two successive quarters;20466921-7d57-4e76-
b14c-e53fd97dcb12;90000;
20466922-7d57-4e76-b14c-e53fd97dcb13;2019-10-24;SYSTEM;Shipment
violating export control;Herbert Hunter;1;Violation of export and
trade control with unauthorized downloads;20466921-7d57-4e76-b14c-
e53fd97dcb13;200000;

In a table format, the header and one line of the file content look like the following:
ID create- crea- title owner prio descr miti_id impact
dAt tedBy
204669 2019-1 SYS- CFR Fred 3 Recent 204669 10000
22-7d5 0-24 TEM non- Fish restruc- 21-7d57
7-4e76- compli- turing -4e76-
b14c- ance might b14c-
e53fd9 violate e53fd9
7dcb11 CFR 7dcb11
code 71

c) There is also another file for the Mitigations entity called riskmanagement-
Mitigations.csv.

d) Click on the file in the explorer:


ID;createdAt;createdBy;descr;owner;timeline
20466921-7d57-4e76-b14c-e53fd97dcb11;2019-10-24;SYSTEM;SLA violation:
authorize account manager to offer service credits for recent delivery
issues;suitable BuPa;Q2 2020
20466921-7d57-4e76-b14c-e53fd97dcb12;2019-10-24;SYSTEM;"SLA
violation: review third party contractors to ease service delivery
challenges; trigger budget review";suitable BuPa;Q3 2020
20466921-7d57-4e76-b14c-e53fd97dcb13;2019-10-24;SYSTEM;Embargo
violation: investigate source of shipment request, revoke
authorization;SFSF Employee with link possible?;29.03.2020
20466921-7d57-4e76-b14c-e53fd97dcb14;2019-10-24;SYSTEM;Embargo
violation: review shipment proceedure and stop delivery until further
notice;SFSF Employee with link possible?;01.03.2020

The files have the name of the namespace of the entities in the data model (for
example: riskmanagement), followed by a '-' and the name of the entity (for

© Copyright. All rights reserved. 13


Unit 2: Development Environment and CAP-Project

example: Risks). When adhering to this naming convention, CAP recognizes the file as
data for the data model and automatically adds it to the built-in SQLite database.
Looking at the contents of the file riskmanagement-Risks.csv, the first line contains all
the properties from your Risks entity. While the other ones are straightforward,
consider the miti_id property. In your entity, you only have a miti property, so where
does this come from? miti is an association to Mitigations, as Mitigations could have
several key properties, the association on the database needs to point to all of these.
Therefore, CAP creates a property <AssociationProperty>_<AssociatedEntityKey> for
each key.
As always, cds watch has noticed that there are files containing the mock data.
Other fields like HasDraftEntity were added because you added
the @odata.draft.enabled annotation in the service definition (risk-service.cds).
You’ve now got a full-blown OData service, which complies to the OData standard and
supports the respective queries without having to code anything but the data model
and exposing the service itself.

Note:
The service is completely exposed without any authentication or
authorization check. You will extend the service later with such checks.

You have added a data model, data, and a service definition to your project. Next, you will
create a UI for your application.

© Copyright. All rights reserved. 14


Unit 3
Exercise 3
Generate a User Interface Using SAP Fiori
Elements

Business Scenario
An SAP Fiori Elements (FE) app is an application that uses SAPUI5, its controls, and its Model
View Controller (MVC) concepts. Most code of an SAP FE app is outside the project, managed
centrally by the SAP FE team. The code inside a project only references these central
components, which take care of creating the UI according to the latest SAP Fiori design
guidelines and covers all the controller logic for you out of the box. The UI can be influenced
by OData annotations. They determine, for example, which properties of an OData service
make up the columns of a table that displays the content of the service.

Task Flow
In this exercise, you will perform the following tasks:
● Build a user interface with SAP Fiori elements 1.
● Explain the advantages of using SAP Fiori elements.
● Modify the user interface with OData annotations.

Prerequisite
You have successfully implemented an SAP CAP-based service.

Task 1: Generate the UI With an SAP Fiori Elements Template

1. Generate the UI with an SAP Fiori Elements Template.

Task 2: Modify the UI With OData Annotations


Now we are going to modify the UI with annotations.
Since, our entire UI content goes into the app/ folder, we create our annotation files inside
this folder.

Project Folder/file Content


app/ UI content
db/ Domain Models and db-related content
srv/ Service definitions and implementations
package.json Your project descriptor

The SAP Fiori Generator automatically generates the services.cds file inside the app
folder. This file ensures all annotation files are loaded: using from'./risks/
annotations';

© Copyright. All rights reserved. 15


Unit 3: User Interface and Business Logic

In case you are splitting up your annotations into multiple files, make sure that you also
include the files in the services.cds.
Usually, you can also have multiple SAP Fiori / front end projects in your CAP project. To
avoid writing redundant annotations for the same entities or schemas, you can create - based
on the guidelines - the file common.cds inside the app/ folder. All annotations inside this file
will then apply to all UI5-Applications.

1. Modify the UI with OData annotations.

You’ve now already finished a full-blown service with a full-blown UI application on top,
running locally.

Task 3: Check the Annotation Files


Let's have a look at the common.cds file and the annotations in there. At the beginning, we
see:
using riskmanagement as rm from '../db/schema';

// Annotate Risk elements


annotate rm.Risks with {
ID @title : 'Risk';
title @title : 'Title';
owner @title : 'Owner';
prio @title : 'Priority';
descr @title : 'Description';
miti @title : 'Mitigation';
impact @title : 'Impact';
}

It's referring to the definitions of the schema.cds file that defines the Risks and
Mitigations entities. Then it annotates the Risk entity with numerous texts. These should
be in a translatable file normally, but for now, we will keep them here. These texts are used as
labels in form fields and column headers by SAP Fiori elements.
Next, take a look at the app/risks/annotations.cds file:
using RiskService from '../../srv/risk-service';

// Risk List Report Page


annotate RiskService.Risks with @(UI : {
HeaderInfo : {
TypeName : 'Risk',
TypeNamePlural : 'Risks',
Title : {
$Type : 'UI.DataField',
Value : title
},
Description : {
$Type : 'UI.DataField',
Value : descr
}
},
SelectionFields : [prio],
Identification : [{Value : title}],
// Define the table columns
LineItem : [
{Value : title},
{Value : miti_ID},
{Value : owner},
{
Value : prio,
Criticality : criticality
},

© Copyright. All rights reserved. 16


Exercise 3: Generate a User Interface Using SAP Fiori Elements

{
Value : impact,
Criticality : criticality
},
],
});

Note:
You will find the code block without page break a few pages later.

This file defines the content of the work list page and the object page, to which you are
navigated, when you select a line in the work list.
The SelectionFields section defines which of the properties are exposed as search fields
in the header bar above the list, in this case prio is the only explicit search field.
From the LineItem section all the columns and their order of the work list are derived. While
in most cases the columns are defined by Value: followed by the property name of the
entity, in the case of prio and impact there’s also Criticality, which for now you can
disregard, but keep it in mind in case you go to the later modules. It currently adds a diamond
icon right left of the fields. You can just ignore it.
The next section defines the content of the object page:
// Risk Object Page
annotate RiskService.Risks with @(UI : {
Facets : [{
$Type : 'UI.ReferenceFacet',
Label : 'Main',
Target : '@UI.FieldGroup#Main',
}],
FieldGroup #Main : {Data : [
{Value : miti_ID},
{Value : owner},
{
Value : prio,
Criticality : criticality
},
{
Value : impact,
Criticality : criticality
}
]},
});

This section defines a single facet, a ReferenceFacet, of the field group FieldGroup#Main.
This field group just shows up as a form. The properties of the Data array within
FieldGroup#Main determine the fields in the form:

© Copyright. All rights reserved. 17


Unit 3: User Interface and Business Logic

The last part of the common.cds file is the most complicated one:
annotate rm.Risks with {
miti @(Common : {
//show text, not id for mitigation in the context of risks
Text : miti.descr,
TextArrangement : #TextOnly,
ValueList : {
Label : 'Mitigations',
CollectionPath : 'Mitigations',
Parameters : [
{
$Type : 'Common.ValueListParameterInOut',
LocalDataProperty : miti_ID,
ValueListProperty : 'ID'
},
{
$Type : 'Common.ValueListParameterDisplayOnly',
ValueListProperty : 'descr'
}
]
}
});
}

Without these lines, you would see the id of the mitigations from the miti field, in both the list
and the object page:

© Copyright. All rights reserved. 18


Exercise 3: Generate a User Interface Using SAP Fiori Elements

By introducing the annotations for the miti property, instead of just displaying the original
value of miti, that is, the ID, the UI shows its description property. The subsequent part
ValueList introduces a value help for miti that you can see on the object page in its edit
mode. The value help takes the id as an input parameter and again displays the description
parameter.

1. Check the files.

You have created a SAP Fiori elements UI for your application. Next, you will add custom
business logic to your application to add highlighting to some fields.

© Copyright. All rights reserved. 19


Unit 3
Solution 3
Generate a User Interface Using SAP Fiori
Elements

Business Scenario
An SAP Fiori Elements (FE) app is an application that uses SAPUI5, its controls, and its Model
View Controller (MVC) concepts. Most code of an SAP FE app is outside the project, managed
centrally by the SAP FE team. The code inside a project only references these central
components, which take care of creating the UI according to the latest SAP Fiori design
guidelines and covers all the controller logic for you out of the box. The UI can be influenced
by OData annotations. They determine, for example, which properties of an OData service
make up the columns of a table that displays the content of the service.

Task Flow
In this exercise, you will perform the following tasks:
● Build a user interface with SAP Fiori elements 1.
● Explain the advantages of using SAP Fiori elements.
● Modify the user interface with OData annotations.

Prerequisite
You have successfully implemented an SAP CAP-based service.

Task 1: Generate the UI With an SAP Fiori Elements Template

1. Generate the UI with an SAP Fiori Elements Template.


a) In SAP Business Application Studio, invoke the Command Palette (View → Find
Command or Cmd+Shift+P) and choose Fiori: Open Application Generator.

b) Choose SAP Fiori Elements and List Report Object Page and select Next.

© Copyright. All rights reserved. 20


Solution 3: Generate a User Interface Using SAP Fiori Elements

c) In the next dialog, choose Use a Local CAP Project and point to the folder of your
current RiskManagement project. Select RiskService (Node.js) as the OData
service and select Next.

d) As the Main entity choose Risks as answer to the question choose No.

© Copyright. All rights reserved. 21


Unit 3: User Interface and Business Logic

e) Enter risks as the module name. Enter Risks as the application title and Risk
Management as the description for the application. Enter riskmanagement as the
namespace. Choose No for all additional settings. Choose Finish.

(If you get a pop-up that says A project has been generated. What would
you like to do with it?, you can ignore it and just close the pop-up).
The application is now generated and after a couple of seconds you can see it in the
app folder of your project. It contains a risks and a webapp folder with a
Component.js file, which is characteristic for a UI5 app. However, the code there is
minimal and it basically inherits its logic from the sap/fe/core/AppComponent.

f) If cds watch isn't still running from the previous lesson, execute it in a terminal and
press on the Open in New Tab button in the right lower corner. If it is still running from
the last exercise, it is enough to refresh the browser page where it is running.
You can now see that cds watch has discovered an HTML page in your app folder:

© Copyright. All rights reserved. 22


Solution 3: Generate a User Interface Using SAP Fiori Elements

g) Click on this link. On the launch page that now comes up, Choose the Risks tile.
You can now see the list page, it looks like this:

Unfortunately, the app looks rather empty, for example, the list has no columns yet.
This is because we miss an essential part of a SAP Fiori elements application that tells
it about columns, form fields and many other things: It is missing UI annotations.

Task 2: Modify the UI With OData Annotations


Now we are going to modify the UI with annotations.
Since, our entire UI content goes into the app/ folder, we create our annotation files inside
this folder.

Project Folder/file Content


app/ UI content
db/ Domain Models and db-related content
srv/ Service definitions and implementations
package.json Your project descriptor

The SAP Fiori Generator automatically generates the services.cds file inside the app
folder. This file ensures all annotation files are loaded: using from'./risks/
annotations';
In case you are splitting up your annotations into multiple files, make sure that you also
include the files in the services.cds.
Usually, you can also have multiple SAP Fiori / front end projects in your CAP project. To
avoid writing redundant annotations for the same entities or schemas, you can create - based
on the guidelines - the file common.cds inside the app/ folder. All annotations inside this file
will then apply to all UI5-Applications.

© Copyright. All rights reserved. 23


Unit 3: User Interface and Business Logic

1. Modify the UI with OData annotations.


a) To add the OData annotations, in the project, go to folder app representing the service
and select New File in the context menu.

b) Enter common.cds as a name.

c) Click on the new file in the explorer.


An editor opens.

d) Enter the following lines into the editor:


using riskmanagement as rm from '../db/schema';

// Annotate Risk elements


annotate rm.Risks with {
ID @title : 'Risk';
title @title : 'Title';
owner @title : 'Owner';
prio @title : 'Priority';
descr @title : 'Description';
miti @title : 'Mitigation';
impact @title : 'Impact';
}

// Annotate Miti elements


annotate rm.Mitigations with {
ID @(
UI.Hidden,
Common : {Text : descr}
);
owner @title : 'Owner';
descr @title : 'Description';
}

annotate rm.Risks with {


miti @(Common : {
//show text, not id for mitigation in the context of risks
Text : miti.descr,
TextArrangement : #TextOnly,
ValueList : {
Label : 'Mitigations',
CollectionPath : 'Mitigations',
Parameters : [
{
$Type : 'Common.ValueListParameterInOut',
LocalDataProperty : miti_ID,
ValueListProperty : 'ID'
},
{
$Type : 'Common.ValueListParameterDisplayOnly',
ValueListProperty : 'descr'
}
]
}
});
}

e) Now we have to include the common.cds file into the services.cds file:
using from './risks/annotations';
using from './common';

© Copyright. All rights reserved. 24


Solution 3: Generate a User Interface Using SAP Fiori Elements

f) Open app/risks/annotations.cds. Here we are going to use UI Annotations to tell


SAP Fiori Elements how the List and Object page should look. These annotations will
only apply to the risks app.
using RiskService from '../../srv/risk-service';
// Risk List Report Page
annotate RiskService.Risks with @(UI : {
HeaderInfo : {
TypeName : 'Risk',
TypeNamePlural : 'Risks',
Title : {
$Type : 'UI.DataField',
Value : title
},
Description : {
$Type : 'UI.DataField',
Value : descr
}
},
SelectionFields : [prio],
Identification : [{Value : title}],
// Define the table columns
LineItem : [
{Value : title},
{Value : miti_ID},
{Value : owner},
{
Value : prio,
Criticality : criticality
},
{
Value : impact,
Criticality : criticality
},
],
});
// Risk Object Page
annotate RiskService.Risks with @(UI : {
Facets : [{
$Type : 'UI.ReferenceFacet',
Label : 'Main',
Target : '@UI.FieldGroup#Main',
}],
FieldGroup #Main : {Data : [
{Value : miti_ID},
{Value : owner},
{
Value : prio,
Criticality : criticality
},
{
Value : impact,
Criticality : criticality
}
]},
});

g) Save all files.


As in the steps before, cds watch has noticed the new file and compiled the service
again, so now it contains the additional annotations.

© Copyright. All rights reserved. 25


Unit 3: User Interface and Business Logic

h) In the browser, reload the test page, which shows the service and the index page.
Select the index page link /risks/webapp/index.html. On the launch page that
now comes up, choose the Risks tile. Select Go. It now shows a work list with some
columns and the data from the service.

You’ve now already finished a full-blown service with a full-blown UI application on top,
running locally.

Task 3: Check the Annotation Files


Let's have a look at the common.cds file and the annotations in there. At the beginning, we
see:
using riskmanagement as rm from '../db/schema';

// Annotate Risk elements


annotate rm.Risks with {
ID @title : 'Risk';
title @title : 'Title';
owner @title : 'Owner';
prio @title : 'Priority';
descr @title : 'Description';
miti @title : 'Mitigation';
impact @title : 'Impact';
}

It's referring to the definitions of the schema.cds file that defines the Risks and
Mitigations entities. Then it annotates the Risk entity with numerous texts. These should
be in a translatable file normally, but for now, we will keep them here. These texts are used as
labels in form fields and column headers by SAP Fiori elements.
Next, take a look at the app/risks/annotations.cds file:
using RiskService from '../../srv/risk-service';

// Risk List Report Page


annotate RiskService.Risks with @(UI : {
HeaderInfo : {
TypeName : 'Risk',
TypeNamePlural : 'Risks',
Title : {
$Type : 'UI.DataField',
Value : title
},
Description : {
$Type : 'UI.DataField',
Value : descr
}
},
SelectionFields : [prio],
Identification : [{Value : title}],
// Define the table columns
LineItem : [
{Value : title},
{Value : miti_ID},
{Value : owner},

© Copyright. All rights reserved. 26


Solution 3: Generate a User Interface Using SAP Fiori Elements

{
Value : prio,
Criticality : criticality
},
{
Value : impact,
Criticality : criticality
},
],
});

Note:
You will find the code block without page break a few pages later.

This file defines the content of the work list page and the object page, to which you are
navigated, when you select a line in the work list.
The SelectionFields section defines which of the properties are exposed as search fields
in the header bar above the list, in this case prio is the only explicit search field.
From the LineItem section all the columns and their order of the work list are derived. While
in most cases the columns are defined by Value: followed by the property name of the
entity, in the case of prio and impact there’s also Criticality, which for now you can
disregard, but keep it in mind in case you go to the later modules. It currently adds a diamond
icon right left of the fields. You can just ignore it.
The next section defines the content of the object page:
// Risk Object Page
annotate RiskService.Risks with @(UI : {
Facets : [{
$Type : 'UI.ReferenceFacet',
Label : 'Main',
Target : '@UI.FieldGroup#Main',
}],
FieldGroup #Main : {Data : [
{Value : miti_ID},
{Value : owner},
{
Value : prio,
Criticality : criticality
},
{
Value : impact,
Criticality : criticality
}
]},
});

This section defines a single facet, a ReferenceFacet, of the field group FieldGroup#Main.
This field group just shows up as a form. The properties of the Data array within
FieldGroup#Main determine the fields in the form:

© Copyright. All rights reserved. 27


Unit 3: User Interface and Business Logic

The last part of the common.cds file is the most complicated one:
annotate rm.Risks with {
miti @(Common : {
//show text, not id for mitigation in the context of risks
Text : miti.descr,
TextArrangement : #TextOnly,
ValueList : {
Label : 'Mitigations',
CollectionPath : 'Mitigations',
Parameters : [
{
$Type : 'Common.ValueListParameterInOut',
LocalDataProperty : miti_ID,
ValueListProperty : 'ID'
},
{
$Type : 'Common.ValueListParameterDisplayOnly',
ValueListProperty : 'descr'
}
]
}
});
}

Without these lines, you would see the id of the mitigations from the miti field, in both the list
and the object page:

© Copyright. All rights reserved. 28


Solution 3: Generate a User Interface Using SAP Fiori Elements

By introducing the annotations for the miti property, instead of just displaying the original
value of miti, that is, the ID, the UI shows its description property. The subsequent part
ValueList introduces a value help for miti that you can see on the object page in its edit
mode. The value help takes the id as an input parameter and again displays the description
parameter.

© Copyright. All rights reserved. 29


Unit 3: User Interface and Business Logic

1. Check the files.


a) Check the files as described above.

You have created a SAP Fiori elements UI for your application. Next, you will add custom
business logic to your application to add highlighting to some fields.

© Copyright. All rights reserved. 30


Unit 3
Exercise 4
Add Custom Business Logic to Your
Application

Business Scenario
In this exercise, you will add custom code to the CAP service to implement conditional
formatting of certain cells of your work list. Depending on the value of the properties impact
and criticality respectively, cells in the table of our work list page will change color.

Task Flow
In this exercise, you will perform the following task:
● Create a JavaScript file to implement dynamic color coding.

Prerequisites
● Generation of a UI channel.
● Familiarity with JavaScript coding.

Task 1: Add Custom Code

1. Add Custom Code

Task 2: Explanation of the Custom Code


Because your file is called risk-service.js and shares the same name as your service
definition file risk-service.cds, CAP automatically treats it as a handler file for the service
defined in there. CAP exposes several events 1 and you can easily write handlers like the one
above. If you want to use a different name for the JavaScript file, you have to use @(impl:...)
notation 2.
The event after is triggered after a READ is carried out for our Risks entity. In your custom
handler, you get all the data, in this case all the risks that were read according to the query.
You can loop over each of them and, if needed, adjust the data of the response. In this case,
the code changes criticality value when the impact is larger than 100000. The new
values for criticality are then part of the response to the read request.
How is this change reflected in the UI? To achieve this, you have to go back to the annotations
you created in the exercise: Generate a User Interface Using SAP Fiori Elements, where you
find your app/risks/annotations.cds file. There you had the two columns prio and
impact annotated with an additional Criticality annotation.
This annotation points to the criticality property of your service.

Note:
Criticality with an upper case C is the annotation, while the property name
criticality could also be called different opposed to the annotation.

© Copyright. All rights reserved. 31


Unit 3: User Interface and Business Logic

As you now set different values in your custom handler for criticality, the SAP Fiori
elements application translates these into icons and colors, which you can see in the UI.
annotate RiskService.Risks with @(UI : {
...
...
LineItem : [
...
...
{
Value : prio,
Criticality : criticality
},
{
Value : impact,
Criticality : criticality
},
],
});

You can find out more about the possible values of the Criticality annotation here 3. This,
however, is just one of the many sections of the OData Annotation vocabularies for UI 4 and
Common 5 usage.

Note:
Keep your application running in your web browser, you will need it later.

© Copyright. All rights reserved. 32


Unit 3
Solution 4
Add Custom Business Logic to Your
Application

Business Scenario
In this exercise, you will add custom code to the CAP service to implement conditional
formatting of certain cells of your work list. Depending on the value of the properties impact
and criticality respectively, cells in the table of our work list page will change color.

Task Flow
In this exercise, you will perform the following task:
● Create a JavaScript file to implement dynamic color coding.

Prerequisites
● Generation of a UI channel.
● Familiarity with JavaScript coding.

Task 1: Add Custom Code

1. Add Custom Code


a) In the project, go to folder srv, representing the service, and select New File in the
context menu.

b) Enter risk-service.js as a name.

c) Select the new file in the explorer, an editor opens.

d) Enter the following lines into the editor:

© Copyright. All rights reserved. 33


Unit 3: User Interface and Business Logic

Note:
The defined constant for the BusinessPartners will be used in a later step.

// Imports
const cds = require("@sap/cds");

/**
* The service implementation with all service handlers
*/
module.exports = cds.service.impl(async function () {
// Define constants for the Risk and BusinessPartners entities
from the risk-service.cds file
const { Risks, BusinessPartners } = this.entities;

/**
* Set criticality after a READ operation on /risks
*/
this.after("READ", Risks, (data) => {
const risks = Array.isArray(data) ? data : [data];

risks.forEach((risk) => {
if (risk.impact >= 100000) {
risk.criticality = 1;
} else {
risk.criticality = 2;
}
});
});
});

e) Save the file.

f) In the browser, reload the page of the SAP Fiori Elements app.
It now shows our work list with the columns Priority and Impact with color and an
icon, depending on the amount in impact.

Task 2: Explanation of the Custom Code


Because your file is called risk-service.js and shares the same name as your service
definition file risk-service.cds, CAP automatically treats it as a handler file for the service
defined in there. CAP exposes several events 1 and you can easily write handlers like the one
above. If you want to use a different name for the JavaScript file, you have to use @(impl:...)
notation 2.
The event after is triggered after a READ is carried out for our Risks entity. In your custom
handler, you get all the data, in this case all the risks that were read according to the query.
You can loop over each of them and, if needed, adjust the data of the response. In this case,
the code changes criticality value when the impact is larger than 100000. The new
values for criticality are then part of the response to the read request.

© Copyright. All rights reserved. 34


Solution 4: Add Custom Business Logic to Your Application

How is this change reflected in the UI? To achieve this, you have to go back to the annotations
you created in the exercise: Generate a User Interface Using SAP Fiori Elements, where you
find your app/risks/annotations.cds file. There you had the two columns prio and
impact annotated with an additional Criticality annotation.
This annotation points to the criticality property of your service.

Note:
Criticality with an upper case C is the annotation, while the property name
criticality could also be called different opposed to the annotation.

As you now set different values in your custom handler for criticality, the SAP Fiori
elements application translates these into icons and colors, which you can see in the UI.
annotate RiskService.Risks with @(UI : {
...
...
LineItem : [
...
...
{
Value : prio,
Criticality : criticality
},
{
Value : impact,
Criticality : criticality
},
],
});

You can find out more about the possible values of the Criticality annotation here 3. This,
however, is just one of the many sections of the OData Annotation vocabularies for UI 4 and
Common 5 usage.

Note:
Keep your application running in your web browser, you will need it later.

© Copyright. All rights reserved. 35


Unit 4
Exercise 5
Add an External Service

Business Scenario
In this exercise, you will extend your CAP service with the consumption of an external
Business Partner service.

Task Flow
In this exercise, you will perform the following tasks:
● Search for a service on the SAP API Business Hub.
● Import an Entity Data Model XML (EDMX) EDMX 1 file to your project.
● Consume an External Service in an UI application.

Prerequisite
You have added custom business logic to your extension.

Task 1: Use the External API in the Project

1. Use the external API in the Project.

Task 2: Connect Your App With the Business Partner API Sandbox Environment of the
SAP API Business Hub
At this point, you have a new service exposed with a definition based on the original edmx file.
However, it doesn't have any connectivity to a back end, so, there’s no data yet. In this case,
you do not create local data as with your risks and mitigations entities, but you connect
your service to the Sandbox environment of the SAP API Business Hub for the Business
Partner API that you want to use. To use the API Business Hub Sandbox APIs, you require an
API key.

1. Connect your app with the Business Partner API Sandbox Environment of the SAP API
Business Hub.

Task 3: Consume the External Service in Your UI Application


In this task, you incorporate the external service into the UI application.

1. Consume the External Service in Your UI Application.

Task 4: Add the Business Partner Field to the UI


You need to introduce the business partner field in the UI:
● Add a label for the columns in the result list table as well as in the object page by adding a
title annotation.
● Add the business partner as a line item to include it as a column in the result list.
● Add the business partner as a field to a field group, which makes it appear in a form on the
object page.

© Copyright. All rights reserved. 36


Exercise 5: Add an External Service

All this happens in the cds file that has all the UI annotations. Enter the code between //###
BEGIN OF INSERT and //### END OF OF INSERT.

1. Add the Business Partner Field to the UI.

You have added an external business partner service to your application. The last step is to
deploy your application manually.

© Copyright. All rights reserved. 37


Unit 4
Solution 5
Add an External Service

Business Scenario
In this exercise, you will extend your CAP service with the consumption of an external
Business Partner service.

Task Flow
In this exercise, you will perform the following tasks:
● Search for a service on the SAP API Business Hub.
● Import an Entity Data Model XML (EDMX) EDMX 1 file to your project.
● Consume an External Service in an UI application.

Prerequisite
You have added custom business logic to your extension.

Task 1: Use the External API in the Project

1. Use the external API in the Project.


a) Navigate into the srv/external folder.
The CAP importer created the API_BUSINESS_PARTNER.csn file out of the EDMX file.
(capire3is a compact representation of CDS). This basically contains all the schema
definitions of the external service.

b) In your project, open the db/schema.cds file and enter the code listed below
between //### BEGIN OF INSERT and //### END OF OF INSERT.

namespace riskmanagement;

using {managed} from '@sap/cds/common';

entity Risks : managed {


key ID : UUID @(Core.Computed : true);
title : String(100);
owner : String;
prio : String(5);
descr : String;
miti : Association to Mitigations;
impact : Integer;
//bp : Association to BusinessPartners;
criticality : Integer;
}

entity Mitigations : managed {


key ID : UUID @(Core.Computed : true);
descr : String;

© Copyright. All rights reserved. 38


Solution 5: Add an External Service

owner : String;
timeline : String;
risks : Association to many Risks
on risks.miti = $self;
}

//### BEGIN OF INSERT

// using an external service from S/4


using { API_BUSINESS_PARTNER as external } from '../srv/external/
API_BUSINESS_PARTNER.csn';

entity BusinessPartners as projection on external.A_BusinessPartner {


key BusinessPartner,
LastName,
FirstName
}

//### END OF OF INSERT

With this code you create a so-called projection for your new service. Of the many
entities and properties in these entities, that are defined in the
API_BUSINESS_PARTNER service, you just look at one of the entities
(A_BusinessPartner) and just three of its properties: BusinessPartner,
LastName, and FirstName, so your projection is using a subset of everything the
original service has to offer.

c) Open the srv/risk-service.cds file.

d) Uncomment the entity BusinessPartners line.

using {riskmanagement as rm} from '../db/schema';

/**
* For serving end users
*/
service RiskService @(path : 'service/risk') {
entity Risks as projection on rm.Risks;
annotate Risks with @odata.draft.enabled;
entity Mitigations as projection on rm.Mitigations;
annotate Mitigations with @odata.draft.enabled;
entity BusinessPartners as projection on rm.BusinessPartners;
}

e) Your SAP Fiori elements app should still be running in your web browser. Select the
SAP icon on the left upper corner to navigate back to the index page. Hit Refresh in
your browser. Now press on the Risks tile and in the application press Go.
The browser now shows a BusinessPartner service next to the Mitigations and
Risks

© Copyright. All rights reserved. 39


Unit 4: External Services

Task 2: Connect Your App With the Business Partner API Sandbox Environment of the
SAP API Business Hub
At this point, you have a new service exposed with a definition based on the original edmx file.
However, it doesn't have any connectivity to a back end, so, there’s no data yet. In this case,
you do not create local data as with your risks and mitigations entities, but you connect
your service to the Sandbox environment of the SAP API Business Hub for the Business
Partner API that you want to use. To use the API Business Hub Sandbox APIs, you require an
API key.

1. Connect your app with the Business Partner API Sandbox Environment of the SAP API
Business Hub.
a) Go back to the SAP API Business Hub page in your browser.

b) Make sure you are logged in. If not, press the Log On button on the upper right.

c) Navigate to the Business Partner API (SAP S/4HANA Cloud → Business Partner
(A2X)).

d) In the right upper corner, choose Show API Key to see your API key.

e) Copy the API key.

© Copyright. All rights reserved. 40


Solution 5: Add an External Service

f) In your project in Business Application Studio, create the file .env in the root of the
project (next to files package.json, README.md, and so on). Copy the following line
into the file and replace <YOUR-API-KEY> with the API key that you copied in the
previous step.
apikey=<YOUR-API-KEY>
The result should look like the following:

The .env file is an environment file providing values into the runtime environment of
your CAP service. You are going to use the API key to call the Business Partner API in
the API Business Hub Sandbox environment.

g) By mentioning the .env file in the .gitignore file you make sure, that when you are
using git as a version-management-system for your project, no credentials get
accidentally leaked into your potentially public git repository.
The .env file is already listed in the .gitignore file. You can verify this, by opening
the .gitignore file in the SAP Business Application Studio.
You can also use the terminal to see the.gitignorefile. For this, just execute the
following command in a new terminal: cat .gitignore

h) Open the package.json file and add the following lines between //### BEGIN OF
INSERT and //### END OF OF INSERT:

"cds": {
"requires": {
"API_BUSINESS_PARTNER": {
"kind": "odata",
"model": "srv/external/API_BUSINESS_PARTNER",
//### BEGIN OF INSERT
"credentials": {

© Copyright. All rights reserved. 41


Unit 4: External Services

"url": "https://sandbox.api.sap.com/s4hanacloud/sap/opu/
odata/sap/API_BUSINESS_PARTNER/"
}
//### End OF INSERT
}
}
}

Note:
Do not copy the comments starting with //###.

Now that you have set all the configurations for the external call, you will implement a
custom service handler for the external BusinessPartner service in the next step.

i) Open the risk-service.js file and insert the following lines between //### BEGIN
OF INSERT and //### END OF OF INSERT:

// Imports
const cds = require("@sap/cds");

/**
* The service implementation with all service handlers
*/
module.exports = cds.service.impl(async function () {
// Define constants for the Risk and BusinessPartners entities from
the risk-service.cds file
const { Risks, BusinessPartners } = this.entities;

/**
* Set criticality after a READ operation on /risks
*/
this.after("READ", Risks, (data) => {
const risks = Array.isArray(data) ? data : [data];

risks.forEach((risk) => {
if (risk.impact >= 100000) {
risk.criticality = 1;
} else {
risk.criticality = 2;
}
});
});

//### BEGIN OF INSERT

// connect to remote service


const BPsrv = await cds.connect.to("API_BUSINESS_PARTNER");

/**
* Event-handler for read-events on the BusinessPartners entity.
* Each request to the API Business Hub requires the apikey in the
header.
*/
this.on("READ", BusinessPartners, async (req) => {
// The API Sandbox returns alot of business partners with empty
names.
// We don't want them in our application
req.query.where("LastName <> '' and FirstName <> '' ");

© Copyright. All rights reserved. 42


Solution 5: Add an External Service

return await BPsrv.transaction(req).send({


query: req.query,
headers: {
apikey: process.env.apikey,
},
});
});
//### END OF INSERT
});

You've now created a custom handler for your service. This time it called on for the
READ event.
The handler is invoked when your BusinessPartner service is called for a read, so
whenever there’s a request for business partner data, this handler is called. It ensures
the request for the business partner is directed to the external business partner
service. Furthermore, you have added a where clause to the request, which selects
only business partners where the first and last name is set.

j) Save the file.

k) In your browser, open the BusinessPartners link to see the data.

Task 3: Consume the External Service in Your UI Application


In this task, you incorporate the external service into the UI application.

1. Consume the External Service in Your UI Application.


a) Open the db/data/schema.cds file.

b) Uncomment the bp property.

namespace riskmanagement;

using {managed} from '@sap/cds/common';

entity Risks : managed {


key ID : UUID @(Core.Computed : true);
title : String(100);
owner : String;
prio : String(5);
descr : String;
miti : Association to Mitigations;
impact : Integer;
bp : Association to BusinessPartners; // <-- uncomment this
criticality : Integer;

© Copyright. All rights reserved. 43


Unit 4: External Services

entity Mitigations : managed {


key ID : UUID @(Core.Computed : true);
descr : String;
owner : String;
timeline : String;
risks : Association to many Risks
on risks.miti = $self;
}

// using an external service from S/4


using {API_BUSINESS_PARTNER as external} from '../srv/external/
API_BUSINESS_PARTNER.csn';

entity BusinessPartners as projection on external.A_BusinessPartner {


key BusinessPartner, FirstName, LastName,
}

As you got a new property in your entity, you need to add data for this property in the
local data file that you've created before for the risk entity.

c) Open the file riskmanagement-Risks.csv in your db/data folder.

d) Replace the content with the new content below which additionally includes the BP
data.
ID;createdAt;createdBy;title;owner;prio;descr;miti_id;impact;bp_Busines
sPartner
20466922-7d57-4e76-b14c-e53fd97dcb11;2019-10-24;SYSTEM;CFR non-
compliance;Fred Fish;3;Recent restructuring might violate CFR code
71;20466921-7d57-4e76-b14c-e53fd97dcb11;10000;9980000448
20466922-7d57-4e76-b14c-e53fd97dcb12;2019-10-24;SYSTEM;SLA violation
with possible termination cause;George Gung;2;Repeated SAL violation
on service delivery for two successive quarters;20466921-7d57-4e76-
b14c-e53fd97dcb12;90000;9980002245
20466922-7d57-4e76-b14c-e53fd97dcb13;2019-10-24;SYSTEM;Shipment
violating export control;Herbert Hunter;1;Violation of export and
trade control with unauthorized downloads;20466921-7d57-4e76-b14c-
e53fd97dcb13;200000;9980000230

e) Save the file.


If you check the content of the file, you see numbers like 9980000230 at the end of the
lines, representing business partners.

Task 4: Add the Business Partner Field to the UI


You need to introduce the business partner field in the UI:
● Add a label for the columns in the result list table as well as in the object page by adding a
title annotation.
● Add the business partner as a line item to include it as a column in the result list.
● Add the business partner as a field to a field group, which makes it appear in a form on the
object page.

All this happens in the cds file that has all the UI annotations. Enter the code between //###
BEGIN OF INSERT and //### END OF OF INSERT.

1. Add the Business Partner Field to the UI.


a) Open the app/common.cds file.

© Copyright. All rights reserved. 44


Solution 5: Add an External Service

b) Insert the following parts:


using riskmanagement as rm from '../db/schema';

// Annotate Risk elements


annotate rm.Risks with {
ID @title : 'Risk';
title @title : 'Title';
owner @title : 'Owner';
prio @title : 'Priority';
descr @title : 'Description';
miti @title : 'Mitigation';
impact @title : 'Impact';
//### BEGIN OF INSERT
bp @title : 'Business Partner';
//### END OF INSERT
criticality @title : 'Criticality';
}

// Annotate Miti elements


annotate rm.Mitigations with {
ID @(
UI.Hidden,
Common : {Text : descr}
);
owner @title : 'Owner';
descr @title : 'Description';
}

//### BEGIN OF INSERT


annotate rm.BusinessPartners with {
BusinessPartner @(
UI.Hidden,
Common : {Text : LastName}
);
LastName @title : 'Last Name';
FirstName @title : 'First Name';
}
//### END OF INSERT

annotate rm.Risks with {


miti @(Common : {
//show text, not id for mitigation in the context of risks
Text : miti.descr,
TextArrangement : #TextOnly,
ValueList : {
Label : 'Mitigations',
CollectionPath : 'Mitigations',
Parameters : [
{
$Type : 'Common.ValueListParameterInOut',
LocalDataProperty : miti_ID,
ValueListProperty : 'ID'
},
{
$Type : 'Common.ValueListParameterDisplayOnly',
ValueListProperty : 'descr'
}
]
}
});
//### BEGIN OF INSERT
bp @(Common : {

© Copyright. All rights reserved. 45


Unit 4: External Services

Text : bp.LastName,
TextArrangement : #TextOnly,
ValueList : {
Label : 'Business Partners',
CollectionPath : 'BusinessPartners',
Parameters : [
{
$Type : 'Common.ValueListParameterInOut',
LocalDataProperty : bp_BusinessPartner,
ValueListProperty : 'BusinessPartner'
},
{
$Type : 'Common.ValueListParameterDisplayOnly',
ValueListProperty : 'LastName'
},
{
$Type : 'Common.ValueListParameterDisplayOnly',
ValueListProperty : 'FirstName'
}
]
}
})
//### END OF INSERT }

c) Open the app/risk/annotations.cds file and insert the following lines


between //### BEGIN OF INSERT and //### END OF OF INSERT:
using RiskService from '../../srv/risk-service';

// Risk List Report Page


annotate RiskService.Risks with @(UI : {
HeaderInfo : {
TypeName : 'Risk',
TypeNamePlural : 'Risks',
Title : {
$Type : 'UI.DataField',
Value : title
},
Description : {
$Type : 'UI.DataField',
Value : descr
}
},
SelectionFields : [prio],
Identification : [{Value : title}],
// Define the table columns
LineItem : [
{Value : title},
{Value : miti_ID},
{Value : owner},
//### BEGIN OF INSERT
{Value : bp_BusinessPartner},
//### END OF INSERT
{
Value : prio,
Criticality : criticality
},
{
Value : impact,
Criticality : criticality
},
],
});

© Copyright. All rights reserved. 46


Solution 5: Add an External Service

// Risk Object Page


annotate RiskService.Risks with @(UI : {
Facets : [{
$Type : 'UI.ReferenceFacet',
Label : 'Main',
Target : '@UI.FieldGroup#Main',
}],
FieldGroup #Main : {Data : [
{Value : miti_ID},,
{Value : owner},
//### BEGIN OF INSERT
{Value : bp_BusinessPartner},
//### END OF INSERT
{
Value : prio,
Criticality : criticality
},
{
Value : impact,
Criticality : criticality
}
]},
});

What does the code do? The first part enables the title and adds the business partner
first as a column to the list and then as a field to the object page, just like other
columns and fields were added before.
The larger part of new annotations activates the same qualities for the bp field as it
happened before in the lesson: Create a CAP-Based Service 4 for the miti field:
Instead of showing the ID of the business partner, its LastName property is displayed.
The ValueList part introduces a value list for the business partner and shows it last
and first name in it.

d) Save the file.

e) Open the srv/risk-service.js file.

f) Add the following lines between //### BEGIN OF INSERT and //### END OF OF
INSERT to the file:

// Imports
const cds = require("@sap/cds");

/**
* The service implementation with all service handlers
*/
module.exports = cds.service.impl(async function () {
// Define constants for the Risk and BusinessPartners entities from
the risk-service.cds file
const { Risks, BusinessPartners } = this.entities;
/**
* Set criticality after a READ operation on /risks
*/
this.after("READ", Risks, (data) => {
const risks = Array.isArray(data) ? data : [data];

risks.forEach((risk) => {
if (risk.impact >= 100000) {

© Copyright. All rights reserved. 47


Unit 4: External Services

risk.criticality = 1;
} else {
risk.criticality = 2;
}
});
});

// connect to remote service


const BPsrv = await cds.connect.to("API_BUSINESS_PARTNER");

/**
* Event-handler for read-events on the BusinessPartners entity.
* Each request to the API Business Hub requires the apikey in the
header.
*/
this.on("READ", BusinessPartners, async (req) => {
// The API Sandbox returns alot of business partners with empty
names.
// We don't want them in our application
req.query.where("LastName <> '' and FirstName <> '' ");

return await BPsrv.transaction(req).send({


query: req.query,
headers: {
apikey: process.env.apikey,
},
});
});

//### BEGIN OF INSERT

/**
* Event-handler on risks.
* Retrieve BusinessPartner data from the external API
*/
this.on("READ", Risks, async (req, next) => {
/*
Check whether the request wants an "expand" of the business partner
As this is not possible, the risk entity and the business partner
entity are in different systems (SAP BTP and S/4 HANA Cloud),
if there is such an expand, remove it
*/
if (!req.query.SELECT.columns) return next();

const expandIndex = req.query.SELECT.columns.findIndex(


({ expand, ref }) => expand && ref[0] === "bp"
);
console.log(req.query.SELECT.columns);
if (expandIndex < 0) return next();

req.query.SELECT.columns.splice(expandIndex, 1);
if (
!req.query.SELECT.columns.find((column) =>
column.ref.find((ref) => ref == "bp_BusinessPartner")
)
) {
req.query.SELECT.columns.push({ ref: ["bp_BusinessPartner"] });
}

/*
Instead of carrying out the expand, issue a separate request for
each business partner

© Copyright. All rights reserved. 48


Solution 5: Add an External Service

This code could be optimized, instead of having n requests for n


business partners, just one bulk request could be created
*/
try {
res = await next();
res = Array.isArray(res) ? res : [res];

await Promise.all(
res.map(async (risk) => {
const bp = await BPsrv.transaction(req).send({
query: SELECT.one(this.entities.BusinessPartners)
.where({ BusinessPartner: risk.bp_BusinessPartner })
.columns(["BusinessPartner", "LastName", "FirstName"]),
headers: {
apikey: process.env.apikey,
},
});
risk.bp = bp;
})
);
} catch (error) {}
});
//### END OF INSERT
});

You have added another custom handler, this one is called on a READ of the Risks
service. It checks whether the request includes a so-called expand for business
partners. This is a request that is issued by the UI when the list should be filled. While it
mostly contains columns that directly belong to the Risks entity, it also contains the
business partner. As we have seen in the annotation file, instead of showing the ID of
the business partner, the last name of the business partner will be shown. This data is
in the business partner and not in the risks entity. Therefore, the UI wants to expand,
that is, for each risk the corresponding business partner is also read.
As the business partner does not reside in the CAP database but in a remote system
instead, a direct expand is not possible. The data needs to be retrieved from the SAP
S/4HANA Cloud system.

g) Save the file.

h) In your tab with the application, go back to the index.html page and press refresh.

i) On the launch page that now comes up, choose the Risks tile and then select Go.
You now see the Risks application with the business partner data in both the result
list and the object page, which is loaded when you select one of the rows in the table:

When you are on the object page, select the Edit button on the top right of the screen.
Now you can use the value help for the Business Partner field and search for other
Business Partners, which are provided via the Business Partner API.

© Copyright. All rights reserved. 49


Unit 4: External Services

You have added an external business partner service to your application. The last step is to
deploy your application manually.

© Copyright. All rights reserved. 50


Unit 5
Exercise 6
Deploy SAP BTP Cloud Foundry Applications
Manually

Business Scenario
You will deploy your CAP application into the Cloud Foundry environment of the SAP Business
Technology Platform manually using:
● The Cloud Foundry Command Line Interface (CLI).
● A Multi-target application (MTA) file. You will also replace the in-memory SQLite database
with an SAP HANA Cloud instance to store the application data.

Task Flow
In this exercise, you will perform the following tasks:
● Prepare a project/extension for SAP HANA Cloud deployment.
● Set Up HDI container.
● Update the project to use SAP HANA.
● Perform further deployment preparations.
● Perform a manual deployment using CF CLI tools.
● Perform a manual deployment using a "Multi Target Application" (MTA) file.
● Generate an MTA Deployment descriptor (mta.yaml).

Prerequisite
You have added an external service.

Task 1: Set Up HDI Container on SAP HANA Cloud Instance


The SAP HANA Cloud instance serves as your cloud database. You can now create schemas
or HDI containers on the database. You can bind a schema or HDI container to an application
to create the data schema and store the application data.

1. Set Up HDI Container on SAP HANA Cloud Instance.

Task 2: Update the Project to use SAP HANA


As you want your CAP service to use the newly created SAP HANA Cloud HDI container, you
need to update the project.

1. Update Project to use SAP HANA.

Task 3: Perform Further Deployment Preparations

1. Perform further deployment preparations.

© Copyright. All rights reserved. 51


Unit 5: Manual Deployment

Task 4: Perform a Manual Deployment Using CF CLI Tools

1. Perform a manual deployment using CF CLI tools.

Task 5: Perform a Manual Deployment Using a "Multi Target Application" (MTA) File
In this section, we will create a "Multi Target Application" (MTA) file for deployment. (See the
description 2). MTA is a way to create deployments consisting of multiple modules that can be
implemented in different technologies. Some advantages of this technology are:
● It provides a build tool.
● It creates service instances, service keys, and destinations automatically.
● It deploys content (HTML5, workflow, …).
● It supports blue-green deployment 3.

Compared to the deployment procedure you performed in the previous steps, this will save
you a lot of manual work in the long run.

Task 6: Generate an MTA Deployment Descriptor (mta.yaml)


The MTA deployment is described in the MTA Deployment Descriptor 4, a file called
mta.yaml. In the first step, let CAP generate an initial mta.yaml file.

1. Generate an MTA deployment descriptor (mta.yaml).

You have:
● Created an application.
● Created a UI with SAP Fiori elements.
● Added custom business logic.
● Added an external service.
● Deployed your application manually.

You still have to deploy the UI part of your application. For this deployment, you will need an
application router (approuter). To manage the access to your application, you need to
implement restrictions and roles. We will cover all this in the next part.

© Copyright. All rights reserved. 52


Unit 5
Solution 6
Deploy SAP BTP Cloud Foundry Applications
Manually

Business Scenario
You will deploy your CAP application into the Cloud Foundry environment of the SAP Business
Technology Platform manually using:
● The Cloud Foundry Command Line Interface (CLI).
● A Multi-target application (MTA) file. You will also replace the in-memory SQLite database
with an SAP HANA Cloud instance to store the application data.

Task Flow
In this exercise, you will perform the following tasks:
● Prepare a project/extension for SAP HANA Cloud deployment.
● Set Up HDI container.
● Update the project to use SAP HANA.
● Perform further deployment preparations.
● Perform a manual deployment using CF CLI tools.
● Perform a manual deployment using a "Multi Target Application" (MTA) file.
● Generate an MTA Deployment descriptor (mta.yaml).

Prerequisite
You have added an external service.

Task 1: Set Up HDI Container on SAP HANA Cloud Instance


The SAP HANA Cloud instance serves as your cloud database. You can now create schemas
or HDI containers on the database. You can bind a schema or HDI container to an application
to create the data schema and store the application data.

1. Set Up HDI Container on SAP HANA Cloud Instance.


a) In your BTP cockpit, select Service Marketplace on the left.

© Copyright. All rights reserved. 53


Unit 5: Manual Deployment

b) The Service Marketplace displays. Type schemas in the Search field and then select
the SAP HANA Schemas & HDI Containers tile.

c) Select the Create button.

© Copyright. All rights reserved. 54


Solution 6: Deploy SAP BTP Cloud Foundry Applications Manually

d) The New Instance or Subscription page appears. Set the Plan to hdi-shared, enter
risk-management-db in the Instance Name field, and then select Create.

e) In the Information dialog that appears, select Instances and Subscriptions.

f) Your risk-management-db instance of the SAP HANA Schemas & HDI Containers
service appears in the list. This service instance is the database container that the CAP
data schema will be deployed to.

© Copyright. All rights reserved. 55


Unit 5: Manual Deployment

Task 2: Update the Project to use SAP HANA


As you want your CAP service to use the newly created SAP HANA Cloud HDI container, you
need to update the project.

1. Update Project to use SAP HANA.


a) Run the command cds add hana.

b) The projects package.json will be updated with the required configurations.


The following parts are added to the cds section of the file:

{
...
...
"cds": {
"requires": {
...
...
"db": {
"kind": "sql"
}
},
"hana": {
"deploy-format": "hdbtable"
}
}
}

This configures deployment for SAP HANA to use the hdbtable and hdbview formats.
They are special file formats that are generated during the build process from
the .cds. definition files and can be deployed to SAP HANA Cloud, in order to create
the data schema.

Task 3: Perform Further Deployment Preparations

1. Perform further deployment preparations.


a) Go to the SAP BTP Cockpit, subaccount level and select Connectivity → Destinations
of the navigational menu on the left side.

© Copyright. All rights reserved. 56


Solution 6: Deploy SAP BTP Cloud Foundry Applications Manually

b) Choose New Destination.

c) Enter the following values into the form:


Key Value
Name API_BUSINESS_PARTNER
Type HTTP
Description Business Partner Sandbox API
URL https://sandbox.api.sap.com/s4hanacloud/sap/opu/
odata/sap/API_BUSINESS_PARTNER/
Proxy Type Internet
Authentication No Authentication

Note:
In the URL, there is no blank between opu/ and odata. The line break in the
URL is automatically created in this handbook.

d) When finished, press Save.

© Copyright. All rights reserved. 57


Unit 5: Manual Deployment

e) The destination needs to be accessed from your CAP service. For that, you need to
create a service instance of the destination service and adjust the configuration of your
package.json file.

f) Select Instances and Subscriptions and then select Create.

g) In the dialog, use the following settings:


Key Value
Service Destination
Plan Lite
Runtime Environment Cloud Foundry
Space your space, for example, dev

Instance Name risk-management-destination-service

h) Select Create. The destination service instance will be created.


The destination service instance will be created.

i) Still being in the Instances and Subscriptions section, select Create again.

j) In the dialog, use the following settings:


Key Value
Service Authorization & Trust Management (xsuaa)
Plan application
Runtime Environment Cloud Foundry
Space your space, for example, dev

Instance Name risk-management-xsuaa

k) Select Next.

© Copyright. All rights reserved. 58


Solution 6: Deploy SAP BTP Cloud Foundry Applications Manually

You are required to provide a configuration.

l) Go to your BAS project and run the following command: cds compile srv/ --to
xsuaa > xs-security.json
This will generate the file xs-security.json in your project root folder.

m) Open the file and change the xsappname-value to risk-management-


<YOURDEVSPACE>:
Make sure to replace <YOURDEVSPACE> with your dev-space name. It should then look
like this for instance:
"xsappname": "risk-management-dev",

n) Copy the JSON.

o) Go back to the SAP BTP Cockpit dialog for the xsuaa instance creation and paste the
copied JSON structure.

p) Select Create.
An instance of the xsuaa service will be created.

q) Your Service Instances overview should now look like the following:

Task 4: Perform a Manual Deployment Using CF CLI Tools

1. Perform a manual deployment using CF CLI tools.


a) In the package.json file, in the requires section, add the following code:

"xsuaa": {
"kind": "xsuaa"
}

The result should look like the following:

{
...
...
"cds": {
"requires": {
"API_BUSINESS_PARTNER": {
"kind": "odata",
"model": "srv/external/API_BUSINESS_PARTNER",
"credentials": {
"url": "https://sandbox.api.sap.com/
s4hanacloud/sap/opu/odata/sap/API_BUSINESS_PARTNER/"

© Copyright. All rights reserved. 59


Unit 5: Manual Deployment

}
},
"db": {
"kind": "sql"
},
//## BEGIN OF INSERT
"xsuaa": {
"kind": "xsuaa"
}
//##END OF INSERT
},
"hana": {
"deploy-format": "hdbtable"
}
}
}

b) Run the command cds add cf-manifest to create the deployment manifest files.
This command creates the files manifest.yml and services-manifest.yml in
your project root. You are going to adjust the manifest.yml file in the next steps.
The services-manifest.yml file contains the Cloud Foundry services, that are
required for your project and are derived from the service bindings in package.json
using the cds.requires configuration.

c) Take a look at the new manifest.yml file in your project root. It shows your
application components and their services dependencies (services sections).

d) For the risk-management-srv application, add the following line into the services
section: - risk-management-destination-service
The resulting risk-management-srv application section should look like the
following:

- name: risk-management-srv
random-route: true # for development only
path: gen/srv
memory: 256M
buildpack: nodejs_buildpack
services:
- risk-management-db
- risk-management-xsuaa
- risk-management-destination-service

You have now defined that your application requires the destination service instance
that you created earlier.

e) In the package.json file in your project root, change the following lines by deleting
or inserting code as indicated:

{
...
...
"cds": {
"requires": {
"API_BUSINESS_PARTNER": {
"kind": "odata",
"model": "srv/external/API_BUSINESS_PARTNER",
//### BEGIN OF DELETE
"credentials": {

© Copyright. All rights reserved. 60


Solution 6: Deploy SAP BTP Cloud Foundry Applications Manually

"url": "https://sandbox.api.sap.com/
s4hanacloud/sap/opu/odata/sap/API_BUSINESS_PARTNER/"
},
//### END OF DELETE
//### BEGIN OF INSERT
"[development]": {
"credentials": {
"url": "https://sandbox.api.sap.com/
s4hanacloud/sap/opu/odata/sap/API_BUSINESS_PARTNER/"
}
},
"[production]": {
"credentials": {
"destination": "API_BUSINESS_PARTNER"
}
}
//### END OF INSERT
},
"db": {
"kind": "sql"
},
"xsuaa": {
"kind": "xsuaa"
}
},
"hana": {
"deploy-format": "hdbtable"
}
}
}

Here you tell the service to distinguish between the development and the
production scenarios. When in development, the API URL is retrieved directly from
the package.json. In a production scenario, the URL should be retrieved from a
destination called API_BUSINESS_PARTNER.

f) Run the command cds build --production to generate the source files required
for production deployment.

g) Run the command cf login to login to the CF environment.

h) Use the API-endpoint from the BTP cockpit. Use your user and password and select
the org and space where you want to deploy the application to.

i) Run the command cf push within the root folder of your BAS project.
The database module and the service module defined in the manifest.yml will be
deployed into your CF account.
The deployment takes a while. You can follow the deployment activity in the terminal
log.

© Copyright. All rights reserved. 61


Unit 5: Manual Deployment

Note:
There also exists the command cf create-service-push, which
additionally to the deployment of the the application modules in
manifest.yml creates or updates the service instances of the services
defined in the services-manifest.yml file. In this case, as you have
created the required service instances manually before, you do not need to
use the command.

j) When the deployment is complete, check the logs for a section where module risk-
management-srv is being started. Within that section, you find a route, which
represents the service URL:

This is the URL for your CAP service that was generated during the deployment. Your
service is running on the SAP Business Technology Platform and is publicly available
via the Internet using this URL.

k) Copy the URL from your deployment log and open it in a new browser tab.

© Copyright. All rights reserved. 62


Solution 6: Deploy SAP BTP Cloud Foundry Applications Manually

l) Try to open the BusinessPartners endpoint.


It should result in an error. The reason is that your service currently cannot access the
SAP API Business Hub sandbox environment because it is missing the API key.
Previously, during local testing, you provided it via the .env file. This is inaccessible in
the BTP environment.

m) You must set the API key as an environment variable apikey for the productive Cloud
Foundry environment. You need to do this manually and just once, by running the
following command in your terminal:cf set-env risk-management-srv apikey
<your-api-key>.
Make sure, that you replace <your-api-key> with your API key from the API
Business Hub.
With the following command:cf env risk-management-srv you can also verify
that the key has been set as user-provided variable.

n) Run the following command: cf restart risk-management-srv


This ensures that your environment variable change takes effect in the application.

o) Open the browser tab with the running service. The BusinessPartners endpoint
should now provide the data from the external service, the SAP API Business Hub
sandbox environment.
Try to open the other service endpoints. The corresponding data should appear. Just
now, it is not stored in an SQLite database, but in your SAP HANA Cloud HDI
Container.
You will notice, that the web application (the UI part) is missing. This was left out on
purpose. You are going to add it to your BTP deployment in a later step, because it
requires an additional component, the so-called application router.

Task 5: Perform a Manual Deployment Using a "Multi Target Application" (MTA) File
In this section, we will create a "Multi Target Application" (MTA) file for deployment. (See the
description 2). MTA is a way to create deployments consisting of multiple modules that can be
implemented in different technologies. Some advantages of this technology are:
● It provides a build tool.
● It creates service instances, service keys, and destinations automatically.
● It deploys content (HTML5, workflow, …).
● It supports blue-green deployment 3.

Compared to the deployment procedure you performed in the previous steps, this will save
you a lot of manual work in the long run.

Task 6: Generate an MTA Deployment Descriptor (mta.yaml)


The MTA deployment is described in the MTA Deployment Descriptor 4, a file called
mta.yaml. In the first step, let CAP generate an initial mta.yaml file.

1. Generate an MTA deployment descriptor (mta.yaml).


a) Open a new terminal in BAS (Terminal → New Terminal).

b) Run the following command cds add mta in the terminal.

© Copyright. All rights reserved. 63


Unit 5: Manual Deployment

The cds Command Line Interface has generated the mta.yaml file based on your
previously created settings in the package.jsonfile.

c) Open the new mta.yaml file.


The mta.yaml file consists of different modules, that are Cloud Foundry apps, and
resources, that are Cloud Foundry services.

Modules:
● risk-management-srv - Your CAP OData service.

● risk-management-db-deployer - Deploys CAP schema and data (CSV files) to


database.

Resources:
The resources are generated from the requires section of cds in the package.json:

● risk-management-db - HANA DB HDI container service instance.

● risk-management-xsuaa - Authorization & Trust Management (xsuaa) service


instance.

The resources are Cloud Foundry service instances, that are automatically created and
updated during the MTA deployment.

d) The risk-management-xsuaa service instance should make use of the xs-


security.json configuration file you generated in an earlier step. Add the following
line to the parameters section of the risk-management-xsuaa resource in the
mta.yaml file:
path: ./xs-security.json
Also remove the config section, as you are providing the configuration via the xs-
security.json file.
The result should look like the following:

# ------------------------------------------------------------
- name: risk-management-xsuaa
# ------------------------------------------------------------
type: org.cloudfoundry.managed-service
parameters:
service: xsuaa
service-plan: application
path: ./xs-security.json # this line was added

The line type: org.cloudfoundry.managed-service tells the MTA deployment


to automatically create the service instance if it does not yet exist. The service and
service-plan parameters tell the MTA deployment what kind of service instance to
create. As you have created the service instance manually before, it will just be
updated with the provided configurations during MTA deployment.

e) The dependency to the destination service instance is still missing in the mta.yaml.
We need to add it manually. As the risk-management-srv module requires the
destination service, add the following line into its requires section:
- name: risk-management-destination-service

© Copyright. All rights reserved. 64


Solution 6: Deploy SAP BTP Cloud Foundry Applications Manually

The result should look like the following:


# --------------------- SERVER MODULE ------------------------
- name: risk-management-srv
# ------------------------------------------------------------
type: nodejs
path: gen/srv
requires:
# Resources extracted from CAP configuration
- name: risk-management-db
- name: risk-management-xsuaa
- name: risk-management-destination-service # this line was added
provides:
- name: srv-api # required by consumers of CAP services (e.g.
approuter)
properties:
srv-url: ${default-url}

f) When adding a requirement, this also needs to be defined in the resources section of
the document.
Add the following lines in the resources section:
# ------------------------------------------------------------
- name: risk-management-destination-service
# ------------------------------------------------------------
type: org.cloudfoundry.managed-service
parameters:
service: destination
service-plan: lite

g) Save the file.

h) Run the following command of the MTA build tool in order to build your project: mbt
build -t ./
The build takes a while. It results in a multitarget application archive file, ending with
the .mtar file extension.

i) Before running the following command, ensure that the SAP HANA database is still
running: cf deploy <.mtar file>
Replace <.mtar file> with the file name of the generated archive. In this case cf
deploy risk-management_1.0.0.mtar.
The deployment takes a while. You can follow the deployment activity in the terminal
log.

j) At the end of the deployment log, you will find a line saying: Application "risk-
management-srv" started and available at "<some_URL>".
Like in this screenshot:

© Copyright. All rights reserved. 65


Unit 5: Manual Deployment

This is the application URL for your CAP service, which is publicly available via the
Internet. Now this might not seem like a big win, because we are achieving the same
deployment result as with the previous manual deployment. But the MTA deployment
offers some more advantages:

● A build tool

● Automatically created service instances

● Service keys

● Destinations

● Content deployment (HTML5, workflow, …)

● Blue-green deployment

You have:
● Created an application.
● Created a UI with SAP Fiori elements.
● Added custom business logic.
● Added an external service.
● Deployed your application manually.

You still have to deploy the UI part of your application. For this deployment, you will need an
application router (approuter). To manage the access to your application, you need to
implement restrictions and roles. We will cover all this in the next part.

© Copyright. All rights reserved. 66


Unit 6
Exercise 7
Define Restrictions and Roles in CDS

Business Scenario
Before deploying to our productive SAP BTP environment, you want to ensure, that only
permitted users can access your app to view and edit data. Therefore, you will first add
authorizations to your CAP service and then add two mock users to further test your app
locally.

Task Flow
In this exercise, you will perform the following tasks:
● Implement authentication support - roles and restrictions - for an application.
● Add local users to test the authentication implementation.

Prerequisite
You have successfully deployed your application manually.

Task 1: Enable Authentication Support


To enable authentication support in CAP, a node.js module called passport needs to be
installed.

1. Enable Authentication Support.

Task 2: Add CAP Role Restrictions to Entities


In this step, you will add authorizations to the Risks service. You will add two different roles
RiskManager and RiskViewer with different access scope.

1. Add CAP Role Restrictions to Entities.

With this change, users who are assigned the role RiskViewer can view ("READ") risks and
mitigations. Users who are assigned the role RiskManager can view and change risks and
mitigations ("*").

Task 3: Add Users for Local Testing


Since the authorization checks have been added to the CAP model, they apply not only when
deployed to the cloud but also for local testing. Therefore, you will need a way to log in to the
application locally.
CAP allows you to add local users for testing as part of the cds configuration. In this tutorial,
we use the .cdsrc.json file to add the users.
The .cdsrc.json file can be used to store project configurations like in the package.json
file. Learn more here 1.

1. Add users for local testing.

© Copyright. All rights reserved. 67


Unit 6: Authorization and Trust Management

Task 4: Access the Risk Application with a User and Password


When accessing the Risks or the Mitigations service in the browser, you get a basic
authorization pop-up window, asking for your user and password. You can use both users that
you defined in the previous step to log in and see how this works.

1. Access the Risk Application with a User and Password.

Task 5: Caveat
There’s no log out functionality yet. To clear the basic authentication login data from the
browser cache, you can either clear the browser cache or simply close all browser windows.
You enabled authentication using passport.js 2. You also added roles and restrictions to
control access to your application. Next you will set up SAP Authorization and Trust
management.

© Copyright. All rights reserved. 68


Unit 6
Solution 7
Define Restrictions and Roles in CDS

Business Scenario
Before deploying to our productive SAP BTP environment, you want to ensure, that only
permitted users can access your app to view and edit data. Therefore, you will first add
authorizations to your CAP service and then add two mock users to further test your app
locally.

Task Flow
In this exercise, you will perform the following tasks:
● Implement authentication support - roles and restrictions - for an application.
● Add local users to test the authentication implementation.

Prerequisite
You have successfully deployed your application manually.

Task 1: Enable Authentication Support


To enable authentication support in CAP, a node.js module called passport needs to be
installed.

1. Enable Authentication Support.


a) Navigate to your risk-management folder in a terminal in the Business Application
Studio. With your cds watch still running in one terminal, it is the easiest to open
another second terminal next to it, by invoking Terminal and the New Terminal in the
menu. Alternatively, you can also suspend cds watch in your existing terminal by
pressing CTRL+C. In both cases, you should already be in the risk-management
folder.

b) Install the passport module. (the --save part makes sure it’s also added as a
dependency to your project's package.json) npm install --save passport.

Task 2: Add CAP Role Restrictions to Entities


In this step, you will add authorizations to the Risks service. You will add two different roles
RiskManager and RiskViewer with different access scope.

1. Add CAP Role Restrictions to Entities.


a) Open the file srv/risk-service.cds.

b) Change the code as shown below and add the restrictions (@(...)) to block to your
Risks and Mitigations entities. You have to delete code - anything between //###

© Copyright. All rights reserved. 69


Unit 6: Authorization and Trust Management

BEGIN OF DELETE and //### END OF DELETE - and add code - anything
between //### BEGIN OF INSERT and //### End OF INSERT.
using {riskmanagement as rm} from '../db/schema';

/**
* For serving end users
*/
service RiskService @(path : 'service/risk') {
//### BEGIN OF DELETE
entity Risks as projection on rm.Risks;
//### END OF DELETE
//### BEGIN OF INSERT
entity Risks @(restrict : [
{
grant : [ 'READ' ],
to : [ 'RiskViewer' ]
},
{
grant : [ '*' ],
to : [ 'RiskManager' ]
}
]) as projection on rm.Risks;
//### END OF INSERT
annotate Risks with @odata.draft.enabled;
//### BEGIN OF DELETE
entity Mitigations as projection on rm.Mitigations;
//### END OF DELETE
//### BEGIN OF INSERT
entity Mitigations @(restrict : [
{
grant : [ 'READ' ],
to : [ 'RiskViewer' ]
},
{
grant : [ '*' ],
to : [ 'RiskManager' ]
}
]) as projection on rm.Mitigations;
//### END OF INSERT
annotate Mitigations with @odata.draft.enabled;
entity BusinessPartners as projection on rm.BusinessPartners;
}

c) Save the file.

With this change, users who are assigned the role RiskViewer can view ("READ") risks and
mitigations. Users who are assigned the role RiskManager can view and change risks and
mitigations ("*").

Task 3: Add Users for Local Testing


Since the authorization checks have been added to the CAP model, they apply not only when
deployed to the cloud but also for local testing. Therefore, you will need a way to log in to the
application locally.
CAP allows you to add local users for testing as part of the cds configuration. In this tutorial,
we use the .cdsrc.json file to add the users.
The .cdsrc.json file can be used to store project configurations like in the package.json
file. Learn more here 1.

1. Add users for local testing.

© Copyright. All rights reserved. 70


Solution 7: Define Restrictions and Roles in CDS

a) In the project, go to the file .cdsrc.json and open it for editing.

b) In the editor, replace its content with the following lines:

{
"[development]": {
"auth": {
"passport": {
"strategy": "mock",
"users": {
"[email protected]": {
"password": "initial",
"ID": "riskviewer",
"userAttributes": {
"email": "[email protected]"
},
"roles": ["RiskViewer"]
},
"[email protected]": {
"password": "initial",
"ID": "riskmanager",
"userAttributes": {
"email": "[email protected]"
},
"roles": ["RiskManager"]
}
}
}
}
}
}

c) Save the file.


The file defines two users, riskviewer and riskmanager. Let's take a look at the
riskmanager example.
The user is defined by an ID, which can be any identifier for a user. The user has an
email, a password parameter, and a rolesparameter.

Task 4: Access the Risk Application with a User and Password


When accessing the Risks or the Mitigations service in the browser, you get a basic
authorization pop-up window, asking for your user and password. You can use both users that
you defined in the previous step to log in and see how this works.

1. Access the Risk Application with a User and Password.


a) In the tab with the running application, navigate back to the launch page, press refresh
in the browser.

b) Choose the Risks tile and in the app press Go.

c) In the pop-up, enter the Username riskmanager.

d) Enter the Password initial.

© Copyright. All rights reserved. 71


Unit 6: Authorization and Trust Management

e) You can now access the Risks application.

Task 5: Caveat
There’s no log out functionality yet. To clear the basic authentication login data from the
browser cache, you can either clear the browser cache or simply close all browser windows.
You enabled authentication using passport.js 2. You also added roles and restrictions to
control access to your application. Next you will set up SAP Authorization and Trust
management.

© Copyright. All rights reserved. 72


Unit 6
Exercise 8
Set Up SAP Authorization and Trust
Management

Business Scenario
You will set up SAP Authorization and Trust Management 1 to secure your application.

Task Flow
In this exercise, you will perform the following tasks:
● Enable authentication support.
● Add roles and scopes.
● Set up application security with XSUAA security configuration.
● Adjust authorization and trust management service (XSUAA) in MTA.

Prerequisite
You have added restrictions and roles to your application.

Task 1: Enable Authentication Support

1. Enable Authentication Support.


To enable authentication support in CAP for SAP BTP, the xssec and xsenv modules
need to be installed.

Task 2: Add Roles and Scopes

1. Add roles and scopes.


In the SAP BTP, Cloud Foundry environment, a single authorization is called scope. For
example, there could be a scope "Read" and a scope "Write" that allow users to read or
write respectively a certain business object. Scopes cannot be assigned to users directly.
They are packaged into roles. For example, the role "Editor" could have "Read" and "Write"
scopes, while the role "Viewer" could have the "Read" scope only.
However, CAP recommends to use roles only and do a one-to-one mapping. See Lesson 1
of this Unit: Defining Restrictions and Roles in CDS we defined two roles.

Task 3: Set Up Application Security with XSUAA Security Configuration

1. Set Up Application Security with XSUAA Security Configuration.


First you need to configure the XSUAA service 2. Create the file xs-security.json in
your RiskManagement project by executing the following in a terminal in BAS:
cds compile srv --to xsuaa >xs-security.json

© Copyright. All rights reserved. 73


Unit 6: Authorization and Trust Management

The generated file contains the configuration of the XSUAA. Behind the scenes, CAP has
taken the authorization parts @(restrict ... ) from your service definition and
created scopes and role templates from it.
For example, it found the roles RiskViewer and RiskManager in the srv/risk-
service.cds file:

entity Risks @(restrict : [


{
grant : ['READ'],
to : ['RiskViewer']
},
{
grant : ['*'],
to : ['RiskManager']
}
]) as projection on rm.Risks;

Then it created scopes and roles for both in the xs-security.json file in your project:

{
"xsappname": "risk-management",
"tenant-mode": "dedicated",
"scopes": [
{
"name": "$XSAPPNAME.RiskViewer",
"description": "RiskViewer"
},
{
"name": "$XSAPPNAME.RiskManager",
"description": "RiskManager"
}
],
"attributes": [],
"role-templates": [
{
"name": "RiskViewer",
"description": "generated",
"scope-references": ["$XSAPPNAME.RiskViewer"],
"attribute-references": []
},
{
"name": "RiskManager",
"description": "generated",
"scope-references": ["$XSAPPNAME.RiskManager"],
"attribute-references": []
}
]
}

Task 4: Adjust Authorization and Trust Management Service (XSUAA) in MTA

1. Adjust Authorization and Trust Management Service (XSUAA) in MTA.


The next step is to adjust the configuration of the Authorization and Trust Management
Service in the mta.yaml to allow user login, authorization, and authentication checks.

You added XSUAA security settings to your application. Now you need to add an application
router (approuter) to route your application's requests from the web browser to either the
service or the UI.

© Copyright. All rights reserved. 74


Unit 6
Solution 8
Set Up SAP Authorization and Trust
Management

Business Scenario
You will set up SAP Authorization and Trust Management 1 to secure your application.

Task Flow
In this exercise, you will perform the following tasks:
● Enable authentication support.
● Add roles and scopes.
● Set up application security with XSUAA security configuration.
● Adjust authorization and trust management service (XSUAA) in MTA.

Prerequisite
You have added restrictions and roles to your application.

Task 1: Enable Authentication Support

1. Enable Authentication Support.


To enable authentication support in CAP for SAP BTP, the xssec and xsenv modules
need to be installed.
a) Open a new terminal in BAS (Terminal → New Terminal).

b) In the terminal, run the following command to install the hdb module and automatically
add it as a dependency into the package.json file of your project: npm i --save
@sap/xssec @sap/xsenv

Task 2: Add Roles and Scopes

1. Add roles and scopes.


In the SAP BTP, Cloud Foundry environment, a single authorization is called scope. For
example, there could be a scope "Read" and a scope "Write" that allow users to read or
write respectively a certain business object. Scopes cannot be assigned to users directly.
They are packaged into roles. For example, the role "Editor" could have "Read" and "Write"
scopes, while the role "Viewer" could have the "Read" scope only.
However, CAP recommends to use roles only and do a one-to-one mapping. See Lesson 1
of this Unit: Defining Restrictions and Roles in CDS we defined two roles.
a) If not already done, read this lesson.

Task 3: Set Up Application Security with XSUAA Security Configuration

1. Set Up Application Security with XSUAA Security Configuration.

© Copyright. All rights reserved. 75


Unit 6: Authorization and Trust Management

First you need to configure the XSUAA service 2. Create the file xs-security.json in
your RiskManagement project by executing the following in a terminal in BAS:
cds compile srv --to xsuaa >xs-security.json
The generated file contains the configuration of the XSUAA. Behind the scenes, CAP has
taken the authorization parts @(restrict ... ) from your service definition and
created scopes and role templates from it.
For example, it found the roles RiskViewer and RiskManager in the srv/risk-
service.cds file:

entity Risks @(restrict : [


{
grant : ['READ'],
to : ['RiskViewer']
},
{
grant : ['*'],
to : ['RiskManager']
}
]) as projection on rm.Risks;

Then it created scopes and roles for both in the xs-security.json file in your project:

{
"xsappname": "risk-management",
"tenant-mode": "dedicated",
"scopes": [
{
"name": "$XSAPPNAME.RiskViewer",
"description": "RiskViewer"
},
{
"name": "$XSAPPNAME.RiskManager",
"description": "RiskManager"
}
],
"attributes": [],
"role-templates": [
{
"name": "RiskViewer",
"description": "generated",
"scope-references": ["$XSAPPNAME.RiskViewer"],
"attribute-references": []
},
{
"name": "RiskManager",
"description": "generated",
"scope-references": ["$XSAPPNAME.RiskManager"],
"attribute-references": []
}
]
}

Task 4: Adjust Authorization and Trust Management Service (XSUAA) in MTA

1. Adjust Authorization and Trust Management Service (XSUAA) in MTA.


The next step is to adjust the configuration of the Authorization and Trust Management
Service in the mta.yaml to allow user login, authorization, and authentication checks.

© Copyright. All rights reserved. 76


Solution 8: Set Up SAP Authorization and Trust Management

a) In your mta.yaml file, change the following:

_schema-version: '3.1'
...
resources:
...
# ------------------------------------------------------------
- name: risk-management-xsuaa
# ------------------------------------------------------------
type: org.cloudfoundry.managed-service
parameters:
service: xsuaa
service-plan: application
path: ./xs-security.json
//### BEGIN OF INSERT
config:
xsappname: 'risk-management-${space}'
role-collections:
- name: 'RiskManager-${space}'
description: Manage Risks
role-template-references:
- $XSAPPNAME.RiskManager
- name: 'RiskViewer-${space}'
description: View Risks
role-template-references:
- $XSAPPNAME.RiskViewer
//### END OF INSERT

b) Save the file.


The configuration for XSUAA is read from the xs-security.json file that was
updated in the previous step.
However, in the config element of the YAML file, values can be added and
overwritten.
The value xsappname gets overwritten with a Cloud Foundry space-dependent value $
{space}. The name has to be unique within an SAP BTP subaccount.
This allows multiple deployments of this application in different spaces of the same
subaccount. This is useful when different members of a team want to try out the
application and don't want to create a new subaccount for each team member.
For a productive application, the xsappname should be explicitly set to the desired
value.
Further, you can add role collections using the xs-security.json file. Since role
collections need to be unique in a subaccount like the xsappname, you can add it here
and use the ${space} variable to make them unique like for the xsappname.
Alternatively, role collections 3 can be manually added in the SAP BTP cockpit.

You added XSUAA security settings to your application. Now you need to add an application
router (approuter) to route your application's requests from the web browser to either the
service or the UI.

© Copyright. All rights reserved. 77


Unit 6
Exercise 9
Create an Application Router

Business Scenario
You will create an application router (approuter) to route requests originating in the web
browser to either the CAP service or to the UI.
For your application to run on the cloud, you need another component on top of the service
and the UI. It will route the request from the web browser either to the CAP service or to the
provider of the UI sources. This component also ensures that authenticated and authorized
users get a token from the XSUAA service, which is also routed to the CAP service.
This component is called an “application router” (approuter). "The application router is the
single point-of-entry for an application running in the Cloud Foundry environment on SAP
BTP. The application router is used to serve static content, authenticate users, rewrite URLs,
and forward or proxy requests to other microservices while propagating user information." 1.
You can either have a standalone approuter or a managed approuter 2. In this module, you are
going to use the standalone approuter, because it does not lead to other service
dependencies. The managed approuter is part of other SAP BTP services like the SAP
Launchpad Service or the SAP Portal Service. Checkout this blog 3 for more detailed
information on the managed approuter versus the standalone approuter.

Task Flow
In this exercise, you will perform the following tasks:
● Create a standalone approuter.
● Configure an approuter using a JSON file.

Prerequisite
You have set up SAP authorization and trust management (XSUAA).

Task 1: Create a Standalone Approuter

1. Create a standalone approuter.

Task 2: Configure an Approuter Using a JSON File

1. Configure the approuter by creating a file.

You added an approuter to your application. In the next step, you will add the UI application to
your project.

© Copyright. All rights reserved. 78


Unit 6
Solution 9
Create an Application Router

Business Scenario
You will create an application router (approuter) to route requests originating in the web
browser to either the CAP service or to the UI.
For your application to run on the cloud, you need another component on top of the service
and the UI. It will route the request from the web browser either to the CAP service or to the
provider of the UI sources. This component also ensures that authenticated and authorized
users get a token from the XSUAA service, which is also routed to the CAP service.
This component is called an “application router” (approuter). "The application router is the
single point-of-entry for an application running in the Cloud Foundry environment on SAP
BTP. The application router is used to serve static content, authenticate users, rewrite URLs,
and forward or proxy requests to other microservices while propagating user information." 1.
You can either have a standalone approuter or a managed approuter 2. In this module, you are
going to use the standalone approuter, because it does not lead to other service
dependencies. The managed approuter is part of other SAP BTP services like the SAP
Launchpad Service or the SAP Portal Service. Checkout this blog 3 for more detailed
information on the managed approuter versus the standalone approuter.

Task Flow
In this exercise, you will perform the following tasks:
● Create a standalone approuter.
● Configure an approuter using a JSON file.

Prerequisite
You have set up SAP authorization and trust management (XSUAA).

Task 1: Create a Standalone Approuter

1. Create a standalone approuter.


a) Using a terminal in BAS, create a folder approuter, where you store all approuter
artifacts, and switch to the new folder:

mkdir approuter
cd approuter

© Copyright. All rights reserved. 79


Unit 6: Authorization and Trust Management

Note:
You could have completed this step in the BAS file explorer instead of the
terminal. However, since we will need a command line interface in the
folder in the next step, we decided to use the terminal for creating the
folder.

b) In the terminal of the new approuter folder, initialize npm and install the latest version
of approuter NPM module 4:

npm init --yes


npm install @sap/approuter

The functionality of the approuter is provided by the @sap/approuter NPM module.

c) Check the required Node.js version for approuter.


This is declared in the package.json file of the approuter. You can check it with this
script:
cat node_modules/@sap/approuter/package.json | grep '"node"'
It outputs something like:
"node": "^12.0.0 || ^14.0.0"
In this example, the approuter supports Node.js 12.x.x and 14.x.x versions.

d) Add the required Node.js version to the approuter/package.json file. This depends
on the supported versions of the approuter, ^14.0.0 in this example. Also add the start
script for the approuter.
{
"name": "approuter",
...
"scripts": {
//### BEGIN OF DELETE
"test": "echo \"Error: no test specified\" && exit 1"
//### END OF DELETE
//### BEGIN OF INSERT
"start": "node node_modules/@sap/approuter/approuter.js"
//### END OF INSERT
},
...
"dependencies": {
"@sap/approuter": "^8.5.5"
//### BEGIN OF DELETE
}
//### END OF DELETE
//### BEGIN OF INSERT
},
"engines": {
"node": "^14.0.0"
}
//### END OF INSERT
}

e) Save the file.

Task 2: Configure an Approuter Using a JSON File

1. Configure the approuter by creating a file.

© Copyright. All rights reserved. 80


Solution 9: Create an Application Router

a) Configure the approuter by creating a file xs-app.json in the approuter folder with
the following content:

{
"welcomeFile": "/app/risks/webapp/index.html",
"authenticationMethod": "route",
"sessionTimeout": 30,
"logout": {
"logoutEndpoint": "/do/logout",
"logoutPage": "/"
},
"routes": [
{
"source": "^/app/(.*)$",
"target": "$1",
"localDir": "resources",
"authenticationType": "xsuaa"
},
{
"source": "^/service/(.*)$",
"destination": "srv-binding",
"authenticationType": "xsuaa"
}
]
}

The configuration in the routes array tells the approuter how to respond to requests.

● The files in the resources folder will be served for all requests to /app. Later,
there’s an explanation on how you get the "app" files into this resource folder.

● All requests starting with /service will be forwarded to the CAP service based on
the URL we configured in the MTA using the destination srv_app. Remember, the
risk service is reachable via /service/risk. Further services are automatically
routed as long as they start with /service/ as well.

Further, the approuter will automatically redirect to the /app/launchpage.html


when accessed without a path, which will then serve the file resources/
launchpage.html.

You added an approuter to your application. In the next step, you will add the UI application to
your project.

© Copyright. All rights reserved. 81


Unit 6
Exercise 10
Add Approuter to MTA

Business Scenario
You will add the UI application and the approuter to the mta.yaml file.

Task Flow
In this exercise, you will perform the following task:
● Add the UI and the approuter to the mta.yaml file.

● Re-build and re-deploy the .mtar file.

Prerequisites
You have set up a standalone approuter.
The automatic creation of the mta.yaml file added everything that is needed from the CAP
side to the mta.yaml file:

● The service.
● The database deployer.
● The dependency to the XSUAA and SAP HANA Cloud service.

Your SAP Fiori elements-based UI application, however, is still missing. You will have to add
this module manually since, currently, there is no automation support to do this.
The approuter is also an application, just like your CAP service and the UI. To deploy the
approuter, you will need to add a configuration to the MTA file that you created earlier.

Task 1: Add the UI and the Approuter to the mta.yaml File

1. Add modules to the mta.yaml file.

Task 2: Re-Build and re-Deploy the .mtar File

1. Re-build and re-deploy the .mtar file.

You added the UI and the approuter to the MTA file. Next, you will assign the required role
collections to your user and check if your user regains access to the application data.

© Copyright. All rights reserved. 82


Unit 6
Solution 10
Add Approuter to MTA

Business Scenario
You will add the UI application and the approuter to the mta.yaml file.

Task Flow
In this exercise, you will perform the following task:
● Add the UI and the approuter to the mta.yaml file.

● Re-build and re-deploy the .mtar file.

Prerequisites
You have set up a standalone approuter.
The automatic creation of the mta.yaml file added everything that is needed from the CAP
side to the mta.yaml file:

● The service.
● The database deployer.
● The dependency to the XSUAA and SAP HANA Cloud service.

Your SAP Fiori elements-based UI application, however, is still missing. You will have to add
this module manually since, currently, there is no automation support to do this.
The approuter is also an application, just like your CAP service and the UI. To deploy the
approuter, you will need to add a configuration to the MTA file that you created earlier.

Task 1: Add the UI and the Approuter to the mta.yaml File

1. Add modules to the mta.yaml file.


a) Add the risk-management-approuter and the risk-management-app module for
the Approuter to the mta.yaml file:

# -------------------- SIDECAR MODULE ------------------------


- name: risk-management-db-deployer
# ------------------------------------------------------------
type: hdb
path: gen/db
parameters:
buildpack: nodejs_buildpack
requires:
# 'hana' and 'xsuaa' resources extracted from CAP configuration
- name: risk-management-db
- name: risk-management-xsuaa

#//### BEGIN OF INSERT

© Copyright. All rights reserved. 83


Unit 6: Authorization and Trust Management

# -------------------- APPROUTER -----------------------------


- name: risk-management-approuter
# ------------------------------------------------------------
type: nodejs
path: approuter
requires:
- name: risk-management-xsuaa
- name: srv-api
group: destinations
properties:
forwardAuthToken: true
strictSSL: true
name: srv-binding
url: "~{srv-url}"
build-parameters:
requires:
- name: risk-management-app
artifacts:
- ./*
target-path: resources
# -------------------- UI -----------------------------------
- name: risk-management-app
# ------------------------------------------------------------
type: html5
path: app
build-parameters:
supported-platforms: []
#//### END OF INSERT

b) Save the file.


The approuter takes the UI resources of the risk-management-app and puts it in the
resources directory. This is where the xs-app.json looks for the files requested
for /app/....
The risk-management-xsuaa binding adds your already existing XSUAA service
instance to the approuter. This enables login and log out. The approuter forwards
requests with the authentication token (Authorization: Bearer <jwt-token>)
to the CAP service. The CAP service then uses the token for authentication and
authorization checks.
The srv-binding creates an environment variable destinations that contains a
JSON array with one object containing the destination of the CAP service. This is
required to forward requests to the CAP service.
The generated environment variable looks like this:
destinations='[{ "name": "srv-binding", "forwardAuthToken": true,
"strictSSL": true, url: "https://..." }]
The URL is taken from the risk-management-srv module that needs to be enhanced
to export this information.

Task 2: Re-Build and re-Deploy the .mtar File

1. Re-build and re-deploy the .mtar file.


a) Build your project with the MTA Build Tool (MBT):
mbt build -t ./
Make sure you're in the root folder of your project.

© Copyright. All rights reserved. 84


Solution 10: Add Approuter to MTA

b) Deploy your project to SAP BTP:


cf deploy risk-management_1.0.0.mtar
Additional Documentation: How to build an MTA archive from the project sources 1.

c) When the deployment is finished, check the deployment log for a line saying:
Application "risk-management-approuter" started and available at
"<some_URL>"
Like in the following screenshot:

This is the URL of the Approuter, that, from now on, will take care of all the requests to
your application.

d) Copy the URL and open it in a new browser tab. In the background, the approuter
authenticates your user and provides it with the authorizations that have been
assigned to the user. Open the Risks application tile and try to retrieve data by
selecting the Go button.
As your user does not have the required application roles yet, the result should look
like the following:

You added the UI and the approuter to the MTA file. Next, you will assign the required role
collections to your user and check if your user regains access to the application data.

© Copyright. All rights reserved. 85


Unit 6
Exercise 11
Assign Role Collections

Business Scenario
You will add a role collection to access your deployed application through the SAP BTP
cockpit with an authenticated and authorized user.
As the name implies, role collections "group together authorizations for resources and
services. Role collections consist of individual roles. Role collections are account-specific.
Role collections that exist in the global account don’t exist in the subaccounts. Likewise, role
collections in subaccounts aren’t available in the global account." 1.
The way this application is designed, the deployed service can only be accessed when a user
has a corresponding role collection assigned. If users tried to open the application without this
authorization, they would get a Forbidden message. How do you assign the role collection to
a user?

Task Flow
In this exercise, you will perform the following task: Assign a role collection.

Prerequisite
You added the UI and approuter to the mta.yaml file.

Assign a Role Collection

1. Assign a role collection.

You have assigned a role collection to access the application through the SAP BTP Cockpit.

© Copyright. All rights reserved. 86


Unit 6
Solution 11
Assign Role Collections

Business Scenario
You will add a role collection to access your deployed application through the SAP BTP
cockpit with an authenticated and authorized user.
As the name implies, role collections "group together authorizations for resources and
services. Role collections consist of individual roles. Role collections are account-specific.
Role collections that exist in the global account don’t exist in the subaccounts. Likewise, role
collections in subaccounts aren’t available in the global account." 1.
The way this application is designed, the deployed service can only be accessed when a user
has a corresponding role collection assigned. If users tried to open the application without this
authorization, they would get a Forbidden message. How do you assign the role collection to
a user?

Task Flow
In this exercise, you will perform the following task: Assign a role collection.

Prerequisite
You added the UI and approuter to the mta.yaml file.

Assign a Role Collection

1. Assign a role collection.


a) In your subaccount in the SAP BTP cockpit tab navigate to the Security tab. Choose
Users and click on your username.

b) After clicking on your user, a new view displays at the right side. Click on the Assign
Role Collection button.

© Copyright. All rights reserved. 87


Unit 6: Authorization and Trust Management

c) From the list, choose RiskManager-DEV. Click on the Assign Role Collection button.

Now you are ready to access the application!

d) In the left pane of your subaccount, navigate to the Cloud Foundry tab and choose
Spaces.

e) Select your space.

f) Verify that the risk-management application has been deployed and that the risk-
management-approuter is running.

© Copyright. All rights reserved. 88


Solution 11: Assign Role Collections

g) Choose the row risk-management-approuter.

h) Choose the link under Application Routes.

i) Verify that the deployed application is running and showing its home screen.

j) Press the Risks tile and then in the application the Go button.
You should see the final deployed application with the data:

© Copyright. All rights reserved. 89


Unit 6: Authorization and Trust Management

Note:
In some cases, your browser might still have cached the authorization
information from the previous app call. When you still receive the
Forbidden message, try to either delete your browser cache and cookies
or to close and reopen your browser.

You have assigned a role collection to access the application through the SAP BTP Cockpit.

© Copyright. All rights reserved. 90


Unit 7
Exercise 12
Create and Connect a GitHub Repository

Business Scenario
In this exercise, you will create a public GitHub 1 repository for the source code of your
application.

Task Flow
In this exercise, you will perform the following tasks:
● Create a public GitHub repository to store the source code of a project.
● Create a personal access token for GitHub.
● Connect your GitHub repository with your CAP project.
● Initialize the local git repository.

Prerequisite
To create a GitHub repository, you need a CAP project and a GitHub user. If you do not have a
GitHub user, sign up for GitHub first.

Task 1: Create a Public GitHub Repository

1. Create a Public GitHub Repository to store the source code of a project.

Task 2: Create a Personal Access Token for GitHub

1. Create a Personal Access Token for GitHub.


To create a personal access token, which you can use instead of a password, follow the
steps described in Creating a personal access token 2.

Task 3: Connect Your GitHub Repository With Your CAP Project


You have created a new, empty GitHub repository. To be able to use it as a repository for your
risk management application source code, you need to connect it with your CAP project. Until
now, the only place where your project's source code resided was your personal dev space in
SAP Business Application Studio.

1. Connect Your GitHub Repository with Your CAP Project.

Task 4: Initialize the Local git Repository


Since we cloned the starter template from GitHub, we already have a GitHub repository.
Therefore, we do not have to create a new local one. All we have to do is to commit all our
recent changes, link the new GitHub repository with our local one and to push the changes to
GitHub.

1. Initialize the local git repository.

You have connected your CAP project with your public GitHub repository using git commands
4.

© Copyright. All rights reserved. 91


Unit 7
Solution 12
Create and Connect a GitHub Repository

Business Scenario
In this exercise, you will create a public GitHub 1 repository for the source code of your
application.

Task Flow
In this exercise, you will perform the following tasks:
● Create a public GitHub repository to store the source code of a project.
● Create a personal access token for GitHub.
● Connect your GitHub repository with your CAP project.
● Initialize the local git repository.

Prerequisite
To create a GitHub repository, you need a CAP project and a GitHub user. If you do not have a
GitHub user, sign up for GitHub first.

Task 1: Create a Public GitHub Repository

1. Create a Public GitHub Repository to store the source code of a project.


a) Open and sign in to https://github.com/.

b) In the Repositories tab, choose New to create a new repository.

c) As the Repository name, enter RiskManagement. Don't tick any of the Initialize this
repository with checkboxes.

d) Choose Create repository.

© Copyright. All rights reserved. 92


Solution 12: Create and Connect a GitHub Repository

e) Copy the HTTPS URL of your newly created GitHub repository.

Task 2: Create a Personal Access Token for GitHub

1. Create a Personal Access Token for GitHub.


To create a personal access token, which you can use instead of a password, follow the
steps described in Creating a personal access token 2.

Task 3: Connect Your GitHub Repository With Your CAP Project


You have created a new, empty GitHub repository. To be able to use it as a repository for your
risk management application source code, you need to connect it with your CAP project. Until
now, the only place where your project's source code resided was your personal dev space in
SAP Business Application Studio.

1. Connect Your GitHub Repository with Your CAP Project.


a) Return to your SAP Business Application Studio.

b) Open a new terminal and navigate to your project root folder.

© Copyright. All rights reserved. 93


Unit 7: Automated Deployment

c) Enter your email address and username. You can use the email address that you've
used to register your GitHub account:

git config --global user.email "[email protected]"


git config --global user.name "Your Name"

This configures the git command line tool locally in your Business Application Studio
dev space. Now when you do file changes and commit them to a git history, git will use
the configured name and email in these commits.

Task 4: Initialize the Local git Repository


Since we cloned the starter template from GitHub, we already have a GitHub repository.
Therefore, we do not have to create a new local one. All we have to do is to commit all our
recent changes, link the new GitHub repository with our local one and to push the changes to
GitHub.

1. Initialize the local git repository.


a) Add all directories and files to the git staging area. Perform the command:
Perform the command:git add.

b) Create the first commit in your git repository.


Perform the command:git commit -m "Push project content to GitHub"

c) Add your copied GitHub repository URL from the previous part of the exercise as
remote repository (without the angle brackets '<' and '>' ):
Perform the command:git remote set-url origin <copied Git repository
url.git>
This tells your local git repository in the Business Application Studio dev space, that it
has a remote counterpart on GitHub. The remote counterpart should act as the origin,
thus it is the repository that you and your colleagues use as the central repository of
your project.

d) Push the commit with your project content to this GitHub repository:
Perform the command:git push -u origin main

© Copyright. All rights reserved. 94


Solution 12: Create and Connect a GitHub Repository

This tells your local git to push the main branch to the remote repository. The -u
option is used because the branch main did not yet exist on the remote repository.

e) When prompted, enter your GitHub username and the personal access token, that you
have created previously.

Note:
The prompt appears in the upper middle of the SAP Business Application
Studio, not in the terminal tab that you have used until now.

You have connected your CAP project with your public GitHub repository using git commands
4.

© Copyright. All rights reserved. 95


Unit 7
Exercise 13
Enable SAP Continuous Integration and
Delivery

Business Scenario
In this exercise, you will enable the SAP Continuous Integration and Delivery (CI/CD) service
for your project.
"Continuous integration (CI) describes a software development process, in which various
team members integrate their contributions frequently into a single main line. Before each
integration, the changes are verified through builds and automated testing. Thereby, you can
detect errors as quickly as possible and prevent integration problems before completing the
development."
"Continuous delivery (CD) adds the aspect that any change that has successfully passed the
tests is immediately ready to be deployed to production, both from a technical and a
qualitative point of view."
For more information about CI/CD such as CI principles and process flows, see:
● Continuous Integration Principles1
● Continuous Integration and Continuous Delivery Guide2

Task Flow
In this exercise, you will perform the following tasks:
● Create and Administer Continuous Integration and Delivery Service.
● Configure Credentials in SAP Continuous Integration and Delivery.
● Configure the GitHub Repository in SAP Continuous Integration and Delivery.

Prerequisite
You have connected your CAP project to your GitHub repository.

Task 1: Create and Administer Continuous Integration and Delivery Service

1. Create and Administer Continuous Integration and Delivery Service.

Task 2: Configure Credentials in SAP Continuous Integration and Delivery

1. Configure Credentials in SAP Continuous Integration and Delivery.


The SAP Continuous Integration and Delivery service will act as an automation tool. It will
retrieve the latest state of your GitHub repository, build your project and deploy it to your
SAP BTP, Cloud Foundry environment. You need to configure GitHub and SAP BTP
credentials for the service to be able to connect to these environments.

© Copyright. All rights reserved. 96


Exercise 13: Enable SAP Continuous Integration and Delivery

Task 3: Configure the GitHub Repository in SAP Continuous Integration and Delivery

1. Configure the GitHub Repository in SAP Continuous Integration and Delivery.


The SAP Continuous Integration and Delivery service can manage multiple repositories.
You need to configure your GitHub repository so that the service is able to retrieve
sources from it.

You have enabled SAP Continuous Integration and Delivery for your project.

© Copyright. All rights reserved. 97


Unit 7
Solution 13
Enable SAP Continuous Integration and
Delivery

Business Scenario
In this exercise, you will enable the SAP Continuous Integration and Delivery (CI/CD) service
for your project.
"Continuous integration (CI) describes a software development process, in which various
team members integrate their contributions frequently into a single main line. Before each
integration, the changes are verified through builds and automated testing. Thereby, you can
detect errors as quickly as possible and prevent integration problems before completing the
development."
"Continuous delivery (CD) adds the aspect that any change that has successfully passed the
tests is immediately ready to be deployed to production, both from a technical and a
qualitative point of view."
For more information about CI/CD such as CI principles and process flows, see:
● Continuous Integration Principles1
● Continuous Integration and Continuous Delivery Guide2

Task Flow
In this exercise, you will perform the following tasks:
● Create and Administer Continuous Integration and Delivery Service.
● Configure Credentials in SAP Continuous Integration and Delivery.
● Configure the GitHub Repository in SAP Continuous Integration and Delivery.

Prerequisite
You have connected your CAP project to your GitHub repository.

Task 1: Create and Administer Continuous Integration and Delivery Service

1. Create and Administer Continuous Integration and Delivery Service.


a) Enter your SAP BTP account. In Account Explorer, under Directories and Subaccounts,
select your subaccount and navigate to the Services tab in the left navigation bar. Go
to Service Marketplace.

b) Enter Continuous Integration & Delivery in the search box. If the tile is displayed, select
it and proceed to substep c.

© Copyright. All rights reserved. 98


Solution 13: Enable SAP Continuous Integration and Delivery

If the tile does not displays, it must be entitled. To achieve this, select Entitlements in
the left bar of your subaccount, then on the upper-right side, select Configure
Entitlements, then Add Service Plans. A pop-up displays, on the left side of the pop-up
select the Continuous Integration & Delivery entitlement and on the right side select
the trial flag. Confirm the pop-up (select Add 1 Service Plan). Navigate back to the
Service Marketplace of your subaccount and try again. The tile should now display.

c) Choose Create.

d) Accept the default settings and choose Create.

© Copyright. All rights reserved. 99


Unit 7: Automated Deployment

Note:
The default settings can change from time to time. So yours might differ
from them on the screenshot.

e) You can Close the pop-up Creation in Progress

f) In your SAP BTP subaccount, choose Security → Users.

g) Choose your user name.

h) On the right side, click on Assign Role Collections.

i) From the list, select CICD Service Administrator and choose Assign Role Collection.
Your user is now authorized to use and administer the Continuous Integration and
Delivery service.

Task 2: Configure Credentials in SAP Continuous Integration and Delivery

1. Configure Credentials in SAP Continuous Integration and Delivery.


The SAP Continuous Integration and Delivery service will act as an automation tool. It will
retrieve the latest state of your GitHub repository, build your project and deploy it to your
SAP BTP, Cloud Foundry environment. You need to configure GitHub and SAP BTP
credentials for the service to be able to connect to these environments.
a) In your SAP BTP subaccount navigate to Services and then to Instances and
Subscriptions.

b) Choose the Go to Application icon located next to the Continuous Integration & Delivery
subscription.

c) Use your credentials to log in to the application.

d) In the Credentials tab in SAP Continuous Integration and Delivery, choose + (Create
Credentials).
If your GitHub repository is private, configure credentials for it, so that the Continuous
Integration & Delivery service can connect to it.

Note:
If your GitHub repository isn't private, you can skip this step.

© Copyright. All rights reserved. 100


Solution 13: Enable SAP Continuous Integration and Delivery

e) Enter the following data:


Field Value
Name <a freely chosen name for your credential, which is unique in
your SAP BTP subaccount>. In this example, the name of the
credential is github.

Type <select> Basic Authentication


Username <your GitHub username>
Password <use the personal access token, which you've created in Gi-
tHub in a previous exercise>

f) To create credentials for deploying to the SAP BTP, Cloud Foundry environment, go to
the Credentials tab and choose + (Create Credentials).

g) Enter the following data:


Field Value
Name <enter a freely chosen name for your credentials, which is
unique in your SAP BTP subaccount.> In this example, the
name of the credentials is cfdeploy

Type <select> Basic Authentication


Username <your username for the SAP BTP cockpit>

© Copyright. All rights reserved. 101


Unit 7: Automated Deployment

Field Value
Password <use your password for the SAP BTP cockpit>

h) Your result will look like this:

Task 3: Configure the GitHub Repository in SAP Continuous Integration and Delivery

1. Configure the GitHub Repository in SAP Continuous Integration and Delivery.


The SAP Continuous Integration and Delivery service can manage multiple repositories.
You need to configure your GitHub repository so that the service is able to retrieve
sources from it.
a) In the Repositories tab in SAP Continuous Integration and Delivery, choose + (Add
repository).

b) For Name, enter a freely chosen name for your repository, which is unique in your SAP
BTP subaccount. In this example, the name of the repository is risk-management-
repo.

c) As Clone URL enter the HTTPS Clone URL of your GitHub repository. Find it by
selecting the green Code button in your GitHub repository. Choose the Clipboard icon
to copy the URL.

© Copyright. All rights reserved. 102


Solution 13: Enable SAP Continuous Integration and Delivery

d) As Credentials, select github that you created in the previous steps.

e) Leave the default values in the Webhook Event Receiver section. Make sure that Type is
set to GitHub.

f) Select Add to add the repository to your SAP Continuous Integration and Delivery
service.

You have enabled SAP Continuous Integration and Delivery for your project.

© Copyright. All rights reserved. 103


Unit 7
Exercise 14
Configure a CI/CD Job

Business Scenario
You have enabled SAP Continuous Integration and Delivery for your GitHub repository and for
deployment into SAP BTP, Cloud Foundry environment. But until now, you have not told the
service what exactly it is supposed to do for you. After completing the next steps, you will
have configured a job in SAP Continuous Integration and Delivery. The job is the actual
automation part of this course.

Task Flow
In this exercise, you will perform the following task:
● Configure a job in the SAP Continuous Integration and Delivery service.

Prerequisite
You have enabled the SAP Continuous Integration and Delivery service for your GitHub
repository and for deployment into SAP BTP, Cloud Foundry environment.

Configure a Job in the SAP Continuous Integration and Delivery Service

1. Create a Job.

2. Configure a Webhook.
The goal is for your SAP Continuous Integration and Delivery service job to run whenever
there is a change on the main branch of your GitHub repository. To retrieve the
information about a change on the repository, you make use of a webhook. There is a
Webhook Event Receiver for your repository in the SAP Continuous Integration and
Delivery service, and you need to configure the webhook itself in your GitHub repository.

You have configured a SAP Continuous Integration and Delivery job, which automates the
build and deployment process of your project.

© Copyright. All rights reserved. 104


Unit 7
Solution 14
Configure a CI/CD Job

Business Scenario
You have enabled SAP Continuous Integration and Delivery for your GitHub repository and for
deployment into SAP BTP, Cloud Foundry environment. But until now, you have not told the
service what exactly it is supposed to do for you. After completing the next steps, you will
have configured a job in SAP Continuous Integration and Delivery. The job is the actual
automation part of this course.

Task Flow
In this exercise, you will perform the following task:
● Configure a job in the SAP Continuous Integration and Delivery service.

Prerequisite
You have enabled the SAP Continuous Integration and Delivery service for your GitHub
repository and for deployment into SAP BTP, Cloud Foundry environment.

Configure a Job in the SAP Continuous Integration and Delivery Service

1. Create a Job.
a) In the Jobs tab in SAP Continuous Integration and Delivery, choose + (Create Job).

b) Enter the following data:


Key Value
Job Name A freely chosen name for your job, which is unique in your SAP
BTP subaccount. In this example, the name of the job is risk-
management-job.
Repository <Choose the repository you created earlier from the drop-
down> (for example, risk-management-repo).
Branch <Enter the GitHub branch from which you want to receive
push events. In this example, the name of the branch is main>
Pipeline <Choose> SAP Cloud Application Programming Model

c) Scroll down to Stages and select Source Repository as the Configuration Mode.

© Copyright. All rights reserved. 105


Unit 7: Automated Deployment

This tells your job, that the actual stages, the work that is to be performed, will be
defined within the source repository itself. You are going to configure the stages in a
following part.

d) Choose Create.

2. Configure a Webhook.
The goal is for your SAP Continuous Integration and Delivery service job to run whenever
there is a change on the main branch of your GitHub repository. To retrieve the
information about a change on the repository, you make use of a webhook. There is a
Webhook Event Receiver for your repository in the SAP Continuous Integration and
Delivery service, and you need to configure the webhook itself in your GitHub repository.
a) Open the Repositories tab.

b) Select your repository, in this case risk-management-repo.

c) Select the ... (More) button and choose Webhook Data.

© Copyright. All rights reserved. 106


Solution 14: Configure a CI/CD Job

d) The following pop-up window appears:

e) Leave it open and, in your project in GitHub, go to the Settings tab.

f) From the navigation pane, choose Webhooks or Hooks.

g) Choose Add webhook.

h) Enter the Payload URL, Content type, and Secret from the Webhook Creation pop-up in
SAP Continuous Integration and Delivery. For all other settings, leave the default
values.

i) Choose Add webhook.

© Copyright. All rights reserved. 107


Unit 7: Automated Deployment

Now, whenever there is a push event to any branch of your repository, the webhook
will be triggered. The webhook then notifies your SAP Continuous Integration and
Delivery service, using the specified Payload URL and Secret.

You have configured a SAP Continuous Integration and Delivery job, which automates the
build and deployment process of your project.

© Copyright. All rights reserved. 108


Unit 7
Exercise 15
Configure the Stages of a CI/CD Pipeline

Business Scenario
You have connected your SAP Continuous Integration and Delivery service to your GitHub
repository and have created a job that is going to take care of automated build and
deployment. Now the job needs to know what steps it needs to perform. The definition of
steps that need to be performed is done using a so-called pipeline. The configuration syntax
of the pipeline that you are going to configure is based on SAP's Open-Source Project Piper 1.
The pipeline configuration is done within your project.

Task Flow
In this exercise, you will configure stages of a project "Piper" pipeline.

Prerequisite
You have enabled your application for CI/CD.

Configure Stages of a CI/CD Pipeline

1. Configure Stages of a CI/CD Pipeline.

2. Commit your changes to GitHub.


If you have added the new folder and file in the Business Application Studio, you can do so
by opening a new terminal from the new .pipeline folder and then by performing the
following steps:

You have configured your CI/CD pipeline. Finally, you will have to verify the success of your
build.

© Copyright. All rights reserved. 109


Unit 7
Solution 15
Configure the Stages of a CI/CD Pipeline

Business Scenario
You have connected your SAP Continuous Integration and Delivery service to your GitHub
repository and have created a job that is going to take care of automated build and
deployment. Now the job needs to know what steps it needs to perform. The definition of
steps that need to be performed is done using a so-called pipeline. The configuration syntax
of the pipeline that you are going to configure is based on SAP's Open-Source Project Piper 1.
The pipeline configuration is done within your project.

Task Flow
In this exercise, you will configure stages of a project "Piper" pipeline.

Prerequisite
You have enabled your application for CI/CD.

Configure Stages of a CI/CD Pipeline

1. Configure Stages of a CI/CD Pipeline.


a) In the GitHub repository of your project (or in SAP Business Application Studio),
execute the following command in a terminal session: cds add pipeline

b) Navigate into the .pipeline folder and open the config.yml file, and replace everything
with the following configuration:
###
# This file configures the project "Piper" pipeline of your project.
# For a reference of the configuration concept and available options,
please have a look into its documentation.
#
# The documentation for the most recent pipeline version can always be
found at:
# https://sap.github.io/jenkins-library/
#
# This is a YAML-file. YAML is an indentation-sensitive file format.
Please make sure to properly indent changes to it.
###

### General project setup


---
general:
pipeline: "sap-cloud-sdk"
buildTool: "mta"
stages:
Build:
mavenExecuteStaticCodeChecks: false
npmExecuteLint: false
Additional Unit Tests:
npmExecuteScripts: false

© Copyright. All rights reserved. 110


Solution 15: Configure the Stages of a CI/CD Pipeline

karmaExecuteTests: false
Release:
cloudFoundryDeploy: true
tmsUpload: false
steps:
cloudFoundryDeploy:
cloudFoundry:
apiEndpoint: "https://api.cf.eu10.hana.ondemand.com"
org: "myOrg"
space: "mySpace"
credentialsId: "cfdeploy"
appName: ""
mtaDeployParameters: "-f --version-rule ALL"
artifactPrepareVersion:
versioningType: "cloud_noTag"

c) Replace the placeholders "myOrg", "mySpace" and "apiEndpoint" with the values of
the space in the SAP BTP, Cloud Foundry environment to which you want to
deploy.credentialsId is the name of the credential you have created in the CI/CD
Service for the SAP BTP access. In previous parts, you named it cfdeploy.
You can get the values for myOrg, mySpace, and apiEndpoint from your subaccount
overview in the SAP BTP cockpit:

Or just run command CF TARGET in the Terminal in SAP Business Application Studio.
Use the values to replace the placeholders as described above.

2. Commit your changes to GitHub.


If you have added the new folder and file in the Business Application Studio, you can do so
by opening a new terminal from the new .pipeline folder and then by performing the
following steps:
a) Navigate into the .pipeline directory:
Use the command: cd .pipeline

b) Add all recent changes into the git staging area:


Use the command: git add -A

c) Create a new commit with the staged changes and push it to the remote repository:

git commit -m "new pipeline"


git push

You have configured your CI/CD pipeline. Finally, you will have to verify the success of your
build.

© Copyright. All rights reserved. 111


Unit 7
Exercise 16
Verify Build Success

Business Scenario
After configuring a job and a pipeline for Continuous Integration and Delivery, you want to
ensure, that the automated build and deployment of your project succeeds.

Task Flow
In this exercise, you will perform the following task:
● Start monitoring a job in SAP Continuous Integration and Delivery.

Prerequisite
You have set up an SAP Continuous Integration and Delivery pipeline.

Start Monitoring a Job in SAP Continuous Integration and Delivery

1. Monitor the Outcome.


After completing these steps, you will have monitored the outcome of your job in SAP
Continuous Integration and Delivery.

You did it!

© Copyright. All rights reserved. 112


Unit 7
Solution 16
Verify Build Success

Business Scenario
After configuring a job and a pipeline for Continuous Integration and Delivery, you want to
ensure, that the automated build and deployment of your project succeeds.

Task Flow
In this exercise, you will perform the following task:
● Start monitoring a job in SAP Continuous Integration and Delivery.

Prerequisite
You have set up an SAP Continuous Integration and Delivery pipeline.

Start Monitoring a Job in SAP Continuous Integration and Delivery

1. Monitor the Outcome.


After completing these steps, you will have monitored the outcome of your job in SAP
Continuous Integration and Delivery.
a) In the Jobs tab in SAP Continuous Integration and Delivery, select your job and verify
that a new tile appears in the Builds view. This tile should be marked as running.

Note:
If no new tile appears, trigger the job manually by choosing the Trigger Build
button.

© Copyright. All rights reserved. 113


Unit 7: Automated Deployment

b) Wait until the job has finished and verify that the build tile is marked as successful.

You did it!

© Copyright. All rights reserved. 114


Unit 9
Exercise 17
Case Study: Create an Application for the
Orders of a Retail Store

Business Scenario
The business you are working in is a retail business for sweets and toys. The worst-case
scenario for your company's business would be if they have no goods to sell. Many products
are ordered by your company on demand and Just-in-Time (JIT).
However, there is no big warehouse to store the goods in any branch. Knowing which order,
together with which products, has which status is important for each store. This information
is essential to keep the business running smoothly. Currently, all branch managers receive an
email every day with the status of the purchase orders.
You are asked by your manager to build an application that shows the order data. This
application should be able to be used by the store managers directly. The requirements
engineering team has already created the necessary system proposal and the data and entity
structures. Your task now is to develop a full-stack web application that displays the data for
the shops. Making your work on this task a little easier, your supervisor provides you with
some helpful hints as a starting point for you.

Required Information
Your colleagues created an ERM diagram for you. Based on that, you need to design the back
end of your application where the data will be stored.

Figure 1: ERM Diagram of the Use Case

Your manager heard about software development from SAP based on the SAP BTP and he
can remember that you had a training about the SAP Extension Suite not too long ago. You
have the task to build the application based on SAP CAP for the back end and SAP Fiori
Elements for the front end. For the back end he provides you some demo data in CSV files
which you can use to implement and test your application.

© Copyright. All rights reserved. 115


Unit 9: Case Study (ILT Only)

For the front end of the application, he specifies the following navigation flow:

Figure 2: Specified Navigation Flow of the Application Front End

On open, the application should start in the “Vendor Screen”. In this screen, all vendors where
our company order goods should be displayed. When you click on one specific vendor you
should get into the “Orders Screen” where you get a list of all orders our company made at
this vendor. By clicking on one specific order, you should get into the “Order Item Screen”
where you can see which items are part of the order. Look at the diagram above to get
information which data should be displayed inside the UI.
To develop this application, you should use capabilities from the SAP Business Technology
Platform.
Use the SAP Business Application Studio for your coding and when your coding is finished,
you should deploy the application to a cloud foundry environment of the SAP BTP. In addition
to that, your manager heard about the autoscaling service inside of SAP BTP. He asked if you
could also implement the autoscaling service if you still got time during the development.

Note:
Have in mind that the use case of this case study is simplified at some points and
functionalities may not exist caused by the required time. The application built in
this case study cannot handle multiple stores, you cannot create, change, or
cancel orders and there is no live data connection for this application. Of course,
depending on a real-life scenario, you can use this project as a starting point. But
for now – this project is only to learn the concepts of SAP CAP and the SAP BTP.
In case of troubles while developing the application or if you want to get an idea as
a starting point, you can ask your trainer for help.
All knowledge you gathered in this training is usable for this exercise. In addition:
You can, of course, use the internet and the official CAP documentation or any
other sample projects.

Task 1: Open the Template for the Case Study

1. Switch to the case_study branch by entering the following command in a new terminal
session:
git checkout case_study
You can find the entire repository at the following URL: https://github.com/SAP-
samples/extension-suite-learning-journey

Task 2: Create the SAP CAP Back End

1. Create a new CAP back end based on the business scenario.

© Copyright. All rights reserved. 116


Exercise 17: Case Study: Create an Application for the Orders of a Retail Store

Task 3: Test the SAP CAP Back End

1. Test your CAP back end that it works properly and as expected.

Task 4: Create the SAP Fiori Elements Front End

1. When you finished the development of the CAP back end, create a Fiori Elements front
end application.

Task 5: Test the SAP Fiori Elements Front End

1. Test your Fiori Elements front end application that it works properly and as expected.

Task 6: Deploy Your Application to the SAP BTP

1. Deploy your application to your BTP account as you learned in the training.

2. Test your deployed application.

Task 7: optional: Implement the Autoscaling Service

1. Create service instance.

2. Create the autoscaling configuration and bind it to your application.

Note:
Use the following metrics:
● Memoryused
● Threshold: 64 for decrease
● Threshold: 128 for increase
● Min. instance: 1
● Max instance: 2

You can refer to the documentation of the autoscaling service: https://


help.sap.com/doc/04f1b7f065bd4baeb63094be22a66c41/Cloud/en-US/autoscaler.pdf
Finished. Your application now scales automatically based on the memory usage. When
your application requires more than 128 MB of memory, a new instance is created and
when your application requires less than 64 MB of memory, the instances get decreased.
The threshold amount is just as an example – real numbers need to be declared based on
the usage of the application and the application type.

© Copyright. All rights reserved. 117


Unit 9
Solution 17
Case Study: Create an Application for the
Orders of a Retail Store

Business Scenario
The business you are working in is a retail business for sweets and toys. The worst-case
scenario for your company's business would be if they have no goods to sell. Many products
are ordered by your company on demand and Just-in-Time (JIT).
However, there is no big warehouse to store the goods in any branch. Knowing which order,
together with which products, has which status is important for each store. This information
is essential to keep the business running smoothly. Currently, all branch managers receive an
email every day with the status of the purchase orders.
You are asked by your manager to build an application that shows the order data. This
application should be able to be used by the store managers directly. The requirements
engineering team has already created the necessary system proposal and the data and entity
structures. Your task now is to develop a full-stack web application that displays the data for
the shops. Making your work on this task a little easier, your supervisor provides you with
some helpful hints as a starting point for you.

Required Information
Your colleagues created an ERM diagram for you. Based on that, you need to design the back
end of your application where the data will be stored.

Figure 1: ERM Diagram of the Use Case

Your manager heard about software development from SAP based on the SAP BTP and he
can remember that you had a training about the SAP Extension Suite not too long ago. You
have the task to build the application based on SAP CAP for the back end and SAP Fiori
Elements for the front end. For the back end he provides you some demo data in CSV files
which you can use to implement and test your application.

© Copyright. All rights reserved. 118


Solution 17: Case Study: Create an Application for the Orders of a Retail Store

For the front end of the application, he specifies the following navigation flow:

Figure 2: Specified Navigation Flow of the Application Front End

On open, the application should start in the “Vendor Screen”. In this screen, all vendors where
our company order goods should be displayed. When you click on one specific vendor you
should get into the “Orders Screen” where you get a list of all orders our company made at
this vendor. By clicking on one specific order, you should get into the “Order Item Screen”
where you can see which items are part of the order. Look at the diagram above to get
information which data should be displayed inside the UI.
To develop this application, you should use capabilities from the SAP Business Technology
Platform.
Use the SAP Business Application Studio for your coding and when your coding is finished,
you should deploy the application to a cloud foundry environment of the SAP BTP. In addition
to that, your manager heard about the autoscaling service inside of SAP BTP. He asked if you
could also implement the autoscaling service if you still got time during the development.

Note:
Have in mind that the use case of this case study is simplified at some points and
functionalities may not exist caused by the required time. The application built in
this case study cannot handle multiple stores, you cannot create, change, or
cancel orders and there is no live data connection for this application. Of course,
depending on a real-life scenario, you can use this project as a starting point. But
for now – this project is only to learn the concepts of SAP CAP and the SAP BTP.
In case of troubles while developing the application or if you want to get an idea as
a starting point, you can ask your trainer for help.
All knowledge you gathered in this training is usable for this exercise. In addition:
You can, of course, use the internet and the official CAP documentation or any
other sample projects.

Task 1: Open the Template for the Case Study

1. Switch to the case_study branch by entering the following command in a new terminal
session:
git checkout case_study
You can find the entire repository at the following URL: https://github.com/SAP-
samples/extension-suite-learning-journey

Task 2: Create the SAP CAP Back End

1. Create a new CAP back end based on the business scenario.

© Copyright. All rights reserved. 119


Unit 9: Case Study (ILT Only)

Task 3: Test the SAP CAP Back End

1. Test your CAP back end that it works properly and as expected.

Task 4: Create the SAP Fiori Elements Front End

1. When you finished the development of the CAP back end, create a Fiori Elements front
end application.

Task 5: Test the SAP Fiori Elements Front End

1. Test your Fiori Elements front end application that it works properly and as expected.

Task 6: Deploy Your Application to the SAP BTP

1. Deploy your application to your BTP account as you learned in the training.

2. Test your deployed application.

Task 7: optional: Implement the Autoscaling Service

1. Create service instance.

2. Create the autoscaling configuration and bind it to your application.

Note:
Use the following metrics:
● Memoryused
● Threshold: 64 for decrease
● Threshold: 128 for increase
● Min. instance: 1
● Max instance: 2

You can refer to the documentation of the autoscaling service: https://


help.sap.com/doc/04f1b7f065bd4baeb63094be22a66c41/Cloud/en-US/autoscaler.pdf
Finished. Your application now scales automatically based on the memory usage. When
your application requires more than 128 MB of memory, a new instance is created and
when your application requires less than 64 MB of memory, the instances get decreased.
The threshold amount is just as an example – real numbers need to be declared based on
the usage of the application and the application type.

© Copyright. All rights reserved. 120

You might also like