Welcome to CAP Samples for Java
Welcome to the bookshop-java project. It demonstrates how to build business applications using the CAP Java SDK providing a book shop web application as an example. The application in this project enables browsing books, managing books, and managing orders.
- Getting Started
- Clone Build & Run
- Using Eclipse
- Using IntelliJ Idea (Community and Ultimate)
- Database Setup and Spring Profiles
- API_BUSINESS_PARTNER Remote Service and Spring Profiles
- Deploy to SAP Business Technology Platform, Cloud Foundry
- Deploy to SAP Business Technology Platform, Kyma Runtime
- Setup Authorizations in SAP Business Technology Platform
- Code Tour
- Get Support
This sample application shows how to conveniently create business applications based on CDS domain models, persisting data with H2, or SAP HANA, and exposing an OData V4 frontend with an SAP Fiori frontend on top.
This sample uses Spring Boot as an application framework. Although a CAP Java application isn’t required to build on Spring Boot, it’s the first choice of framework, as it’s seamlessly integrated.
The domain models are defined using CDS entity definitions.
By default, an in-memory H2 database is used for data persistency. Once productively deployed to SAP Business Technology Platform, SAP HANA can be used.
Services are defined using CDS Service Models. The OData V4 Protocol Adapter translates the CDS service models into corresponding OData schemas and maps the incoming OData requests to the corresponding CDS services.
Although CAP provides generic event handlers to serve most CRUD requests out-of-the-box, it’s possible to add business logic through Custom Event Handlers.
A SAP Fiori UI is added using predefined SAP Fiori elements templates. SAP Fiori annotations add information to the service definitions, on how to render the data.
Framework and Infrastructure related Features:
- Application configuration for Spring and CDS using application.yaml
- Mocking users for local development
- Authentication & Authorization (including user-specific restrictions with
@restrictin the Admin Service)
- Cloud Foundry Deployment using MTA with XSUAA Service Bindings
- Application Router configuration including authentication via the XSUAA Service. See package.json, xs-app.json and xs-security.json
- Multitenancy configuration via mta-multi-tenant.yaml, .cdsrc.json, sidecar module
Domain Model related Features:
- CDS Query Language with a Static CDS Model in the Admin Service
- Use of Aspects in the Model Definition such as the
cuidAspect in Books
- Input validation using model annotation
- Data Localization for Books
- Use of Media Data in Books and AdminService
Service Model related Features:
- Custom event handlers such as the Custom business logic for the Admin Service
- Custom actions such as
addToOrderin the Admin Service. The Action implementation is in the Admin Service Event Handler
- Add annotations for searchable elements in the Admin Service
- Localized Messages in the Admin Service Event Handler
- role-based restrictions in AdminService and ReviewService
- Use of
- Media Data processing in the Admin Service Event Handler
User Interface related Features:
- Support for SAP Fiori Elements
- SAP Fiori Draft based Editing for Books, Orders and Reviews
- SAP Fiori annotations specific for Browse Books, Manage Books, Manage Orders, Manage Reviews and common annotations, which apply to all UI's
- UI Annotations for custom actions in the Browse Books and Manage Books UI, including annotations for a button and a popup
- Value Help for Books and Authors
- Model Localization for English and German language for static texts
- Custom File Upload extension which provides a button for uploading
- A simple Swagger UI for the CatalogService API at http://localhost:8080/swagger/index.html
CDS Maven Plugin Features:
- Install Node.js in the default version.
- Install the latest version of @sap/cds-dk.
- Execute arbitrary CDS commands.
- Generate Java POJOs for type-safe access to the CDS model.
- Clean project from artifacts of the previous build.
The following sections describe how to set up, build, and run the project.
Make sure you have set up a development environment (that means, you’ve installed the CDS Compiler, Java, and Apache Maven) as described here.
Clone Build & Run
- Clone the project:
git clone https://github.com/SAP-samples/cloud-cap-samples-java.git
- Build and run the application:
Optionally, use the following steps to import the project to Eclipse:
Import the project using File > Import > Existing Maven Projects.
Now, you should see the projects bookshop and bookshop-parent in the project/package explorer view.
In Project Explorer, change the property "Package Presentation" from "Flat" to "Hierarchical" for better understanding.
Building and Running
To compile the project, right-click the file
bookshop-parentproject root folder and select Run as > Maven build.
In the following dialog, enter the string
clean installinto the field labeled with "Goals" and click "Run".
Note: This step also compiles the CDS artifacts, thus repeat this once you made changes to the CDS model. This step also generates source files, therefore refresh the "bookshop" project in your IDE.
To run the application, right-click the
bookshopproject root in the Package Explorer and select Run as > Spring Boot App (make sure you have Spring Tools 4 installed).
This step creates a default Run Configuration named
Bookshop - Applicationand starts the application afterwards. To go on with the next step, stop the application again.
Then, set the default working directory by editing your Run Configuration via Run > Run Configurations > Bookshop - Application. On the tab Arguments change the default Working Directory to:
Afterwards, click Run. This step starts the applications
mainmethod located in
Use the following links in the browser to check if everything works fine:
http://localhost:8080/: This should show the automatically generated index page of served paths. http://localhost:8080/fiori.html: This is the actual bookshop application UI. http://localhost:8080/swagger/index.html: This is providing a Swagger UI for the CatalogService API.
You'll start with a predefined stock of books as this procedure starts the bookshop application with a CSV-initialized in-memory H2 database.
Two mock users are defined for local development:
userto browse books
adminto manage books and orders
Using IntelliJ Idea (Community and Ultimate)
IntelliJ can handle the project more or less out-of-the-box. Since some of the event handlers in the project rely on the code generated from the CDS model the build path of the project (module) needs to be extended with the folder containing the generated code. In order to add the generated code you need to add the 'gen' folder to the build path:
- Open the project settings.
- Navigate to the 'modules' section.
- Select the srv/src/gen folder and mark it as 'sources'.
- Save and leave the project settings.
- Trigger a rebuild.
After the generated code is considered by IntelliJ's build the application can be handled just as any other Spring Boot application in IntelliJ.
Database Setup and Spring Profiles
The application comes with two predefined profiles that determine how to run the application:
defaultprofile specifies to use an in-memory H2 database. The in-memory database is set up automatically during startup of the application and initialized with some example data from CSV files.
When deploying the application to Cloud Foundry, the CF Java Buildpack automatically configures the
cloudSpring profile. This profile doesn’t specify any datasource location. In that case CAP Java can automatically detect SAP HANA service bindings available in the environment.
API_BUSINESS_PARTNER Remote Service and Spring Profiles
The behavior of the API_BUSINESS_PARTNER remote service is controlled using profiles (see
Using mock data via internal service: When using only the
defaultprofile (default when omitting any profile setting), the API_BUSINESS_PARTNER API is mocked as a local service using the mock data.
Using mock data via internal service through OData: With the
mockedprofile, all requests to the API_BUSINESS_PARTNER service will be routed through HTTP and OData to itself (
http://localhost:<port>/api/API_BUSINESS_PARTNER/...). This mode is similar to using a real remote destination, and such helps to prevent issues from differences in local service and remote service behavior.
Using the sandbox environment: You can access data from the SAP API Business Hub sandbox with the
sandboxprofile. The API key needs to be provided with the environment variable
CDS_REMOTE_SERVICES_API_BUSINESS_PARTNER_DESTINATION_HEADERS_APIKEY. You can retrieve it by clicking on Show API Key on this page after logging in.
Using S/4HANA cloud or on-premise system: With the
destinationprofile, you can access data from a real S/4HANA system. You need to create a destination with name
s4-destinationand make sure that an instance of XSUAA and destination service are bound to your application. For an on-premise destination, you additionally need to bind the connectivity service and add an additional property
URL.headers.sap-clientwith the S/4HANA client number to your destination.
destination can be combined with the
default profile for hybrid testing and with the
cloud profile when deployed to the cloud.
Deploy to SAP Business Technology Platform, Cloud Foundry
CAP Java applications can be deployed to the SAP Business Technology Platform either in single tenant or in multitenancy mode. See Multitenancy in CAP Java for more information.
- Install the Cloud MTA Build Tool:
npm install -g mbt.
- Install the Cloud Foundry Command Line Interface.
- Get an SAP Business Technology Platform account to deploy the services and applications.
- Create a SAP HANA Cloud Instance in your SAP Business Technology Platform space.
- Ensure you have an entitlement for
SAP HANA Schemas & HDI Containerswith plan
hdi-sharedin the same space.
Deploy as Single Tenant Application:
cf deploy mta_archives/bookshop_1.0.0.mtar
Deploy as Multitenant Application:
cf deploy mta_archives/bookshop-mt_1.0.0.mtar
- Go to another subaccount in your global account, under subscriptions and subscribe to the application you deployed.
cf map-route bookshop-mt-app <YOUR DOMAIN> --hostname <SUBSCRIBER TENANT>-<ORG>-<SPACE>-bookshop-mt-appor create and bind the route manually.
Before you can access the UI using the (tenant-specific) URL to the bookshop(-mt)-app application, make sure to Setup Authorizations in SAP Business Technology Platform.
Deploy to SAP Business Technology Platform, Kyma Runtime
TIP: You can find more information in the Deploy Your CAP Application on SAP BTP Kyma Runtime tutorial and in the Deploy to Kyma/K8s guide of the CAP documentation.
- BTP Subaccount with Kyma Runtime
- BTP Subaccount with Cloud Foundry Space
- HANA Cloud instance available for your Cloud Foundry space
- BTP Entitlements for: HANA HDI Services & Container plan hdi-shared, Launchpad Service plan standard
- Container Registry (e.g. Docker Hub)
- Command Line Tools:
- Logged into Kyma Runtime (with
kubectlCLI), Cloud Foundry space (with
cfCLI) and Container Registry (with
Add Deployment Files
CAP tooling provides your a Helm chart for deployment to Kyma.
Add the CAP Helm chart with the required features to this project:
cds add helm:hana_deployer cds add helm:xsuaa cds add helm:html5_apps_deployer
Helm chart configuration
This project contains a pre-configured configuration file
values.yaml, you just need to do the following changes in this file:
<your-container-registry>- full-qualified hostname of your container registry
domain- full-qualified domain name used to access applications in your Kyma cluster
Use API_BUSSINESS_PARTNER Remote Service (optional)
You can try the
API_BUSINESS_PARTNER service with a real S/4HANA system with the following configuration:
Create either an on-premise or cloud destination in your subaccount.
Add the binding to the destination service for the service (
srv) to the
srv: ... bindings: ... destinations: serviceInstanceName: destinations
(The destination service instance is already configured)
Set the profiles
destinationactive in your
srv: ... env: SPRING_PROFILES_ACTIVE: cloud,destination # TODO: To be removed after @sap/cds-dk patch CDS_ENVIRONMENT_K8S_SERVICEBINDINGS_CONNECTIVITY_SECRETSPATH: '/bindings/connectivity' CDS_ENVIRONMENT_K8S_SERVICEBINDINGS_CONNECTIVITY_SERVICE: 'connectivity'
For on-premise only: Add the connectivity service to your Helm chart:
cds add helm:connectivity
Prepare Kubernetes Namespace
Create container registry secret
Create a secret
container-registry with credentials to access the container registry:
The Docker Server is the full qualified hostname of your container registry.
Create a HDI container and a secret
bash ./scripts/create-db-secret.sh bookshop-db
It will create a HDI container
bookshop-db on your currently targeted Cloud Foundry space and creates a secret
bookshop-db with the HDI container's credentials in your current Kubernetes namespace.
Build data base deployer image:
cds build --production pack build $YOUR_CONTAINER_REGISTRY/bookshop-hana-deployer \ --path db \ --buildpack gcr.io/paketo-buildpacks/nodejs \ --builder paketobuildpacks/builder:base
$YOUR_CONTAINER_REGISTRY with the full-qualified hostname of your container registry)
Build image for CAP service:
pack build $YOUR_CONTAINER_REGISTRY/bookshop-srv \ --path srv/target/*-exec.jar \ --buildpack gcr.io/paketo-buildpacks/sap-machine \ --buildpack gcr.io/paketo-buildpacks/java \ --builder paketobuildpacks/builder:base \ --env SPRING_PROFILES_ACTIVE=cloud
Build HTML5 application deployer image:
Push container images
You can push all the container images to your container registry, using:
docker push $YOUR_CONTAINER_REGISTRY/bookshop-hana-deployer docker push $YOUR_CONTAINER_REGISTRY/bookshop-srv docker push $YOUR_CONTAINER_REGISTRY/bookshop-html5-deployer
helm upgrade bookshop ./chart --install -f values.yaml
Access the UI
Before you can access the UI you should make sure to Setup Authorizations in SAP Business Technology Platform.
- Create a Launchpad Service subscription in the BTP Cockpit
- Go to HTML5 Applications
- Start any of the HTML5 applications
Additionally, you can add the UIs to a Launchpad Service site like it is described in in the last two steps of this tutorial.
Setup Authorizations in SAP Business Technology Platform
To access services and UIs that require specific authorizations (e.g.
admin) you need to assign a corresponding role and role collections to your user in SAP BTP Cockpit.
- For single-tenant applications open the subaccount where you deployed the
bookshopapplication to. For multitenant applications open the subaccount where you subscribed to the
- Navigate to Security -> Roles
- Create a role with name
bookshop-adminbased on the
adminrole template of the
- Enter a Business Partner ID of your S/4 system as value for the
businessPartnerattribute. When using the sandbox environment use
- Enter a Business Partner ID of your S/4 system as value for the
- Navigate to Security -> Role Collections
- Create a new role collection
- Assign the
bookshop-adminrole to this role collection
- Assign the role collection to your user
- Assign the
Copyright (c) 2022 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, version 2.0 except as noted otherwise in the LICENSE file.