SAP Home Learn Build Integrate Model Operate Extend with AI ConnectTutorial navigator Knowledge Graph API Devtoberfest Developer Advocates App Space

Manage my Account SAP Devs YouTube ↗ Learnings ↗ Community ↗ Provide Feedback ↗
Logout
⤢ Open full site

Add a Custom Event Handler

Write your first CAP Java Custom Event Handler.

Overview

🎓 beginner 10 min. SAP Cloud Application Programming ModelBeginnerSAP Business Technology PlatformJava

You will learn

  • How to write a custom event handler for CAP Java
  • Which event handler classes and methods are available
René Jeglinsky R René Jeglinsky December 10, 2024
Created by December 10, 2024
Contributors

Prerequisites

Steps

Intro

In the following tutorials, you will learn that the CAP Java runtime can handle all CRUD events (create, read, update, and delete) triggered by OData requests out of the box. For now, we’ll show you how to do this manually, so that you can see how to write a custom event handler to extend the event handling process.


Step 1 Create Java class for custom event handler

  1. Create the Java package, by creating a new folder called handlers under srv/src/main/java/customer /products_service.

    package for Custom Event Handlers
    package for Custom Event Handlers

  2. Create the Java class file AdminService.java in the created handlers folder, with the following content and make sure you Save the file:

Java
package customer.products_service.handlers;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.sap.cds.services.cds.CdsCreateEventContext;
import com.sap.cds.services.cds.CdsReadEventContext;
import com.sap.cds.services.cds.CqnService;
import com.sap.cds.services.handler.EventHandler;
import com.sap.cds.services.handler.annotations.On;
import com.sap.cds.services.handler.annotations.ServiceName;

@Component
@ServiceName("AdminService")
public class AdminService implements EventHandler {

    private Map<Object, Map<String, Object>> products = new HashMap<>();

    @On(event = CqnService.EVENT_CREATE, entity = "AdminService.Products")
    public void onCreate(CdsCreateEventContext context) {
        context.getCqn().entries().forEach(e -> products.put(e.get("ID"), e));
        context.setResult(context.getCqn().entries());
    }

    @On(event = CqnService.EVENT_READ, entity = "AdminService.Products")
    public void onRead(CdsReadEventContext context) {
        context.setResult(products.values());
    }

}

This class now handles the READ and CREATE events that target the Products entity of the AdminService.

  • The READ operation just returns all entities kept in memory.

  • The CREATE event extracts the payload from the CQN representation and stores it in memory.

CDS Query Notation (CQN) is the common language in CAP to run queries against services. It can be used to talk to the services defined by your model, but also remote services, such as the database.

The event handler uses the following APIs, which are available for service providers in CAP Java:

  • Event handler classes have to implement the marker interface EventHandler and register themselves as Spring Beans (@Component). The marker interface is important, because it enables the CAP Java runtime to identify these classes among all Spring Beans.
  • You register your Event Handler Methods with @Before, @On, or @After annotations. Every event, such as an entity creation, runs through these three phases. Each phase has a slightly different semantic. You will learn more about these semantics in the subsequent tutorial.
  • The annotation @ServiceName specifies the default service name all event handler methods apply to. Here this is AdminService, as this was also the name when defining the service in the CDS model.
  • Event handler methods get an event-specific event context parameter, which provides access to the input parameters of the event and the ability to set the result. For example, let’s look at the CdsCreateEventContext context parameter. The event we’re extending is the CREATE event. The type of the context variable is specific to this extended CREATE event. The onCreate method returns void, as the result is set by running: context.setResult(…).
Step 2 Stop the application
+
Step 3 Restart the application
+
Step 4 Insert data through HTTP request
+
Step 5 Read data using the Products entity page
+

Resources

Discussion

Share feedback on this tutorial or join the conversation in SAP Community.

Submit detailed feedback Discuss in Community
Steps
Step 1 of 5
1. Create Java class for custom event handler 2. Stop the application 3. Restart the application 4. Insert data through HTTP request 5. Read data using the Products entity page

Learn more →