How to create data transfer object(DTO), Converter and populator, Facade?

In this blog, we will explain the process of creating a data transfer object(DTO), Converter and populator, facade. We will show you the process of calling facade from the controller class and defining spring bean and its properties. We will create one model attribute and populate it. We will modify the UI by making a change in the tag file.

We take one example and this example explains how to show cart subtotal without taxes. Remember that there are many other ways by which we can show cart subtotal without taxes but we took the following approach to explain the above points.

Show cart subtotal without taxes/How to show cart subtotal without taxes?

Currently in SAP Hybris Commerce Accelerator when we add products to the cart then it shows cart subtotal with taxes. You can observe this in below image where we added one product to the cart in the apparel storefront that shows cart subtotal with taxes.

cart subtotal with taxes

Now here our goal is to show cart subtotal without including taxes. To achieve this goal we do not make any changes in OOB(out of the box) files but we use them from our created custom files to achieve this goal. We need to follow the following steps to achieve this goal.

  1. Create data transfer object(DTO)
  2. Create converter and populator
  3. Create facade and populate the data
  4. Call the facade from CartPageController/ Modify CartPageController
  5. Modify the cartTotal.tag file

1. Create data transfer object(DTO)

Now we will create one DTO(data transfer object) class named as SubTotalWithOutTax and it contains one property called as a sub of PriceData type. This sub property will hold the value of order subtotal without taxes.

Steps to create SubTotalWithOutTax DTO class

  1. Navigate to yacceleratorfacades->resources and open yacceleratorfacades-beans.xml.
  2. Add the following lines of code to yacceleratorfacades-beans.xml file.
    SubTotalWithOutTax DTO class
    Note: This entry must be between <beans> </beans> tag.
  3. Build the hybris system by running ant clean all.
    After successful build we can check our SubTotalWithOutTax DTO(data transfer object) class at the specified package and the file will look like this.

    SubTotalWithOutTax.java
    SubTotalWithOutTax.java

     

2. Create converter and populator

Before learning how to create converter and populator we need to know why we need converters and populators?

Now we will create a converter and populator for our SubTotalWithOutTax DTO(data transfer object) class. We need to follow the following steps to create a converter and populator.

  1. Now we create SubTotalWithOutTaxPopulator to fill the data in SubTotalWithOutTax DTO(data transfer object) class as you can see in the below image. SubTotalWithOutTaxPopulator implements the Populator interface.
    SubTotalWithOutTaxPopulator.java
    SubTotalWithOutTaxPopulator.java

     

  2. Navigate to yacceleratorfacades->resources and open yacceleratorfacades-spring.xml. Now we define a spring bean for the new SubTotalWithOutTaxPopulator and SubTotalWithOutTaxConverter as shown in below image.
    yacceleratorfacades-spring.xml
    yacceleratorfacades-spring.xml

     

  3. Build the hybris system by running ant clean all.

3. Create facade and populate the data

Generally, facade classes are created to call the services and to fill the data in DTO(data transfer object) class using converters and populators.

In our case, we create one DefaultBitbyteCartFacade class that implements BitbyteCartFacade interface. Through this class, we make a call to CartService and populate the data in SubTotalWithOutTax DTO class using converter and populator.

We need to follow the following steps to create BitbyteCartFacade

  1. Navigate to yacceleratorfacades->src and create an interface named as BitbyteCartFacade. as you can see in the below image

    BitbyteCartFacade.java
    BitbyteCartFacade.java
  2. Now we provide the implementation for the BibyteCartFacade interface in DefaultBitbyteCartFacade class.

    DefaultBitbyteCartFacade.java
    DefaultBitbyteCartFacade.java
  3. Navigate to yacceleratorfacades/resources and open yacceleratorfacades-spring.xml. Now we define a spring bean for the new DefaultBitbyteCartFacade as shown in below image.

    Spring Bean for Facade
    yacceleratorfacades-spring.xml
  4. Build the hybris system by running ant clean all.

4. Call the facade from CartPageController/Modify CartPageController

CartPageController is permitted to use annotation-based declaration so we inject BitbyteCartFacade as shown below in CartPageController.

BitbyteCartFacade bean Injection
CartPageController.java

Now add following lines of code inside prepareDataForPage method

Setting Model Attribute
CartPageController.java

Build the hybris system by running ant clean all.

5. Modify the cartTotal.tag file

Navigate to yacceleratorstorefront->web->webroot->WEB-INF->tags->cart and open cartTotal.tag file.

Replace the following lines of code with line number 14 and 15 to this file as shown in the image.

cartTotals.tag
cartTotals.tag

After saving this file, refresh apparel storefront and you can clearly observe that subtotal of the cart does not include taxes.

Cart Subtotal Without Taxes

Interceptor in SAP Hybris Commerce

Interceptor

An interceptor addresses a particular step in the life cycle of a model. When the life cycle reaches a certain step, you can activate a corresponding interceptor. An interceptor can modify the model, raise an exception to interrupt the current step or publish an event if the model matches certain criteria. For example, you could check that an attribute contains certain values before saving the model.

In easy words, we can say that anything that intercepts something else is called an interceptor. We can take one example to explain interceptor concept in a real-life scenario. We take one example where a person wants to watch a movie in the cinema hall. Now we will see how an interceptor is used in this scenario.

Interceptor Example

In the above diagram, we can see that one person went to the cinema hall and his journey intercepted at the ticket checking counter. Here Diamond(Has ticket) works as an interceptor. If a person has a ticket then he is permitted to watch a movie. If he doesn’t have a ticket then he is redirected to buy a ticket at the ticket counter.

What is the model’s life cycle?

This question is asked in hybris interviews. Here I am trying to explain this so it can help you in cracking hybris interview.

A model represents a state in the database. The representation is not live, that means that modified model values are not written to the database automatically. Instead, when you modify a model, you must explicitly save it to the database to have its state reflected there.

Model Life cycle
Model Life Cycle

Phases in the Model’s life cycle

There are four phases in the model’s life cycle.

  1. Instantiating the model
  2. Modifying model values
  3. Saving Model Values
  4. Removing the model

 

1. Instantiating the model

This can be done by either creating a new Model instance or by loading a Model from the database.

  1. Creating a model instance:- Visit link Model service create method vs new operator.
  2. Loading an existing model from the database is possible either by using pk or by using a query expression.
    Example:- UserModel user = modelService.get(pk);    [loading using primary key]

2. Modifying model values

We can modify the properties of the model if required.

3. Saving model values

If a model is created or modified. We save back the model to update the database. If we have used a new model, a new record is inserted/created in the database, otherwise, the existing record is updated.

4. Removing the model

If the model is no longer needed, the database record is deleted.

We can use interceptors to hook into the model’s life cycle.

Types of interceptors

  1. Load interceptor

    The load interceptor is called whenever a model is loaded from the database. You may want to use this interceptor if you want to change the values of the model after load. An exception raised during execution prevents the model from being loaded. To use this interceptor we must implement LoadInterceptor interface.

  2. InitDefaults Interceptor

    The InitDefaults interceptor is called when a model is filled with its default values. This happens either when it is created via the modelService.create method or when the modelService.initDefaults method is called. You can use this interceptor to fill the model with additional default values defined in the items.xml. To use this interceptor we must implement InitDefaultsInterceptor interface.

  3. Prepare interceptor

    The Prepare interceptor is called before a model is saved to the database before it is validated by Validate interceptors. Use this to add values to the model or modify existing ones before they are saved. An exception is raised during execution prevents the model from being saved. Prepare interceptor is called before the Impex translators. To use this interceptor we must implement PrepareInterceptor.

  4.  Validate interceptor

    The Validate interceptor is called before a model is saved to the database after is been prepared by the Prepare interceptors. We can use Validate interceptor to validate values of the model and raise an InterceptorException if any values are not valid. To use this interceptor we must implement ValidateInterceptor.

  5.  Remove Interceptor

    The Remove interceptor is called before a model is removed from the database. We can use this interceptor to prevent the removal of the model by raising an InterceptorException. To use this interceptor we must implement RemoveInterceptor.

