Interceptors in SAP Commerce

What are Interceptors:-

We need to use interceptors whenever we want to perform some action during a model’s life cycle.
Example: If we need to validate the model data before saving it in the database.

We can see the main use of interceptors in some scenarios as mentioned below

  1. Auditing the details while saving the model data.
    2. Validating the model data before saving.
    3. Restrict data from deleting or modifying based on some conditions.

We can even modify the model before saving it using interceptors.

Why do we need interceptors?

The interceptors can interrupt a model’s lifecycle, execute some code, and then allow the model to continue its lifecycle.

Types of interceptors in Hybris:-

There are 5 main interceptors provided by Hybris

1) Init Defaults interceptor
2) Prepare interceptor
3) Validate interceptor
4) Load interceptor
5) Remove interceptor

1) Init Defaults interceptor: –

This interceptor is represented by an interface called “InitDefaultsInterceptor”.

This is called when a model needs to be filled with its default values.

This will be called automatically when the modelService.create method is called or when the modelService.initDefaults method is called.

We can use this interceptor to fill the model with additional default values, apart from the values defined in the items.xml file.

2) Prepare interceptor:-

 This interceptor is represented by an interface called PrepareInterceptor”.

This is called before a model is saved to the database and before it is validated by Validate interceptors.

We can use this to add values to the model or modify existing ones before they are saved.

If any exception is raised during execution, the Model will not be saved.

Example: –

In the AddressModel we have firstName and lastName should start with the first letter as capital.

Steps for creating the PrepareInterceptor

Step1: Create a PrepareInterceptor in core extension

package com.hybris.clavrit.core.interceptor;

import de.hybris.platform.core.model.user.AddressModel;
import de.hybris.platform.core.model.user.CustomerModel;
import de.hybris.platform.core.model.user.UserModel;
import de.hybris.platform.servicelayer.interceptor.InterceptorContext;
import de.hybris.platform.servicelayer.interceptor.InterceptorException;
import de.hybris.platform.servicelayer.interceptor.PrepareInterceptor;
import org.apache.commons.lang.StringUtils;

public class FullNameFormatInterceptor implements PrepareInterceptor<AddressModel> {
    @Override
    public void onPrepare(AddressModel addressModel, InterceptorContext interceptorContext) throws InterceptorException {
        if (StringUtils.isNotBlank(addressModel.getFirstname())) {
            addressModel.setFirstname(capitalizeFirstLetter(addressModel.getFirstname()));
        }
        if (StringUtils.isNotBlank(addressModel.getLastname())) {
            addressModel.setLastname(capitalizeFirstLetter(addressModel.getLastname()));
        }
    }
    private String capitalizeFirstLetter(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }
}

Step 2: Add the step1 entry in *core-spring.xml file

<bean id="fullNameFormatInterceptor" class="com.hybris.clavrit.core.interceptor.FullNameFormatInterceptor">
</bean>

<bean id="fullNameFormatInterceptorMapping"
      class="de.hybris.platform.servicelayer.interceptor.impl.InterceptorMapping">
    <property name="interceptor" ref="fullNameFormatInterceptor"/>
    <property name="typeCode" value="Address"/>
</bean>

Step 3: Go to BackofficeTypes->type Address and click on search
1In the above image click on red color highlighted symbol we can see the list of addresses will be displayed.
2
In the above image click on red color highlighted symbol to create new address.

3
4
After adding the above details (here we can observe that First Name and Last Name the first letter of the word starts with small letter) click on finish and you can see the output.
5

3) Validate interceptor:-

 

This interceptor is represented by an interface called ValidateInterceptor

This is called before a model is saved to the database after is been prepared by the Prepare interceptors.

We can use this interceptor to validate values of the model and raise an InterceptorException if any values are not valid.

Example:

In email id we have @ and . Symbol we need to validate whether the email id contains @ and . Symbol

Steps for creating the ValidateInterceptor:-

Step1: Create a ValidateInterceptor in core extension.

package com.hybris.clavrit.core.interceptor;

import de.hybris.platform.core.model.user.CustomerModel;
import de.hybris.platform.servicelayer.interceptor.InterceptorContext;
import de.hybris.platform.servicelayer.interceptor.InterceptorException;
import de.hybris.platform.servicelayer.interceptor.ValidateInterceptor;
import org.apache.commons.lang.StringUtils;

public class EmailValidationInterceptor implements ValidateInterceptor<CustomerModel> {
    private static final String EMAIL_REGEX = "^[\\w.-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$";
    @Override
    public void onValidate(CustomerModel customerModel, InterceptorContext context) throws InterceptorException {
        String email = customerModel.getCustomerID();
        if (StringUtils.isNotBlank(email) && !email.matches(EMAIL_REGEX)) {
            throw new InterceptorException("Invalid email format");
        }
    }
}

Step 2: Add the step1 entry in *core-spring.xml file

<bean id="emailValidationInterceptor" class="com.hybris.clavrit.core.interceptor.EmailValidationInterceptor"/>

<bean id="emailValidationInterceptorMapping"
      class="de.hybris.platform.servicelayer.interceptor.impl.InterceptorMapping">
    <property name="interceptor" ref="emailValidationInterceptor"/>
    <property name="typeCode" value="Customer"/>
</bean>

Step 3: Go to BackofficeTypes->type Customers and click on search
6
In the above image click on red color highlighted symbol to see the list of customers. Scenario 1: if we are passing the invalid customerID then that customer is not created in Database.
7
In the above image click on the red color highlighted symbol to create the new customer.
8
After filling all values click on the finish button. If we observe that we are giving the customerID is invalid so it will give the output is “Invalid email format
Scenario 2: if we are passing the valid customerID then that customer is created in Database.
9
After filling all values click on the finish button. If we observe that we are giving the customerID is valid so the new customer will be created in the Database.
10

4) Load interceptor:-

 

This interceptor is represented by an interface called LoadInterceptor

This is called when we retrieve the model from the database.

We can use load interceptor if we want to change the values of the model after loading it.

If any exception raised during execution, Model will not be loaded.

5) Remove interceptor:-

 

This interceptor is represented by an interface called RemoveInterceptor

This is called before a model is removed/deleted from the database.

We can use remove interceptor whenever we need to remove models that are related to the model but are not in the model context.

We can also use to prevent the removal/deletion of the model if it’s always required

 




Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top