How to register an interceptor?

After implementing an interceptor, we need to register it as a spring bean. The steps involved in registering an interceptor as followed:-

  1. Navigate to  customExtension->resources and open customExtension-spring.xml. Add the following line of code to this file.
    Custom Interceptor Bean
  2. In this step, we will do Interceptor mapping as shown in below image.
    Interceptor Mapping

Backoffice Customization

What is Backoffice Framework?

Backoffice Framework is new SAP Hybris Backoffice Framework designed to facilitate the creation of business tools and user interfaces in an easy and consistent way. It is shipped with SAP Hybris Commerce in the backoffice extension. It makes it possible to create a variety of components that can be reused later on in all kinds of applications. These components are standalone and deployable widgets can be easily modified without touching the code base.

In this tutorial, we will show you, how to create a custom widget using the Backoffice Framework. Our custom widget will have one input and one submit button. Suppose we enter some input and press the button, If the entered value is an integer then one pop up appears and it contains a message that Input value is an integer otherwise it will display an error that entered input is not an integer.

Steps to create a custom widget

  1. Create a custom  backoffice extension

  2. Create a widget definition

  3. Creating a widget view

  4. Create a service for widget/Use existing service for a widget

  5. Create a controller for the widget

  6. Build and start the server

  7. Deploy the widget

1. Create a custom  backoffice extension

Here we will create one custom backoffice extension named hybrisdiary using the BackOffice template extension. In this custom backoffice extension (hybrisdiary) we can create our custom widgets. To create custom backoffice extension(hybrisdiary) follow the following steps:-

  1. Open the command prompt and navigate to  <%HYBRIS_HOME_DIR%>/hybris/bin/platform directory and run the setantenv.bat file as shown in below image.setantenv.bat
  2. Now run ant extgen command.ant extgen
    Extgen prompts you to specify values for the technical aspects of an extension. Extgen comes with default values for all these technical aspects.
    These default values are defined in the project.properties file in the extgen directory. The default value is displayed in brackets ([ and ])
  3. Now we enter ybackoffice as shown in below image.ybackoffice
  4. Now enter extension name hybrisdiary as shown in below image.
    hybrisdiary custom backoffice name
  5. Now enter the package name(de.hybris.hybridiary) as shown in below  image
    package name
  6. If you want to register  SASS support for your extension then press enter otherwise type false and then press enter. Here we are using default value so we will press enter.
  7. If you want to create sample widget then press enter otherwise type false and then press enter. Here we are creating sample widget so will press enter.
  8. If you want to create a sample style sheet then type true and then press enter. If you do not want to create a sample style sheet then simply press enter.
    SASS extension sample widget sample style sheet
  9. Navigate to <%HYBRIS_HOME_DIR%>/config and open local.properties file and specify the following entry and save it.
    backoffice.sass.enabled=true
  10. Now run ant sasscompile from the platform.
    ant sasscompile
  11. Now we will add our custom backoffice extension(hybrisdiary) to localextensions.xml
    localextensions.xml
  12. Now we will do ant clean all.
    ant clean all

If the build successful then your custom backoffice extension successfully generated. If you are using eclipse then import your custom backoffice extension in to eclipse.

2. Create a widget definition

To create a widget definition, we must keep in mind that widget-definition id must be unique. If your widget-definition id matches with existing widget-definition id then your new widget will not appear on the list of widgets in the choose widget wizard. Now do the following steps to create the widget definition:-

  1. Navigate to hybrisdiary->backoffice->Resources->widgets and create a new folder called as mycustominput
    mycustominput folder location
  2. Now create a definition.xml file inside the newly created folder(mycustominput).
  3. Now add the following lines of code to the file(definition.xml).

    definition.xml
    definition.xml

3.Creating a widget view

The view of our widget will be defined in the ZUL file and the name of the file must match with last part of the widget ID as defined in the definition.xml file. The last part of widget ID is mycustominput so the view file name will be mycustominput.zul. In mycustominput.zul file, we will define all frontend component. To check whether the entered input is an integer or not we need one textbox for input and one button to submit. So we will define one textbox and one button in mycustominput.zul file. Now follow the following steps to create the widget view:-

  1. Now create a mycustominput.zul file inside the mycustominput folder.
  2. Now add the following lines of code to the mycustominput.zul file.
    mycustominput.zul
    mycustominput.zul

     

4.Create a service for widget/ Use existing service for a widget

For our example, we need some service to do some action. Either we can create our custom service to do some logic or we can use existing services. In our example, we will create a custom service that will check that the entered input is an integer or not. To create a service for our custom widget, we need to follow the following steps:-

  1. Navigate to hybrisdiary->src folder and create MyCustomInputService.java file in de.hybris.hybrisdiary.mycustominput package.
  2. Add the following lines of code to the MyCustomInputService.java file.

    MyCustomInputService.java file
    MyCustomInputService.java
  3. Navigate to hybrisdiary->resources and open hybrisdiary-backoffice-spring.xml file and define the bean for MyCustomInputService as shown in below image.
    mycustominputservice bean
    mycustominputservice bean

     

5. Create a controller for the widget

Here we have not defined any action for submit button so when we click on the button nothing will happen. To do some action we need to define a controller for the widget. To create a controller for the custom widget we need to follow the following steps:-

  1. Navigate to hybrisdiary->backoffice/src and create MyCustomInputController.java in de.hybris.hybrisdiary.widgets.mycustominput package.
  2. Add the following lines of code to the file.

    MyCustomInputController
    MyCustomInputController.java
  3. Navigate to hybrisdiary->backoffice->Resouces->widgets->mycustominput and open definition.xml file and we add a controller class to this file as shown in the image.

    definition.xml
    definition.xml

6.Build and start the server

Now we will build the system by running ant clean all and we start the server by running the hybrisserver.bat file.

7.Deploy the widget

Now we will deploy our custom widget. To deploy the custom widget do the following steps:-

  1. Open the internet browser.
  2. Enter https://localhost:9002/backoffice  in the browser’s address bar.
  3. Enter your credentials and log in.
    backoffice login
  4. Press F4 to enter into Application Orchestrator mode and click on the symbol(+ symbol inside an orange circle) to add the new widget as shown in below image.
    Application Orchestrator mode
    Application Orchestrator mode

    The choose widget appears, which contain all the available widgets and choose My Custom Input widget. You can easily learn the process of adding a widget to backoffice by observing the image.
    add widget process

  5. Now press F4 to enter into normal mode and you will see the newly added widget in backoffice.
    new widget in backoffice
  6. Now we enter 54 in the input box and which is an integer and we press the submit button. Now message box will appear which show us that “input value is an integer“.
    working widget

Navigation management in SAP Hybris Commerce

Navigation management through impex

When we create a website based on an existing content catalog, a default navigation structure is created for our content catalog. If we create a website based on a new content catalog, we must build navigation structure for our new content catalog. So we will learn here how to create navigation nodes using impexes.

Create new navigation node using impex

To explain this we will create one new custom navigation node in apparel storefront. In apparel storefront, there are 5 navigation nodes as shown in the image and we will add another navigation node at the end of navigation nodes.

Apparel Store
Apparel Storefront

Steps to create a new navigation node

Step-1

Create a new CMSNavigationNode. Like created in below image.

CMSNavigationNode

Step-2

Create a new CMSNavigationEntry for CMSNavigationNode. Like created in below image.

CMSNavigationEntry

Step-3

Create a new CMSLinkComponent. Like created in below image.

CMSLinkComponent

Step-4

In this step, we do localization of CMSNavigationNode and CMSLinkComponent as shown in the image

Localiztion

The complete impex will look like this.

create_navigation_node
new_navigation_node.impex

Here we assume that your server has started already. Now run the above impex(new_navigation_node.impex) in HAC(Hybris Administration Console) and synchronize the content catalog(apparel-ukContentCatalog).

Now access the apparel storefront and you can clearly observe newly created navigation node. In below image, you can see new custom navigation node.

Apparel store with new node
Apparel store with new navigation node

Create Children nodes of Custom navigation nodes

Now we will create children of above-created navigation node. To create children of above-created navigation node, we need to follow the following steps

Step-1

Create a new CMSNavigationNode. Like created in below image.

ChildrenCMSNavigationNode

Custom Brands Nav Node is a child of Custom Nav Node and Custom Brands Nav Node is the parent of bitbyte Link and hybrisdiary Link.

Navigation tree structure

Step-2

Create a new CMSNavigationEntry for children nodes. Like created in below image.

CMSNavigationEntry For Children

Step-3

Create a new CMSLinkComponent. Like created in below image.

CMSLinkComponentForChildren

Step-4

In this step, we do localization of CMSNavigationNode and CMSLinkComponent as shown in the image.

Children's localization

The complete impex will look like this.

Complete impex for children node
new_navigation_children_node.impex

Here we assume that your server has started already. Now run the above impex(new_navigation_children_node.impex) in HAC(Hybris Administration Console) and synchronize the content catalog(apparel-ukContentCatalog).

Now access the apparel storefront and Hover on custom navigation node and you can clearly observe newly created children(HYBRISDIARY and BITBYTE) of custom navigation node. In the below image you can observe.

Apparel store with Childrens
Apparel store with new navigation node and with its children

Commerce Quotes in SAP Hybris Commerce

Commerce Quotes

Commerce quotes enable buyers to create the quote and negotiate the final price of an order using the storefront. The quote can be negotiated by both parties(user and seller) until an agreement is reached, at which point the buyer checks out the quote and places an order.

Who can Create quotes?

  1. Buyers create quotes using their session cart, and then submit the quote requests to their sales representative. Buyers can only request quotes if the cart value is more than a defined amount ( default value is 25000 but this can be configured). The sales representative then adjust the quote and makes a vendor quote for negotiation. Both roles have the flexibility to modify the quote during the negotiation process, they can add, remove and comments. The quote is sent back and forth until both parties agree to the terms.buyerquote                          Diagram:- The quote process when a buyer initiates a quote
  2. A sales representative can also create quotes for their buyers using ASM(Assisted Service Module). A quote created or modified by the sales representative must be approved by the vendor if the amount is above defined threshold ( default value is 75000), at which point it becomes a legally binding vendor quote. If the buyer agrees with the terms, vendor quote is then converted to an order, which must be approved by the buying organization.salesrepresentative

Diagram: quote process when a sales representative initiates a quote

Quote Negotiation Process

There are three user roles that are involved in the quote negotiation process.

  1. Buyer:- The buyer submits quote requests to the sales representative, and then decides to accept or reject the vendor quotes submitted by the sales representative
  2. Sales Representative:- The sales representative receives the buyer’s quote request and modifies it to make an attractive vendor quote. The sales representative can also create a quote on buyer’s behalf.
  3. Seller Approver:- The seller approver must approve any vendor quotes submitted by the sales representative that exceeds the vendor’s authorization threshold.

Quote Status in quote negotiation process

Each user role can review the status of the quote to see where in the negotiation process it is. The quote status that appears in the storefront depends on the role that is viewing the quote. Any changes made to a quote by one role are not visible to any other role until the quote is submitted for the next step in the process.

  1. Quote Status for buyer:- During the negotiation process, these are the quote status visible to the buyer
  • Draft:-Quote created by the buyer but not submitted to a sales representative. The buyer can edit, submit or cancel the quote.
  • Submitted:-Quote sent to the sales representative. The buyer can’t edit or cancel the quote and must wait to get a vendor quote from the sales representative.
  • Ordered: –A vendor quote that was accepted and ordered.
  • Cancelled:-Quote cancelled by the buyer.
  • Vendor Quote:-The legally binding vendor quote from a sales representative. The buyer can

a) accept the vendor quote and check out the order.

b) cancel the vendor quote

c) reject the quote and continue negotiation

d) modify the vendor quote, which also rejects the vendor quote and continue the negotiation.

2. Quote Status for Sales Representative:-These are the quote statuses are visible to sales representative during the negotiation process.

  • Draft:-Quote that the sales representative created or modified, but has not submitted by the vendor quote yet. A sales representative can either edit the draft quote or submit a vendor quote.
  • Requested:-Quote that has been submitted by the buyer or that has been rejected by the seller approver. A sales representative can either edit it or submit a vendor quote.
  • Submitted: –A legally binding quote submitted by the sales representative. Sales representative can’t make any modifications.
  • Cancelled:-Quote cancelled by the buyer. Sales representative can’t make any modifications.

3. Quote Status for Seller Approver:- The quote status indicates which vendor quote the approver must act on

  • Pending: –A vendor quote submitted by the sales representative that exceeds the vendor approval threshold. This is the only status that the seller approver can act on.
  • Rejected: –A vendor quote that was rejected by the seller approver.
  • Approved: –A vendor quote that was approved automatically because it did not exceed the vendor’s threshold.
  • Cancelled:-A vendor quote or quote that was cancelled by the buyer.

Enable Commerce Quote in Storefront

Commerce quote is implemented in the powertools storefront by default. But here we will enable commerce quote in Apparel storefront.

Commerce quote is enabled by a switch to set to true in the project.properties file of the apparelstore.

Navigate to <%HOME _DIR%>/config and open the local.properties file and add properties to enable quote and restart the server

enablecommercequotesinapprelstore

Change the quote threshold

Buyers can only request quotes if the value of their cart is more than a certain value and that certain value is called as quote threshold. The default quote threshold value is 25000. We can modify this by following two ways

  1. Modifying project.propertiesTo change the default quote threshold value navigate to <%HYBRIS _DIR%>/config and open the local.properties file and add the following property and restart the server.

updatedquotethreshold

  1. Using the HAC(Hybris Administration Console)To change the minimum quote amount threshold using HAC
    1. log in to HAC
    2. Navigate to Platform->Configuration
    3. In the search field, enter quote.request.initiation.threshold quotethreshold
    4. Enter the required threshold amount in the value field.
    5. Click Apply all.

Change the seller approver threshold

Vendor quote that exceeds a vendor’s authorization threshold must be approved, otherwise, they are automatically approved. We can modify the seller approver threshold by following two ways

1. Using HAC(Hybris Administration Console)

To change the authorization threshold using HAC

  • log into HAC
  • Navigate to Platform->Configuration
  • In the search field, enter commerceservices.quote.seller.auto.approval.thresholdupdatesellerthreshold
  • Enter the required threshold amount in the value field.
  • Click Apply all.

2. Change in local.properties

To change the authorization threshold navigate to <%HYBRIS _DIR%>/config and open the local.properties file, add the following property and restart the server

autosellerapprovalthreshold

Steps involved in achieving quote negotiation process in Apparel storefront

Create and Submit quote:-

we added items to cart and our total cart value is more than quote threshold value so we request a quote by clicking on request a quote button in the cart page as below:

requestquote

In this scenario, we are assuming that buyer is already logged in the storefront. Now we are redirected to quote draft page and here we will modify the quote name and add a quote description and after that, we will click on submit quote button.submitquote

Making a Vendor Quote:-

To work on a quote for a customer, sales representative log into ASM(Assisted Service Module) and start a session for the customer. Sales representative use the quotes listing page to see if there are any quote requests that need their attention. The quote listing page is accessed by navigating to my-account->my-quotes. The listing displays all quotes that have been submitted by the buyer. As you can see in below image

quotelisting

Clicking the quote name(Vinay Sharma quote request) in the listing loads the details page for that quote.

quotedetails

Sales representative clicks on edit quote button.

Now click on the discount link below sub-total and it will open discount model. Here sales rep will enter the discount related data. In our case, we are providing 5% discount. You can observe in below images

discountlink

discount

Clicking submits quote creates a legally binding vendor quote that the buyer can accept. Our quote is below the threshold, so it is automatically approved.

Now Buyers can view all their quotes by navigating to my-accounts->my-quotes

vendorquote

In our scenario, we are assuming that user happy with the vendor’s quote so he accepts and checkout.

acceptingaquote

New features in SAP Hybris Commerce 6.6

New features in SAP Hybris Commerce 6.6

The SAP Hybris Commerce release 6.6 includes key enhancements, focus on Enabling Consent and Personal Data Management. The following features are included in SAP Hybris Commerce 6.6 :-

  • GDPR(General Data Protection Regulation)
  • SAP Hybris Customer Experience Enhancements
  • Enhancement to Search and Navigation
  • SAP Hybris Product Content Management
  • SAP Integrations

GDPR(General Data Protection Regulation)

SAP Hybris Commerce 6.6 includes key enhancements to enable organizations to implement processes to be compliant with the GDPR. These capabilities include consent management, security, encryption, reporting, and data management. The new GDPR feature include:-

  1. Consent Management

    Consent management offers better transparency and customer engagement by allowing users to grant consent for their personal data to be captured and processed.

  2. Personal Data Reporting

    Personal Data Reporting allows the reporting of personal customer data that is captured, to be generated and provided to customers.

  3. Customer Account Closure

    Customer Account Closure allows customers to close their website accounts at any time using self service.

  4. Personal Customer Data Annotation Framework

    Personal Customer Data Annotation Framework allows the easy configuration of personal customer data so it can be flagged and used for Personal Data Reporting.

  5. Personal Customer Data Retention/Erasure Framework

    Personal Customer Data Retention/Erasure Framework provides the ability to retain or delete a customer’s personal data based on legal/configurable retention periods.

  6. Generic Audit

    Generic Audit stores all personal customer data changes. It allows the storage every change made to all instances of given data type. You can enable what data items get audited at the properties level with type-level granularity.

 Advantages

  • Enable compliance of General Data Protection Regulation.
  • Minimize business disruption.
  • Earn customer trust and confidence.

SAP Hybris Customer Experience Enhancements

  1. SmartEdit for Customer Experience

    SmartEdit for SAP Hybris Customer Experience provides an easy and intuitive way to edit and manage your website across all touch points from a single interface. The following features and framework enhancements have been introduced to SmartEdit in SAP Hybris Commerce 6.6

    • Cloning Components
    • Moving Pages to trash
    • Converting shared slots to non-shared slots
    • Framework improvements, such as a new build system and management of nested components.
  1. Personalization

    SmartEdit for SAP Hybris Customer Experience provides an easy and intuitive way to edit and manage your website across all touch points from a single interface. The following features and framework enhancements have been introduced to SmartEdit in SAP Hybris Commerce 6.6

    • Cloning Components
    • Moving Pages to trash
    • Converting shared slots to non-shared slots
    • Framework improvements, such as a new build system and management of nested components.

Advantages

  • Increase flexibility of personalization.
  • Enhance customer experience.
  • Drive sales and increase conversion.

Enhancement to Search and Navigation

Search and Navigation capabilities allow you to configure how your customers browse through category navigation and search for products based on keywords or facets. The following features are new in SAP Hybris Commerce 6.6

  1. Enhanced search experience with Personalization

    You can easily apply personalized search settings by applying Search Profiles for selected Target Group on the top of the search Profiles that had been already activated in the Activation Set. To provide even more targeted experience, you can activate Search Profiles for different Target Groups and they will be all combined together if the user qualifies for more than one Target Group.

  2. Improved Solr Security

    The SAP Hybris Commerce 6.6 comes with support to encrypt communications to and from Solr, and between Solr nodes, using SSL. SAP Hybris Commerce 6.6 also offers support for authentication and authorization using the security framework of Solr.

  3. Solr Upgrade to 7.1

    In this release they have upgraded to the new Solr major version 7.1 to keep up with Solr enhancements.

Advantages

  • Offer personalization experience for product search.
  • Drive sales and increase conversion.

SAP Hybris Product Content Management

With the SAP Hybris Commerce 6.6 release they have introduced a new Microsoft Excel Import/Export Feature and enhanced the collaboration Center with the Workflow Visualization feature.

  1. Microsoft Excel Import/Export

    SAP Hybris Commerce 6.6 would allow you to fulfill two scenarios

    • Export selected products and perform a mass editing through the spreadsheet and then re-import them again.
    • Download an empty Excel sheet that is pre-populated with all the attributes defined in your system, and import new products using the this Excel template.

    This new feature of Product Content Management(PCM) will make the life of product content managers a whole lot easier.

  2.  The Workflow Visualization

    The Workflow Visualization allows you to visually see the workflow. With the SAP Hybris Commerce 6.6 release they have also introduced a feature that allow you to clone a product. This serves as a base for an extended feature where you will be able to clone a product multiple times.

Advantages

  • Enhance usability.
  • Increase flexibility of the tool.
  • Enable higher productivity.

SAP Integrations

SAP Integrations provides a framework for connecting the omni-commerce capabilities of SAP Hybris Commerce with other SAP products. The release note cover the following

  1. SAP Back-End Integration: SAP S/4HANA and SAP ERP

    The following feature are in the new release:-

    • Allows the cancellation of return orders.
    • Fixed the issue regarding the modification of refund amount by customer support agent using Backoffice. The modified refund amount is now reflected in the back end.
    • Data Privacy Management.
  1. SAP CPQ for Product Configuration

    SAP CPQ for product configuration provides access to a comprehensive solution to manage personalized and customizable products in and with SAP Hybris Commerce. The following feature are new in the release:-

    • Enhancements for product configuration rules.
    • Switch for option price.
  1. SAP Product Configuration Integration

    The SAP Product Configuration integration provides access to a comprehensive solution to manage personalized and customizable products in and with SAP Hybris Commerce Cloud. The following feature are new in this release:-

    • Support of multilevel products.
    • Conflict handling.
    • Reconfiguration for product configuration rules.
    • Switch for option price.
  1. SAP Hybris Marketing Integration

    SAP Hybris Marketing integration allows you to offer your customers personalized interactions and shopping in an online store. The following feature are new in this release:-

    • Data privacy Management.
    • Campaign restriction in SmartEdit.
  1. SAP Hybris Cloud for Customer Integration

    The SAP Hybris Cloud for Customer integration with SAP Hybris Commerce 6.6 includes quote replication developments. The following feature are new in this release:-

    • Sales quote replication from SAP Hybris Commerce to SAP Hybris Cloud for Customer.
    • Update the commerce quote from SAP Hybris Cloud for Customer with the price and discounts.
    • Convert quote to sales order and replicate to SAP ERP or SAP S/4HANA.
  1. SAP Digital Payment Integration

    SAP Hybris Commerce integration with SAP Digital Payments enables a B2C customer to register a credit card, fetch the card details and authorize the payment during the item checkout process. The following features are new in this release:-

    • Digital payments integration is avaialble with B2B scenario as well.
    • The existing credit card can be removed from the My Accounts -> Payment Details ->page.
    • If an order is returned, then the payment done using credit card will be reversed.
    • The configurations are now made available in the Backoffice Administration Cockpit.

Advantages

  • Advanced campaign management capabilities.
  • Additional integration scenarios.
  • More end-to-end processes.
  • Better customer experience.

AddOn Concept

AddOn Concept

AddOns are built on top of the existing SAP Hybris Commerce to extend the functionality of the SAP Hybris Commerce Accelerator. AddOns are a type of extension that allow you to add front end files(such JSP, HTML, CSS and JavaScript files, as well as images) from within your own AddOn, Instead of modifying the storefront-end files directly.

Using AddOns, you can extend the functionality of Hybris Commerce Accelerator without editing the core code base. The core code base in this context means Hybris Platform, and all additional extension delivered with Hybris Commerce Accelerator. An AddOn is a regular extension that may or may not provided additional front-end components to Hybris Commerce Accelerator.

Advantages of AddOn Concept

  1. AddOn file kept separate from the rest of the front-end files.
  2. When you upgrade the Accelerator, it will not overwrite your files.
  3. You can easily remove your AddOns without refactoring the code of your whole extension.

Creating AddOns

To create your custom AddOn follow the following steps:

1.Open the command prompt and

navigate to the <%HYBRIS_HOME_DIR%>hybris/bin/platform directory.

navigatetoplatform

2.Now run the setantenv.bat file. Do not close the command prompt.

setantenv

3.Run the following command to create your custom AddOn

ant extgen -Dinput.template=yaddon -Dinput.name=myaddon -Dinput.package=com.myapp

Before running above command you can observe that inside hybris/bin/custom folder only single extension(bitbyte)

before creation of addon

Now Run the following command from platform

create addon

After running the above command you can see your custom AddOn inside hybris/bin/custom folder.

hybris diary addon

4.Configure localextension.xml file

Add your custom extension (AddOn) to <%HYBRIS_HOME_DIR%>/hybris/config/localextensions.xml

localextenstion.xml
localextensions.xml

now rebuild the Hybris system by running ant clean all .

ant clean all

Installing an AddOn for specific storefront

The addoninstall tool allow you to configure an AddOn for a specific storefront. It also adds the AddOn to the extensioninfo.xml file of the storefront, and generates the relevant project.properties file for the AddOn.

Now follow the following steps to install AddOn

  1. Before running ant addoninstall command ensure that addonsupport extension is listed in localextensions.xml file.
addonsupport extension in localextension.xml
localextensions.xml

Also ensure that the AddOn and storefront extension that you want to install are listed in localextensions.xml file.

2.Now run the following command to install the AddOn

ant addoninstall -Daddonnames="addonname" -DaddonStorefront.<storefrontTemplateName>="StoreFront"

addoninstall

3. When addoninstall has finished running successfully, rebuild the Hybris system by running ant clean all .

Uninstalling an AddOn for a specific storefront

The addonuninstall tool can be used to remove an AddOn from the storefront.

Now run the following command to uninstall the AddOn

ant addonuninstall -Daddonnames="addonname" -DaddonStorefront.<storefrontTemplateName>="StoreFront"

addonuninstall

When addonuninstall has finished running successfully, rebuild the Hybris system by running ant clean all .

 

Flexible Search Caching with TTL

images

 

Flexible queries are already cached in hybris commerce which provide good performance in most of projects. Generally, hybris regions cache performs well when system has more read of data than writes. Frequent changes to data (products, images, master data etc.) will result in invalidation of cached entities, types and flexible queries on all nodes forcing system to fetch data from database as cache has been invalidated. Projects having very frequent changes in database can suffer from high performance degradation due to frequent invalidations.

In this post we will be discussing an option to stop invalidation of query for specified amount of time irrespective of change in items in database, this feature is called TTL – Tme To Live. The value of TTL is defined in session context which enforces query to live at least for this duration. Implementation of TTL can significantly improve performance in applications which have frequent changes in database.

Below are steps to executed to implement TTL in a project:

  1. Create an aspect class as below – this class is picking configurable properties: a flag and duration of TTL (in seconds) from configuration file and sets in session context:

1

  1. Define spring bean:

2

  1. Add AOP configuration for specific methods to enable TTL caching:

3

Please note this feature should be tuned as per your use case.  Applications with less writes than reads can have adverse affect on performance. Downside of this configuration is that cached queries will not pick changes immediately on storefront for the defined time so there need to be ballance between performace gain vs data accuracy.  Overall this is a very good option to finetune the performance of hybris applications.

Try it and enjoy improved performance!

 

Extgen

Extgen

SAP Hybris commerce ships with an extension generator tool called extgen, which is short for extension generator. Using extgen tool, you can create new extension based on extension templates. With the extgen tool, you can create one new extension using one template extension. From a technical perspective, any extension can be used as a template extension. The extgen tool is fairly basic in that it simply replaces the tokens configured in properties file.

SAP Hybris Commerce installation

Before running the extgen tool, you need to download the latest version of SAP Hybris Commerce.

Once you have downloaded SAP Hybris Commerce, extract the Hybris Commerce ZIP file.

1.Open a command prompt.

cmd

2.Navigate to the %HYBRIS_HOME_DIR%/installer directory.

navigate

3. Invoke the installer with the b2c_acc recipe by entering the following command.

installer

Steps to create an extension using extgen

1.Navigate to the %HYBRIS_HOME_DIR%/hybris/bin/platform directory

platform

2. Now run setantenv.bat file. Do not close the command prompt.

setantenv

3.Now run

extgen

Extgen prompts you to specify values for the technical aspects of an extension. Extgen comes with default values for all these technical aspects.

These default values are defined in the project.properties file in the extgen directory. The default value is displayed in brackets ([ and ])

Choose a template for generation

Press enter to use the default value. Here default value is [yempty] and we press enter.

template

Choose the name of extension

Here we specify the name of the extension is hybrisdiary.

extensionname

Choose the package name

We can choose default package name for our extension but we specify the name of the package is org.bitbyte .

 package

Now observe that new extension(hybrisdiary) has been created inside hybris/bin/custom folder.

 custom

Configure localextension.xml file

Add your extension to your X:\%HYBRIS_HOME_DIR%\hybris\config/localextensions.xml. After the creation of extensions using extgen, make sure to update the localextensions.xml file as below

localextension

localextension.xml file

Navigation management through SmartEdit

Navigation management through SmartEdit

SmartEdit provides Navigation management that enables you to add, move, edit and delete navigation nodes for a content catalog. You can easily change the order of the navigation nodes using drag and drop feature. You can also add, edit and remove entries from navigation nodes. Entries are pages, media, and components that you associate with navigation nodes.

When you create a website based on an existing content catalog, a default navigation structure is created for your content catalog. If you create a website based on a new content catalog, you must build navigation structure for your new content catalog.

 

Signing into SmartEdit

SmartEdit provides an intuitive user interface that allows content managers to easily edit the content catalog of their companies website.

Procedure

We assume that your server has started already and now follow following steps to sign in into SmartEdit

  1. Open an internet browser.
  2. Enter https://<server.ip.address>:9002/smartedit in the browser’s address bar.
  3. Enter your credentials.(username=’admin’ and password=’nimda’)
  4. Select the language and sign in.

smartedit

All the catalogs that are available in your websites are displayed in the Your Site page.

yoursite

Adding Navigation Nodes

We can add following types of navigation nodes:

  1. Top level
  2. Sibling
  3. Child

 

Adding a Top level Node

toplevel

Click on + ADD NEW TOP LEVEL and after that Enter the name of the node and title of the node to the corresponding fields and press save.

topnode

Now you can see that Bitbyte added as top level node to the site.

addnode

Adding Sibling and Child Nodes to Navigation Nodes

Go to navigation node that you want to add a sibling or child node to and Click the Option menu and select Add a Sibling or Add a child. Here we will add child node.

option

After that we enter the name and the title of the child and save it.

child

Now you can clearly observe that one child node(Hybrisdiary) added to the Bitbyte node.

addchild

AngularJS MVC and Scopes

AngularJS MVC Architecure

MVC stands for model view controller. It is a software design pattern for developing web applications. It is very popular because it isolates the application logic from the user interface layer and supports separation of concerns. The controller receives all requests for the application and then works with the model to prepare any data model by the view. The view then uses the data prepared by the controller to generate a final presentable response. The MVC abstraction can be graphically represents as follows

mvc

1. Model

It is responsible for managing application data. It responds to the request from view and to the instructions from controller to update itself.

2. View

It  is responsible for displaying all data or only a portion of data to users. It also specifies the data in a particular format triggered by the controller’s decision to present the data.

3.Controller

It is responsible to control the relation models and views. It responds to user input and performs interactions on the data model objects. The controller receives input, validates it, and then performs business operations that modify the state of the data models.

AngularJS Scopes

Scope is a special JavaScript object which plays the role of  joining controller with the views. Scope contains the model data. In controller, model data is accessed via $scope object.

Example:

 scope

Code Explanation

  1. Scope is passed as first argument to controller during its constructor definition.
  2. $scope.firstName and $scope.lastName are the models.
  3. We have set values to models which will be reflected in the application module whose controller is myController.

Output

scopeoutput

AngularJS Modules and Controller

AngularJS Modules

A module defines an application. It is container for the different parts of your application like controller, services, filters, directives etc.

Controller always belong to a module.

Creation of a module

A module is created by using the AngularJS function angular.module

module

The “myApp” parameters refers to an HTML element in which the application will run. Now we can add controllers, directives, filters, and more, to your AngularJS application.

AngularJS Controllers

AngularJS application mainly relies on controllers to control the flow of data in the application. A controllers is defined using ng-controller directive. A controllers is a JavaScript object containing attributes/properties and functions. Each controller accepts $scope as a parameter which refers to the application/module that controller is to control.

Example:

In the following example we will explain module and controller.

 controller

Output:

 controleroutput

Code Explanation:

  • ng-app directive is used to denote that this application should be considered as an angular application. “myApp” is the name given to our AngularJS application.
  • In body tag we have added an ng-controller directive along with the name of our controller “myControl”. This basically makes our body tag the ability to access the contents of the “myControl”. We need to mention the name of the controller under the directive to ensure that we are able to access the functionality defined within the controller.
  • We are creating a module which will attached to our “myApp” So this module now becomes part of our application.
  • In the module, we define a function which assigns a value of “Bit” and “Byte” to our firstName and lastName variables respectively.

AngularJS Directives

AngularJS Directives

AngularJS facilitates you to extend HTML with new attribute. These attributes are called directives.

Directives are special attributes starting with ng- prefix.

We are going to discuss following directives which are the most common directives –

  • ng-app:- This directive starts an AngularJS application.
  • ng-init:-This directive initialize application data.
  • ng-bind:-This directive binds the value of HTML inputs controls to application data.
  • ng-model:-This directive binds the values of AngularJS application data to HTML input controls(input, selection, text area).
  • ng-repeat:-This directive repeats HTML elements for each item an collection.

 

ng-app directive

ng-app directive defines the root element. It starts an AngularJS application and automatically initializes or bootstraps the application when web page containing AngularJS application is loaded. It is also used to load various AngularJS modules in AngularJS application.

Example:

ngpp

The ng-app directive also tells AngularJS that the <body>  is the owner of the AngularJS application.

ng-init directive

ng-init directive initializes an AngularJS application data. It is used to put values to the variables to be used in the application.

In the following example. we will initialize the variable

nginit

ng-bind directive

ng-bind directive bind the application data to HTML view. The ng-bind directive bind AngularJS data to HTML the same way as AngularJS expression.

ngbind

Output:

 ngbindoutput

ng-model directive:

This directive binds the values of AngularJS application data to HTML input controls. In following example, we’ve defined a model named “name” and access that variable using ng-bind directive.

 ngmodel

Output:

 

 

ng-repeat directive:

ng-repeat directive repeats HTML elements for each item in a collection

ngrepeatprogram

Output:

ngrepeat

We have so many other built in directives that we will discuss later.

Spring Boot

 

SpringBootLogo
Spring Boot

 

 

Before entering into spring boot just a brief summary about spring

What is Spring??

Spring is a high performance, lightweight, non-invasive, easily testable application framework. Using spring we can develop all layer implementations unlike struts (struts framework supports only developing web applications).

In one line we can say spring is the end to end application development framework.

The core concept of spring framework is dependency injection. By dependency injection, we can achieve loose coupling.

 What does it do??

 Spring approach is developing enterprise Java applications by using POJOs. Because of using POJOs no need of application server we can use the servlet container.

 There are so many enterprise Java applications, all these applications having some similarities. When we write a business service to solve business problem spring handle all those things like connecting to the database, establishing transaction service and so on…Spring provides a template for this to build these applications.

The flexibility with the spring is we can concentrate only building on business services and spring handle rest of the common things like connecting to the database, running queries and handling HTTP requests…

Spring provides infrastructure support, for example, spring connecting to the databases like the relational database and mango DB, spring has infrastructure support when we are building our applications.

Spring framework Pros and Cons….

Pros:

  • Simple
  • Testable
  • Loose Coupling.
  • Performance
  • Security
  • Integration

Cons:

  • Huge framework.
  • Multiple setup and configuration steps.
  • Multiple build and deploy steps.
  • The learning curve would be high.

So Spring Boot comes as handy…!!!

What is Spring Boot??

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can just run.” — from official spring.io

The main aim of spring boot is accelerating (speed up) application development, by the “convention over configuration” approach.

By using Spring Boot, we can develop end to end application with production ready.

What does it do??

Spring Boot reduces the complexity of dependency management with the help of spring boot starters concept. Whereas in spring we need to search for the required libraries for specific spring version.

For example, if we want to declare the web related dependencies, in general, we need to declare each and every dependency related to the web. But in the case of Spring Boot, we declare only one dependency “spring-boot-starter-web” it pulls all the required dependencies for the web module.

Some common configurations such as DataSource, JdbcTemplate, DispatcherServlet, HandlerMapping……. Spring Boot comes with the auto configuration to configure all these configurations by adding @SpringBootApplication or @EnableAutoConfiguration.

By using Spring Boot, we can create the standalone application and just run like normal java application we don’t have to find out servlet container because Spring Boot comes with the embedded servlet container. Whereas traditional Spring application we are building a war file and deploy in the servlet container.

Spring Boot comes with production ready features.

Setup:

  • We will use Maven or Gradle build for Spring Boot application.
  • Spring Boot works with Spring 4.x version and later. And JDK 1.8
  • Eclipse or STS

To build spring application we need to manage dependencies, so we need to add required jars for the specific version of spring. We will add the jars to the classpath so that the classes in jars are available to that application.

We are not following this approach, we are using Maven (build and dependency management tool) in Maven we will declare all the dependencies in pom.xml file and so that maven tool will automatically import required jars from the repository to our classpath.

Sample Spring Boot Application:

Create a simple Maven project.

Picture1

 

Skip the archetype by selecting the create a simple project

Picture2

 

Enter the group id, Artifact Id, and Name

Picture3

 

Package Structure of SampleSpringBoot project

Picture4.png

The default dependency file (pom.xml) is like below.

Picture5.png

We adding the dependency spring boot starter parent which will act as a parent for the all remaining spring boot dependencies. And we are adding Java version and spring boot starter web dependency

Picture6.pngWe are creating SpringBootDemo application this is the starting point for our application and @SpringBootApplication tells spring this is spring boot application and create servlet container and deploy in a container.

What SpringApplication class will do??

Setup default configuration

 Starts spring application context

Every spring application has application context which runs the spring application

Performs class path scan

 If we declare a class with annotation @Service or @Controller … spring will look at those classes and treated service annotation service, controller annotation as a controller to identify all these classes it has to be scan the class path

Starts Tomcat Server

 No need to download any Tomcat server by default it comes with spring boot so the output of the application is as standard application

Picture7.png

We are creating Rest Controller to handle HTTP requests.

Picture8.pngOverriding Tomcat port number in “application. properties” file, if the Tomcat default port (8080)  is listening to some other process.

Picture9.png

Run the sample spring boot application as like normal Java application.

Picture10.png

By running sample spring boot application as a standalone java application, tomcat will have started automatically on the port 9090.

Picture11.png

To verify this in the browser, just enter the localhost port number and request mapping.

Picture12.png

 

 

 

 

 

 

 

AngularJS

 

 

angularjs

Introduction to  AngularJS

AngularJS version 1.0 was released in 2012.

Misko Hevery, a Google employee, started to work with AngularJS in 2009.

AngularJS is a JavaScript framework designed for creating single page web application.

AngularJS is entirely based on HTML and JavaScript, so there is no need to learn any other syntax or language.

What is AngularJS?

AngularJS is structural framework for dynamic web apps. It lets you use HTML as your template language and lets you HTML’s syntax to your application’s components clearly and succinctly. AngularJS’s data binding and dependency injection eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it an ideal partner with any server technology.

Features of AngularJS

1.You don’t need to write special code to bind data to the HTML controls. This can be done by just adding few snippets of code.

2.When carrying out DOM(document object model) manipulation a lot of JavaScript was required to be written to design any application. But with AngularJS, you will be amazed with the lesser amount of code need to write for DOM manipulation.

3.AngularJS provides developers options to write client side application(using JavaScript) in clean MVC(model view controller).

4.AngularJS is open source, completely free, and used by thousands of developers around the world

 

Advantages of AngularJS

1. MVC(Model view controller)

Most frameworks require programmers to splitting the app into multiple MVC components. After that, the programmer has to write a code to put them together again. AngularJS, however, strings it together automatically. That saves you time, and reduces the app’s time to market.

2.Two way Binding

It is possible to do two way binding with AngularJS, meaning you can make any data related  changes and would immediately be propagated to the corresponding views and when any change is made in the view, that would happen in the underlying models as well. As soon as the app data changes, there will be corresponding changes in the UI as well.

3.Dependency Injection

The built in dependency injection is something most developers love about AngularJS. This feature helps them to develop, test and understood application in a better way.

Dependency Injection is a software design pattern in which components are given their dependencies  instead of hard coding them within the component. This relieves a component from locating the dependency and makes dependencies configurable. This helps in making component reusable, maintainable and testable.

4.Routing

AngularJS can take care of routing which means moving from one view to another. This is the key fundamental of single page application, wherein you can move to different functionalities in your web application based on user interaction but still stay on the same page.

Disadvantages of AngularJS

Though AngularJS comes with lots plus points but same time we should consider the following points:-

1.Confusing

There are multiple ways to do the same thing with AngularJS sometimes, it can be hard for novices to say which way is better for a task. Hence it is imperative for programmers to develop an understanding of the various components and how they help.

2.Not secure

Being JavaScript only framework, application written in AngularJS are not safe. Server side an authentication is must to keep an application secure.

3.Not degradable

If your application user disables JavaScript then user will just see the basic page and nothing.

First AngularJS program

Before we start with creating our first AngularJS program, let us see what are the important part of a AngularJS application

1.ng-app

This directive defines AngularJS application.

2.ng-model

This directive bind the value of HTML controls to application data.

3.ng-bind

This directive bind the application data to HTML view.

4.Expression

AngularJS expression can be written inside double braces.{{expression}}

NOTE:

AngularJS lets you extend HTML with new attribute called directive.

AngularJS directive are prefix with ng-.

Steps to create AngularJS program

1.Load framework

framework

 2.Declare HTML body as an AngularJS application using ng-app

ngapp

3.Define model name using ng-model directive

ngmodel

4.Accesing member varible

expression

Now our first AngularJS program

first

output

output1

output2

 

 

Java 8 | Lambda Expression

The lambda expression feature reshaped the Java language. Lambda expression comes with the functional programming construct to the object oriented programming. Lambda is nothing but an anonymous method.

Features:

  • Lambda expression reduces the number of lines of code.
  • Lambda expression provides implementation to the functional interface.
  • New capabilities are added to the API library.
  • Parallel processing of multi-core environments, especially handling of the for-each style of operations.

 Example:  


@FunctionalInterface

package in.co.bitbyte.java8;

public interface Developer {

public void writeReadableCode();

}

 Implementation of Functional Interface(without lambda expression):


package in.co.bitbyte.java8;

public class Test {

public static void main(String[] args) {

Developer d = new Developer() {

@Override

public void writeReadableCode() {

System.out.println(“At bitbyte, developers  think simple”);

}

};

d.writeReadableCode();

}

}

Implementation of Functional Interface(with lambda expression):


package in.co.bitbyte.java8;

public class Test {

public static void main(String[] args) {

Developer d = () -> {

System.out.println("At bitbyte developers think simple");

};

d.writeReadableCode();

}

}

 This feature changing the way that code is written. Two primary reasons to change the style of coding:

Added new syntax elements that expressive power of the language.

In addition to this added new capabilities to the API library, a big step into the collection API for iteration.

Syntax:

Lambda operator:         (parameters)  -> {actions}

The left side of lambda operator indicates “parameters” right side of the lambda operator lambda body specifies the “actions” need to be performed by the lambda expression.

Lambda expressions are not executed on its own. It works with the implementation of the functional interface.

Before lambda expression, we used the anonymous inner class to implement a functional interface (Single Abstract Method). So many built-in interfaces in Java 7 Runnable, Comparable and so on… Java 8 called this interfaces as functional interface some of the added functional interfaces are BiConsumer, Bi

Example:


package in.co.bitbyte.java8;

public class TestingBuiltInFunctionalInterface {

public static void main(String[] args) {

Runnable r = new Runnable() {

@Override

public void run() {

System.out.println("I am from run method of Runnable interface using anonymous inner class");

}

};

r.run();

}

}

We can implement the above same Runnable interface by using the lambda expression in a very simple way.

Example:


package in.co.bitbyte.java8;

public class TestingBuiltInFunctionalInterface {

public static void main(String[] args) {

Runnable r = () -> {

System.out.println("I am run method from Runnable interface using lambda expression");

};

r.run();

}

}

In the above example, we didn’t mention the method name of the interface because in the functional interface having exactly only one abstract method. We implemented the functional interface using the lambda expression.

If we want to do iteration in the collection, we will do iteration one of the following way.


package in.co.bitbyte.java8;

import java.util.ArrayList;

import java.util.List;

public class Ecommerce {

public static void main(String[] args) {

List list = new ArrayList();

list.add("Hybris");

list.add("ATG");

list.add("DemandWare");

list.add("Intershop");

for(String ecommerceTech : list)

{

System.out.println(ecommerceTech);

}

}

}

But the lambda expression defines a new style for the for-each operation. The main advantage here is we can achieve parallel processing. Without lambda, expression iteration is like processing each element.

Example:


package in.co.bitbyte.java8;

import java.util.ArrayList;

import java.util.List;

public class Ecommerce {

public static void main(String[] args) {

List list = new ArrayList();

list.add("Hybris");

list.add("ATG");

list.add("DemandWare");

list.add("Intershop");

list.forEach(ecommerceTech ->{System.out.println(ecommerceTech);});

}

}

Java 8 | Functional Interface

An interface which is having only one abstract method then it is called as a functional interface. (only one abstract method, one or more default methods or static methods)

Example:

package in.co.bitbyte.java8;

@FunctionalInterface

public interface Mobile {

public void makeCall();

}

We can use the annotation @FunctionalInterface to declare the interface as a functional interface. If it is not valid functional interface, Compiler will throw an error.

This annotation is optional. The compiler will consider interface as a functional interface if it contains exactly one abstract method.

Uses:

  • The functional interfaces are used extensively in lambda expressions.
  • The functional interface acts as a function. We can pass the interface as a parameter this is the functional programming approach.
  • So many interfaces in Java are functional interfaces (built in functional interfaces) like Comparator, Runnable and so on.
  • The main advantage of using functional interface is backward compatibility.

Note: we can declare abstract methods that are overriding the public methods of Object class. These methods did not consider as abstract methods in a functional interface. [Reason behind this thing is any implementation of the interface will have an implementation from Object class]

Example:

package in.co.bitbyte.java8;
@FunctionalInterface
public interface Mobile {  

public void makeCall(); 

public String toString(); 

boolean equals(Object obj);

static useInternetServices()
{
  System.out.println("use whats app");
}
default void mailServices()
{
System.out.println("Use e-mail service");
}

Java 8 | Default methods in interface

Every developer in office is instructed to write no-nonsense code. That’s a protocol.

So when there is no exception, why should every developer create their own creative ways to code. Every one should follow a consistent methodology. Let that manager of your’s define the PMDs for you. I know you will gonna hate it. But then…

It makes sense to have some non abstract methods in an interface. This may be conveniently called default implementation.

Java 8 let you do this. Now you can define a default implementation, which is available to all implementing classes.

Below is a sample.

Interface

package com.bitbyte;

public interface Developer {
	
	public void writeReadableCode();
	
	default void thinkSimple(){
		System.out.println("At bitbyte, Developers think Simple");
	}

}

Implementing class

package com.bitbyte;

public class JavaDeveloper implements Developer {

	@Override
	public void writeReadableCode() {
		System.out.println("Please write Simple and readable code");
	}
}

Client Class

package com.bitbyte;

public class Client {

	public static void main(String args[]) {

		JavaDeveloper coolDeveloper = new JavaDeveloper();
		
		// abstract method call
		coolDeveloper.writeReadableCode();
		// Non abstract method call
		coolDeveloper.thinkSimple();
	}
}

Since you always have a jackAss in team, who still want his own implementation. He can do so.


package com.bitbyte;

public class CoolDeveloper implements Developer {

	@Override
	public void writeReadableCode() {
		System.out.println("Please write Simple and readable code");
	}
	
	@Override
	public void thinkSimple() {
		
		System.out.println("I am cool myself. I know what i am doing!!!");
		
	}
}

How to submit a form to Hybris from external application

Gate crash is embarrassing, back door entry is risky. Great is to be welcomed by a friend inside the party, when you are not invited.

Recently, i came to a situation, where i wanted to submit a form to hybris from a application. I thought it would be easy, and all i need is to do a post to a URL.

Booom. It came out with a flat Bad or missing csrf value error.

Once i thought, perhaps i am trying to breach the hybris security. Since there is a contract between client (browser) and the server (hybris) to exchange information. To keep this information just between them, a shared private token is used. This token, known as csrf token, is bound to a session.

@sumitg88 talked about it one of his blog.

Bypassing a request from security layer is one thing. What i wanted was to go through the security layer, and still be able to submit a form, from outside the spring context of Hybris storefront.

I created an API in storefront, which can pass a csrf-token for the current session. The current session can be opened by application, by hitting the home page, may be in an iframe, or through a java program in backend.

Hybris forcefully adds a csrf token inside a hidden field, in every spring mvc form. You can see this happening by going to html source of a page with form. This token is actually validated against the session token to allow a request to pass to the services.

hiddenFields.put(CSRFTokenManager.CSRF_PARAM_NAME, CSRFTokenManager.getTokenForSession(request.getSession()));

In Html forms you can see:

      <input type="hidden" name="CSRFToken" value="0b4eefff-1a05-4bdb-843a-fa9598633dab">

Our API could give the same csrf token, which we can pass through our form in external application. This way, Hybris will take this request as a valid one, and we can submit the form.

The API could look like below:

      public static String getTokenForSession(final HttpSession session)
	{

		// cannot allow more than one token on a session - in the case of two requests trying to
		// init the token concurrently
		Enumeration<String> enumeration=session.getAttributeNames();
		String csrfTokenAttr=null;
		String token=null;
		while(enumeration.hasMoreElements())
		{
			String attrName=enumeration.nextElement();

			if (attrName.contains("CSRFTokenManager.tokenval"))
			{ 
				csrfTokenAttr=attrName;
			}
		}
		synchronized (session)
		{
			token = (String) session.getAttribute(csrfTokenAttr);
			if (null == token)
			{
				token = UUID.randomUUID().toString();
				session.setAttribute(csrfTokenAttr, token);
			}
		}
		return token;
	}

Once you have a valid token, from one of the session, you can submit any form smoothly.

Enjoy!!!!

Hot Deployment – Hybris

Introduction

In this tutorial I will be covering the configuration of JRebel with Hybris. With JRebel configured you will be able to modify java source classes and compile them on the fly.

“No need to build and start the server again and again”

The configuration is very simple, just 3 steps and you are good to go!

Step 1

  • Download JRebel: Archive can be downloaded from the below link http://zeroturnaround.com/software/jrebel/download/prev-releases/
  • Extract the zip file at a location of your preference, for eg: C:/jrebel
    unzip
  • Active JRebel:
    – Go inside bin folder of JRebel.
    – Start the activation utility by running “activate-gui.cmd” file.
    – It will open a Jrebel activation window. The window will contain 2 tabs:
    Try JRebel    for free and I already have a license.Choose Try JRebel for FREE and fill the basic information.

jrebelfreeform
OR
Buy a license and fill the information in the I already have a license section.

Step 2

  • Add the below given property in local.properties file
    tomcat.javaoptions=-agentpath:C:/jrebel/lib/jrebel64.dll
    ** change the version of the jrebel[XX].dll according to the machine specifications.

 Creation of rebel.xml file:
– You will be required to add the rebel.xml file in the resource folder of each extension.

rebel.png

– Create a new rebel.xml class and copy/paste the below given content into the file:

<?xml version=”1.0″ encoding=”UTF-8″?>
<application xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xmlns=”http://www.zeroturnaround.com&#8221; xsi:schemaLocation=”http://www.zeroturnaround.com http://update.zeroturnaround.com/jrebel/rebel-2_1.xsd”&gt;
<classpath>
<!– Make sure to replace Absolute_Path with your concrete values –>
    <dir name=”{Absolute_Path}/classes”/>
</classpath>
</application>

**   The absolute path should be the complete path to the classes folder.
Example: C:/hybris/bin/custom/demo/demofacades/classes

***The classes folder is the compiled source folder of Hybris and not IDE’s(eclipse).

Step 3

  • Change the IDE(eclipse) compile output path in “.classpath” file of the extension.classpath.png
    TO
    classpath1.png
    Path structure:
    path.png
    All the configurations are completed.You just need to recompile the code from IDE(eclipse) after making the changes in the Java source file.For Eclipse you need to do the below mentioned step:

    • Just go to Project -> Clean
    • Select “Clean projects selected below” option and select the extensions which contains the modified java source classes.
    • Select “Start build immediately”.
    • Select “Build only the selected projects”.
    • Press OK and you are done!