0% found this document useful (0 votes)
279 views438 pages

Hybris Developer Training Guide

The hybris platform allows developers to schedule automated tasks called CronJobs. CronJobs can be configured to run at specific times or intervals and are used to perform periodic tasks like backups, catalog updates, imports/exports, and price recalculations. The course will cover an overview of CronJobs, how they are configured and implemented in hybris.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
279 views438 pages

Hybris Developer Training Guide

The hybris platform allows developers to schedule automated tasks called CronJobs. CronJobs can be configured to run at specific times or intervals and are used to perform periodic tasks like backups, catalog updates, imports/exports, and price recalculations. The course will cover an overview of CronJobs, how they are configured and implemented in hybris.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 438

hybris Developer Training Part I - Core Platform

The hybris Software Developer track expands participants' knowledge of the underlying technical capabilities
of the hybris platform. Participants require a solid knowledge of Java and the Spring framework as well as
common tools such as Eclipse and Ant. The aim of the course is to give developers a set of tools and
techniques that enable them to effectively extend and enhance the hybris framework.

1.1.1. Duration
The course is designed as a four days training track.

1.1.2. Course Description


The training course concentrates on important programming aspects within the hybris Platform. With
extensive hands-on segments, it covers development topics such as development environment set up, data
modeling, data import and export using ImpEx, hybris Management Console customization, ServiceLayer
programming, as well as Web Service API and Cockpit framework programming. It also focuses on the
important topics of Validation, Workflows, and the Process Engine.

The course is based on the hybris Development Trail found in the hybris Wiki. During the course the
participants will use best-practice software engineering concepts and strategies, such as test driven
development (TDD).

1.1.3. Requirements

Knowledge Requirements Excellent knowledge in Java Programming.

Very good knowledge in Spring framework and Eclipse

Technical Prerequesites Every participant needs a computer

(dual core CPU, 8 GB memory, 3 GB of free hard disk space)

Internet connection

hybris Wiki account

Pre-installed Software Most recent Java Development Kit 7

Most recent Eclipse SDK + Web Tools Platform

No virtual machines
hybris Developer Training Part I - Core Platform Part I Core Agenda
th
V 5.0 13 June 2013

page 2 of 4

Please make sure to periodically consult hybris Wiki for updated information regarding training
agenda and supported software.

Modules which contain hands-on parts based on hybris Development Trail are marked with “(T)”.

Link to the trail in the Wiki: https://wiki.hybris.com/display/tr50/hybris+Developer+Training+Trails+-


+Part+I+Core

Wiki account required.

1.1.4. Warm-Up
 Introduction
 Online Resources
 Product Line
 Support & Release Strategy
 Architecture overview
 Spring overview

1.1.5. Development Environment Setup (T)


Covers the Trails ”Preparation“, “Goal“, and ”New Extension“

 Installing the hybris Multichannel Suite


 Build Framework
 Basic Configuration
 Bundled servers
 Server start modes & hac
 Initialization and Update
 Extension Concept
 Eclipse Integration

1.1.6. Data Modeling with hybris Type System (T)


Covers the Trails “New Data Model”, “New Data Model II”
 Introduction to the Type System
 Relations

1.1.7. hybris Management Console (T)


Covers the Trail “Integrating in the hMC”
 hybris Management Console
 Overview of the hMC
 Storing Layout Configuration
 hMC Localization
 Type System Localization

Page 2 of 4
1.1.8. PCM Basics
 Internationalization
 Catalogs
Part I Core Agenda
 Media Management in hybris
th
V 5.0 13 June 2013

page 3 of 4

1.1.9. Flexible Search


 Overview
 Syntax
 API examples

1.1.10. Import and Export (T)


Covers the Trail “Populating the Data Model”
 Overview
 Syntax & examples
 Invoking

1.1.11. Programming with the ServiceLayer (T)


Covers the Trails “Testing the Data Access Objects”, “Testing the Service”, “Service-Overview,
“Testing the Facades”, “Service interceptors” and “Events”
 Architecture of the ServiceLayer
 Services
 Models
 Interceptors
 Events

1.1.12. Java Bean (T)


Covers the Trail “Frontend”
 Overview

1.1.13. CronJobs (T)


Covers the Trail “CronJob”
 Overview

1.1.14. Cockpit Framework (T)


Covers the Trail “Cockpit Basics”
 Theoretical Background
 Layout Configuration

1.1.15. Workflows (T)


Covers the Trail “Workflows”
 Overview
 Working with workflows

Page 3 of 4
1.1.16. Security (T)
 Basics
 Type-Based Access Rights
Part I Core Agenda
 Item-Based Access Rights
th
 Restrictions V 5.0 13 June 2013

 Spring security page 4 of 4

1.1.17. Transactions
 Overview
 Examples

1.1.18. Cache
 Overview

1.1.19. Validation
 Data Validation Framework
 Validation service
 Administration cockpit
 Cockpit integration

1.1.20. Process Engine (T)


Covers the Trail “Process Engine”
 Architectural Overview
 Features
 Business analysis
 Creating a process
 Task extension

1.1.21. Accelerator
 Overview
 Benefits
 Features
 A long term vision

Page 4 of 4
1
2

hybris Developer Training Part I - Core Platform

Generation of Java
Beans
3

Overview

hybris Developer Training Part I - Core Platform


Overview Java Beans Overview 4

Java Beans are used as transport objects for the frontend layer

Contain an abstraction of models (subset of attributes from models)

Are automatically generated

Their class name, attributes or superclass are defined in xml


configuration file

Each extension may provide a bean configuration file

Definitions of these Java Beans or Enums are merged across


extensions.
A declarative approach Java Beans Overview 5

Generate Java Beans out of a configuration file

<bean class="org.training.data.MyPojo">
<property name="id" type="String"/>
</bean>

public class MyPojo implements


java.io.Serializable
{
private String id;

public MyPojo()
{
// default constructor
}
...
}
Why? Java Beans Overview 6

Merge attributes into existing beans


Useful as DataObjects used by Frontend layer

extension1-beans.xml extension2-beans.xml
<bean class="org.training.data.MyPojo"> <bean class="org.training.data.MyPojo">
<property name="id" type="String"/> <property name="flag" type="boolean"/>
</bean> </bean>

Triggered through: ant all


public class MyPojo implements
java.io.Serializable
{
private String id;
private boolean flag;
public MyPojo()
{
Generated to // default constructor
platform/bootstrap/gensrc }
...
}
Templates Java Beans Overview 7

Generation templates are velocity scripts


<bean ... template=“resource/mypojo-
template.vm">
Default templates:
bean: global-beantemplate.vm
enum: global-enumtemplate.vm
Create a new template
my-template.vm
package $packageName;
#foreach ($i in $imports)
import $i;
#end
Templates implementation Java Beans Overview 8

Implementation
<bean class="org.training.data.MyPojoExtended"
template="resources/my-template.vm”/>
<property type="boolean" name="custom" />
<property name="segment"

type="org.training.enums.TestEnum"/>
</bean>

More info
wiki.hybris.com/display/release5/
Generating+Beans+and+Enums
9
1
2

hybris Developer Training Part I - Core Platform

CronJobs
3

Overview

hybris Developer Training Part I - Core Platform


CronJobs – Key Facts CronJobs Overview 4

Automated tasks

Performed at a certain time (such as 16:05), or at fixed


intervals (such as every five minutes)

Can be used for:


Backups
Updating / synchronizing catalog contents
Imports / Exports
Re-calculating prices
etc…
CronJobs – Key Facts (2) CronJobs Overview 5

A CronJob consists of a:
Job: What to do
Trigger: When to run
CronJob: Runtime information

Allows re-using code and


items

CronJobs always run in a


SessionContext (i.e. they
have a user assigned)
How to create a CronJob CronJobs Overview 6

Step 1 – create job logic:


public class MyJob implements JobPerformable<CronJobModel>
{
public PerformResult perform(final CronJobModel cronJob)
{
//the logic
}
}

Step 2 – register it as spring bean:


<bean id="myJob" class="my.package.MyJob"/>
How to create a CronJob (2) CronJobs Overview 7

Step 3 – create items: job, cronJob and trigger items


Run a system update with only essential data checked – for each bean of type
JobPerformable a Job item is being created.
INSERT_UPDATE CronJob;
code[unique=true];job(code);singleExecutable;sessionLanguage(isocode)
;myCronJob;myJob;false;de

INSERT_UPDATE Trigger;cronjob(code)[unique=true];cronExpression
; myCronJob; 0 0 0 * * ?

Equivalent to running system update is to run such script:


INSERT_UPDATE ServicelayerJob;code[unique=true];springId
;myJob;myJob

To start cronJob immediately after it’s creation, add this line at the end:
#% afterEach: impex.getLastImportedItem().setActivationTime(new Date());
How to start a CronJob CronJobs Overview 8

Using Impex
#% afterEach: impex.getLastImportedItem().setActivationTime(new Date());

Using the hMC

Using Ant

ant runcronjob -Dcronjob=myCronJob

Using the API


cronJobService.performCronJob( myCronJobModel );
Useful CronJob properties CronJobs Overview 9

Email template
notify certain user using given email template

Enable code execution


enable or disable BeanShell

User
to empower restrictions

Node id
to specify server for job execution
10
1
2

hybris Developer Training Part I - Core Platform

Cockpit Framework
3

Theoretical Background
Layout Configuration

hybris Developer Training Part I - Core Platform


hybris Cockpits – Basic Ideas and Motivations Theoretical Background 4

New UI feeling
Cockpit has to feel like a Fat Client (Rich Internet Application)
No request / response

Work-process oriented
Mass data editing
Speed up daily tasks
Seamless Workflow integration
hybris Cockpits – Key Facts Theoretical Background 5

Perspectives for role-oriented usage


Manage and structure product information and catalogs in high-
volume and collaborative environments
Drag and drop functionality (e.g. for reorganizing catalog structures)
Undo
Jump-in URLs (CMS welcome page, migros intranet search)
Access rights for perspectives
Celum integration
Classification attributes
Data export (csv export of search results)
New concept for browser tabbing
Additional editors (list editor, media editor, range editor)
Dynamic columns in list view (classification attributes, variant
attributes)
Workflow Integration: workflow actions with attached products can be
handled
hybris Cockpits – Using Standards Theoretical Background 6

Designed to create rich internet applications (RIA)


Ajax-based event-driven mechanism
Configuration in ZUML (ZK User Interface Markup Language)
Rich selection of GUI components available
hybris Cockpits – Technical Key Facts Theoretical Background 7

Base framework for all cockpit applications


Extension in platform
All cockpit applications extend base cockpit framework

Standard frameset for cockpit user interfaces

Common pool of components for all cockpit applications


Reusable UI components like value editors, lists, section panels

Generic services and functionality


Workflow integration
Synchronization integration
hybris Cockpits – Creating a Custom Cockpit Theoretical Background 8

Part of the hybris Multichannel Suite:


A 'ycockpit' extension that can be used with our extension template mechanism to
create a fresh template in seconds
All needed libraries included. Just start developing!
A standard Security framework to protect different perspectives
'Excel-like' editing
Reusable hybris components on top of the existing ZK components
Cell editors for all hybris data types including reference editors
hybris Cockpits – Levels of Customization Complexity Theoretical Background 9

Easy Customization
Configure editor area/list view Browser
Area
Configure the advanced search
Configure base setting for search and
labels of all kinds

Medium Customization
Add own editors for all view types
Add custom section to editor area or
Navigation Context Editor
navigation area
Area Area Area
Add custom column to list view

Expert Customization
Customize type service and
change default types
Implement own perspective
by customizing all areas
Set up own Cockpit application
10

Theoretical Background
Layout Configuration

hybris Developer Training Part I - Core Platform


Editable And Customizable Layout Configuration 11

3-11

Browser Area
Navigation Editor
Area Area

Context Area
Configuration Schema Layout Configuration 12

consists of returned to

Cockpit Cockpit components Java object with


configuration

request converts XML into


configuration
from

looks up and
assembles

Configuration factory Component configuration (XML)


Overview Layout Configuration 13

XML configuration
3 different scopes
Per principal
Per component and context
Per type or subtype

Subtyping
Subtype item type without data model changes
Write own view configuration for subtype

wiki.hybris.com/display/release5/Configuration+of+the+Cockpit+UI
Different View Configurations for the Same Item Type Layout Configuration 14
Configuration Details Layout Configuration 15

The configuration for a cockpit is stored in XML files.


These XML files are backed by XSD files. For a list of cockpit
elements, you can refer to /bin/platform/ext/cockpit/resources.
The exact configuration for a specific cockpit element can depend on
the constellation of user, cockpit element and type of item.
There are several similarities between configuring a cockpit and
configuring the hybris Management Console:
Configurations are stored in several XML files
Configurations can be user- and usergroup-specific

But there are also differences:


Cockpits use a much bigger number of XML files (one for each constellation)
Cockpit files are assembled at runtime
UI localization strings for cockpits can be specified directly in an XML file
Configuration Details (2) Layout Configuration 16

In addition to configurations specific to certain areas (such as the grid


view), there is also a base configuration. This is used as the most
basic configuration
The cockpit framework uses an inheritance mechanism for
configuration in which more specific configuration overrides more
general configuration
The exact configuration for a cockpit component is assembled from all
the relevant XML fragments, then converted into a Java object using
JAXB, and then returned to the component
Example of Editor Area Layout Configuration 17

<editor>
<group qualifier="General" visible="true" initially-opened="true">
<label key="cockpit.config.label.General" />
<property qualifier="product.code" />
<property qualifier="product.catalogversion"
editor="shortListEditor">
<parameter>
<name>allowCreate</name>
<value>true</value>
</parameter>
</property>
<property qualifier="product.description" editor="wysiwyg"/>
</group>
</editor>
Accessing Classification Attributes Layout Configuration 18

<group qualifier="general" visible="true">


<label key="cockpit.config.label.General" />
<property qualifier="product.code"/>
<property qualifier="product.name"/>
...
<property qualifier="SampleClassification/1.0/cpu.fsbSpeed"/>
<property qualifier="SampleClassification/1.0/cpu.clockSpeed"/>
...
</group>
Using Properties of Referenced Types Layout Configuration 19

<base>
...
<search-properties>
<property qualifier="CatalogVersion.version"/>
<property qualifier="CatalogVersion.catalog.name"/>
</search-properties>
...
</base>
20
1
2

hybris Developer Training Part I - Core Platform

Next Generation Cockpit


3

Overview
Widget development
Application orchestrator

hybris Developer Training Part I - Core Platform


The Next Generation Cockpit Framework Cockpit NG Overview 4

One single application for managing “everything”

Business role/process-centric

Reusable & Extensible

Runtime configurable

Platform independent
Key concepts Cockpit NG Overview 5

One single backoffice application built using a set of widgets.

By combining and connecting widgets, an application can be designed


and put together in no time, using the Application Orchestrator.

Every widget instance can have its own settings, connections with other
widgets and UI configuration.

The set of widgets available to a business user and their tasks can be
mapped to their business role by assigning him to the right usergroup.
Framework extensions Cockpit NG Overview 6

backoffice extension:
backoffice framework with standard widgets
Single web application for all backofice applications
Main backoffice application that is available to all backoffice users.
Accessible by default at http://localhost:9001/backoffice
The application UI depends on user business role.
Contains Application Orchestrator for live modification of your backoffice UI

ybackoffice extension template


Template that you can use to generate your custom backoffice extensions.
In the custom extension, you can implement your own components that are reusable
in the Application Orchestrator to add them to the backoffice application.

Each ybackoffice module extension will contribute to one backoffice application,


accessible under above link
The background of cockpit NG behavior 7

There’s one (spring) application context for all ybackoffice module


extensions

Widgets from each ybackoffice module extension are available in


application orchestrator. Not part of backoffice UI but waitining in
repository, ready to be used in application orchestrator.

Widgets added to {ext.name}-backofice-widgets.xml are going to


be added to the backoffice application setup Part of backoffice UI.

Each bean defined in {ext.name}-backofice-spring.xml is going


to be available from within widget controller of any widget.

All beans defined in global (tenant) application context (services, etc.)


are available in the backoffice application context
Widgets Cockpit NG Overview 8

A widget is a stand-alone, deployable component with a clearly defined


interface and a specific purpose.
A Widget definition describes a widget type, its ID and name, its view and
controller classes. Also any additional settings specific to that widget
A widget used in an application is an instance of a widget definition.
Widget communication Cockpit NG Overview 9

To have a meaningful backoffice application, the widgets have to communicate with


each other.
A widget can have inputs and outputs which are called sockets. A socket has an ID
and a type definition. This helps with compatibility checking, when connecting two
widgets.
Every widget instance has representation for each connection established between
two widgets. Such widget connection has references to the source and the target
widget as well as IDs of input and output socket.
10

Overview
Widget Development
Application Orchestrator

hybris Developer Training Part I - Core Platform


What constitutes a Widget? Widget Development 11

Widget definition (definition.xml)


Component interface i.e. inputs and outputs
Other meta info e.g. controller class, view file, author, name

Widget view (.zul)


Standard ZK XML syntax with added hybris tags
Change and refresh browser. No compile required!

Controller
Java class containing business logic
Standard syntax allowing you to react to inputs and component events
Example widget definition: Product List Widget Development 12

definition.xml

<widget-definition id="org.mybackoffice.widgets.productlist">
<name>Product List</name>
<defaultTitle>List</defaultTitle>
<view src="productlist.zul" />
<controller class="com.widgets.ProductListController" />

<sockets>
<input id="products" type="com.hybris.product.data.ProductData"
multiplicity="LIST" />

<output id="selectedProduct"
type="com.hybris.product.data.ProductData" />
</sockets>

<settings>
<setting key="list" default-value="false" type="Boolean" />
</settings>
</widget-definition>
Example widget view: Product List Widget Development 13

productlist.zul OR view.zul

<widget xmlns="http://www.zkoss.org/2005/zul"
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance>

<div id="gridContainer" sclass="yw-pageablelist-gridcontainer"


if="${!widgetSettings.list}">
</div>

<div sclass="yw-simplelist“ if="${widgetSettings.list}>


<listbox id="gridList" emptyMessage="${labels.emptylist}" />
</div>

</widget>
Example widget controller: Product List Widget Development 14

public class ProductListController extends DefaultWidgetController


{
private Listbox gridList;

@SocketEvent(socketId = “products”)
public void setProducts(final List<? extends Object> products)
{
gridList.setModel(new SimpleListModel(products));

// do other cool things…


}

@ViewEvent(componentID = “gridList”, eventName = Events.ON_SELECT)


public void selectProduct(final SelectEvent<Component, ProductData>
event) {
final Set<ProductData> selectedObjects = event.getSelectedObjects();
sendOutput(“selectedProduct”, selectedObjects.iterator().next());
}
}
Example widget: Product List Widget Development 15
Example widget connection: Product Detail Widget Development 16

definition.xml

<widget-definition id="org.mybackoffice.widgets.productdetail">
<name>Product Detail</name>
<defaultTitle>Details</defaultTitle>
<author>hybris</author>
<version>0.1</version>

<view src="productdetail.zul" />


<controller class="com.widgets.ProductDetailController"/>

<sockets>
<input id="selectedProduct”
type=”com.hybris.product.data.ProductData"/>
</sockets>
</widget-definition>
Example widget: Product Detail Widget Development 17
Actions & Editors Widget Development 18

Actions
Actions are used to trigger some action depending on the state of widget model
property.
For example you want to have an icon that will show in the widget once some specific
property has specific value.

Editors
Editors are used to properly handle different types of data for editing.
For example you want to have a text box that will show the value of some type, of some
widget model property.
Backoffice – UI Configuration Widget Development 19

UI configuration is responsible for the configuration of user interface. Here you


define UI of each widget instance. There are three different versions of this
configuration respected in the following order:
${HYBRIS_DATA_DIR}/backoffice/config/cockpit-config.xml: Merged configuration of
the whole backoffice application. You can modify it during run time from the
application orchestrator.

mybackoffice/backoffice/resources/mybackoffice-backoffice-config.xml: Configuration
of components on the mybackoffice extension level.

mybackoffice/backoffice/resources/widgets/mywidget/cockpit-config.xml (optional):
Configuration of your widget. You can consider is as a default configuration of your
widget.
Backoffice – Application configuration Widget Development 20

Application configuration holds information about all widgets added to your


application, keeps information things like viewing restriction and sockets
connections. There are two different versions of this configuration respected in the
following order:
${HYBRIS_DATA_DIR}/backoffice/config/backoffice-widgets.xml: Merged configuration
of the whole backoffice application. You can modify it during run time from the application
orchestrator.

mybackoffice/backoffice/resources/mybackoffice-backoffice-widgets.xml: Configuration
of components on the mybackoffice extension level.
21

Overview
Widget development
Application orchestrator

hybris Developer Training Part I - Core Platform


Application Orchestrator – key features 22

Accessible by pressing F4 key in the backoffice application


only for administrators.
Add, remove and connect widgets, perspectives and other
components
Add or change settings of a widget instance
Connect widgets using their sockets
Manage UI localization by providing values for labels.
Manage access restrictions (allowed roles)
Access and reset application configuration (widgets.xml) and UI
configuration (cockpit-config.xml)
Inspect application mash-up and communication flow
Consits of two views
Main view Application Orchestrator 23

The main widget view is a place where you should add widgets and design a
mash-up of your application. Here you can see two types of components,
widgets and slots/children.
Symbolic widgets view Application Orchestrator 24

The symbolic widgets view helps to get an overview on the mash-up of your
application. It shows how each widget depends on each other and how
connections are established. Here you can also add widgets.
25
1
2

hybris Developer Training Part I - Core Platform

Workflows
3

Overview
Data Model
Working with workflows
Automated steps

hybris Developer Training Part I - Core Platform


Overview Workflow Overview 4

The hybris workflow extension enables modelling and


processing workflows which are usually backoffice related
user interaction
A workflow can represent:
Complex processes with multiple tasks and users
Creating a new product in the catalog
Handling customer complaints
Quote negotiation (B2B)

Single and easy tasks which can be assigned to a backoffice user


Changing the image of a product
Workflow Module – Key features Workflow Overview 5

Design human and system based workflows

Start a workflow via hybris CronJobs

Allocate users and user groups to certain tasks

Comment on the task

Add task-relevant attachments

Get real-time notification via e-mail

Track a workflow

Cockpit & Process Engine Integration


6

Overview
Data Model
Working with workflows
Automated steps

hybris Developer Training Part I - Core Platform


Workflow Workflow Overview 7

Technically workflows are CronJobs

Generated out of a workflow template

Might have attached items


WorkflowTemplate Workflow Overview 8

Template for a real workflow

Defines workflow structure through


WorkflowActionTemplates
WorkflowAction Workflow Overview 9

Concrete task the assigned principal has to do

Principals should work on the task and

Finish the action by choosing a decision

Gets activated through incoming decisions (AND, OR)


WorkflowActionTemplate Workflow Overview 10

Action definition in a workflow template

Partial order between WorkflowActionTemplates through


WorkflowDecisionTemplates

Each WorkflowActionTemplate has an assigned principal


11

Overview
Data Model
Working with workflows
Automated steps

hybris Developer Training Part I - Core Platform


Modeling a Workflow Workflow Overview 12

Through API

Create WorkflowTemplateModel, ... (Service Layer)

ImpEx

hybris Management Console (hMC)


Starting a Workflow Workflow Overview 13

Through API

WorkflowService: creating, monitoring, ...

WorkflowProcessingService: starting, terminating, ...

Activation Script

Evaluated each time an items is created, saved, removed

Access to item, type, initial values and / or current values

Manually through UI (cockpit) if user is in


visibleForPrincipals
Displaying Workflows Workflow Overview 14

In Product Cockpit

Workflows for the current user


15

Overview
Data Model
Working with workflows
Automated steps

hybris Developer Training Part I - Core Platform


Automated steps in a workflow Workflow Overview 16

Use automated steps if no manual interaction is needed

Any service layer business logic

Implementation steps

1. Implement interface AutomatedWorkflowTemplateJob

2. Create a bean

3. Any implementing class gets added automatically to


AutomatedWorkflowTemplateRegistry during server start-
up
Quiz Questions Working with Workflows 17

Imagine you want to create a workflow for assigning a


Car to each newly created Employee. What do steps you
would have to do
The assignment task should be done by admin

Admin can also decide to let the Car being assigned automatically
References Working with Workflows 18

https://wiki.hybris.com/display/release5/workflow+Extension+-
+Technical+Guide

https://wiki.hybris.com/pages/viewpage.action?pageId=141793777
19
1
2

hybris Developer Training Part I - Core Platform

Security
3

Basics
Type-Based Access Rights
Restrictions
Spring security
Custom Access Rights

hybris Developer Training Part I - Core Platform


Security areas to consider Security Basics 4

Web access control


IP range
Spring security per web app

Administration rights
hac access

Data permissions
Role based
Type and Item

Database security
Transparent symmetric encryption
Field encryption
Limiting DB user rights
Basics Security Basics 5

User accounts in the hybris Multichannel Suite can be individual


people or roles:
who is allowed or is not allowed to authenticate against a part of the application
who is allowed or is not allowed to perform specific tasks

PrincipalGroup defines UserGroup, Company


Company: Unlike UserGroups, Companies
can hold addresses

User defines: Employee, Customer

Default user accounts and groups


that cannot be removed:
anonymous (Customer)
admin (Employee)
admingroup
Where Do User Accounts Affect the hybris Multichannel Suite? 6

JaloSession
At any given time, a user must be assigned to the JaloSession
hybris Management Console
The hMC displays (or hides) elements depending on the user and the user groups
the user belongs to
Cockpits
In addition to user-specific configuration, Cockpits also have workflow integration
and can let users manage workflow steps
Web Services
The hybris Web Services system allows user-specific access rights
Order Process
A customer must log in to insure that the shopping cart is assigned to an individual
person.
Addresses
The reference to a user account is mandatory
CronJobs
CronJobs use a JaloSession and therefore also require that a user be set
7

Basics
Type-Based Access Rights
Restrictions
Spring security
Custom Access Rights

hybris Developer Training Part I - Core Platform


Type-Based Access Rights – Overview Type-Based Access Rights 8

Access rights for hybris types and their attributes


Access is granted to individual users and/or user groups
Affect the entire type, not individual items
Also can affect individual type attributes
Effective in the hMC, hybris Cockpits and web services
The entire type or attribute will be hidden from display to the user
account

Advantages Disadvantages

Attribute-based Affect the entire type, not


just individual instances
Can be imported from and Not effective everywhere
exported to Excel easily (for example, on the
ServiceLayer)
Importing Type-Based Access Rights 9

Type access configuration can be imported by impex

$START_USERRIGHTS;;;;;;;;;
Type;UID;MemberOfGroups;Password;Target;read;change;create;remove;change_perm
UserGroup;productManagerGroup;cockpitGroup;;;;;;;
# Access Rights for Products & Catalog;;;;;;;;;
;;;;Product;+;+;+;+;+;
;;;;Product.ean;+;-;-;-;-;
;;;;Catalog;+;;;
;;;;Media;+;+;+;+;+;
$END_USERRIGHTS;;;;;

Full syntax:
wiki.hybris.com/display/release4/ImpEx+API#ImpExAPI-UserRights
API CRUD example Type-Based Access Rights 10

Generic service for checking permission assignments:


permissionCheckingService.checkTypePermission(typeCode,

PermissionsConstants.REMOVE).isDenied();

For typical CRUD permission checking use:


PermissionCRUDService – wrapper over PermissionCheckingService

permissionCRUDService.canReadType( typeCode );
permissionCRUDService.canChangeAttribute( typeCode,

attributeQualifier );
11

Basics
Type-Based Access Rights
Restrictions
Spring security
Custom Access Rights

hybris Developer Training Part I - Core Platform


Restrictions – Overview Restrictions 12

Restrictions / Personalization Rules


Restrictions define a filter which is added to FlexibleSearch
statements at execution time
for the specified type
for a user or a user group.
System-wide effect
Items matching the Restriction will be inaccessible to the user.

Advantages Disadvantages

Take effect for every FlexibleSearch Requires FlexibleSearch syntax knowledge


automatically
Can block access to individual instances of a May require extended knowledge about hybris
type data model
Factory-Predefined Access Rights Restrictions 13

A special set of factory-predefined restrictions and type-based access


rights:
Category
Visibility for certain user groups (such as customergroup), in order to display
the categories in the web frontend
Catalog
Made readable and writeable for certain user groups (such as
catalogmanagergroup)
Language
Made readable and writeable for certain user groups that can have read and
write access to several languages

Advantages Disadvantages

Allows easy rights management for Not very generic approach


many common use cases

Can be used as a starting point for


further customization
Restrictions in cockpits Restrictions 14

In cockpits restrictions are disabled by default

To enable restrictions in cockpits search box:

cockpit.disableRestrictions=false
ImpEx example Restrictions 15

Restrictions can be imported as any other item through Impex:

INSERT_UPDATE SearchRestriction;code;principal(UID);\
restrictedType(code);active;query
;FrontRestriction;customergroup;\
Product;true;{catalogVersion} IN (?session.catalogversions)

( line ending with '\' and the following are a single line in ImpEx file.)
16

Basics
Type-Based Access Rights
Restrictions
Spring security
Custom Access Rights
Spring security Spring Security 17

Spring security framework takes care of:


Restricting access
Delegating authentication and authorization
Remember me services, login pages etc.

Spring security framework is used in:


Cockpits
Accelerators

Each web application has separate security configuration


Spring security (2) Spring Security 18

To enable:
Use spring delegating filter springSecurityFilterChain in your application
web.xml

To configure
Use ‘security’ xml namespace
<security:intercept-url pattern="/my-account*"
access="hasRole('ROLE_CUSTOMERGROUP')"
requires-channel="https" />

For consistent authentication across all extensions use the


coreAuthenticationProvider
public Authentication authenticate(...)
{
User user = getUserByLogin( userDetails.getUserName()
);
Object credential = authentication.getCredentials();
...//verify - compare
}
References 20

Documentation about Principals:


wiki.hybris.com/display/release5/Users+in+the+hybris+Platform

Type-Based Access Rights:


wiki.hybris.com/display/release5/Access+Rights

Restrictions:
wiki.hybris.com/display/release5/Restrictions

Comparison of Access Rights:


wiki.hybris.com/display/release5/Comparison+of+Access+Rights

Configuring User Roles – Best Practices:


wiki.hybris.com/display/release5/
Configuring+User+Roles+in+the+hMC+-+Best+Practices
21

Basics
Type-Based Access Rights
Restrictions
Spring security
Custom Access Rights

hybris Developer Training Part I - Core Platform


Custom Access Rights – Overview Item-Based Access Rights 22

Allows defining very fine-grained access control.

You may define your own permission types.

You can grant or deny permissions to the item instances.

However.. don’t overuse


managing and checking permissions on item level can considerably degrade
performance - huge number of items is involved.

If possible use type-based permissions together with restrictions.

Exposed API allows checking of both Item and Type permissions.


Limitations Item-Based Access Rights 23

Permissions are not automatically enforced.


Your code must invoke a method or two from PermissionCheckingService
By default only Media management SecureMediaFilter uses item-based rights

Permission assignments are calculated hence it’s not possible to


search for the effective permission assignments using a Flexible
Search Query of the form:
return all items that have a permission XYZ granted for principal P.

Permission assignments are currently not represented by models, you


cannot directly import them using the ImpEx scripts.
Use PermissionManagementService from ImpEx using bean-shell scripting.
API example Item-Based Access Rights 24

Create item permission


permissionManagementService.createPermission(permissionName);

Check item permission:


permisionCheckingService.checkItemPermission(item, principal,
permissionName).isGranted();

Add item permission:


new PermissionAssignment(PermissionsConstants.READ, principal);
permissionManagementService.addItemPermission(mediaItem,
permissionAssginment);

More info:
wiki.hybris.com/display/release5/
Managing+and+Checking+Access+Rights
25
1
2

hybris Developer Training Part I - Core Platform

Transactions
3

Overview

hybris Developer Training Part I - Core Platform


Transactions Transactions Overview 4

Transactions are ACID (atomic, consistent, isolated, durable)

Hybris provides implementation of spring PlatformTransactionManager


so you can use:
@Transaction
tx xml schema
TransactionTemplate
Or direct hybris API

The JTA UserTransaction interface is not provided

hybris doesn’t participate in global transactions of multiple systems


Transactions isolation 5

Isolation level is fixed to READ_COMMITED


you can’t change that with @Transactional annotation (ignored)

Nested transactions are supported


inner transaction simply joins outer transaction

Models are persisted without transaction by default:


model.service.transactional.saves=false

More info at:


wiki.hybris.com/display/release5/Transactions
Annotation example Transactions Examples 6

The easiest way to enable transactions in your code

@Transactional(propagation=Propagation.REQUIRES_NEW,
isolation=SERIALIZABLE)
public void provideService()
{
repo1.retrieveFoo();
repo2.retrieveFoo();
}

Notice the isolation level will be ignored!


10
1
2

hybris Developer Training Part I - Core Platform

Cache
3

Overview

hybris Developer Training Part I - Core Platform


Theory Cache Overview 4

Regions based cache


By default: EHCache implementation of region.
Provided: hybris implementation as an option (for backward compatibility)
Each region is configurable:
What types it’s caching
The maximum size
The eviction policy
Each hybris model is cached
Each FS query is cached
Hint: avoid FS queries with small differences (e.g. with new Date())

No master cache server


Each cluster has its own cache
Caches are invalidated either via udp or tcp network messaging
When Data Is Cached (and invalidated) Cache Overview 5

Caching items:
When calling flexible search or getters that refer to ComposedTypes, the
underlying data is returned from the cache or, if not yet cached, first retrieved
and then written to the cache.
When calling modelService.save, the cached value is invalidated (and hence
removed from the cache)

Caching FlexibleSeach results:


When executing FlexibleSearch query like: SELECT code FROM Product the
list of results is cached in the main cache.
When a product is removed, then its item data and the cached flexible search
result for the above query are removed from the cache.
Eviction policies Cache Overview 6

First In, First Out (FIFO): Elements are evicted in the same order as
they come in. When a PUT call is made for a new element, and
assuming that the maximum limit is reached for the memory store, the
element that was placed first (First-In) in the store is the candidate for
eviction (First-Out).

Least Frequently Used (LFU): For each GET call on the element the
number of hits is updated. When a PUT call is made for a new
element, and assuming that the maximum limit is reached for the
memory store, the element with least number of hits, the Less
Frequently Used element, is evicted.

Least Recently Used (LRU): The last used timestamp is updated when
an element is put into the cache or an element is retrieved from the
cache with a GET call.
How Data Is Cached Cache Overview 7

Region Cache – configurable


Standard configuration:
Example of custom cache configuration Cache Overview 8
Custom cache configuration Relations 9

To change preconfigured cache region settings, provide new values in


the local.properties for the preconfigured parameters:

# Size of a region that stores all other, non-typesystem and non-query


objects. Default value is 100000.
regioncache.entityregion.size=50000

# Change eviction policy used by entity region. Possible vales are FIFO
(default), LFU and LRU.
regioncache.entityregion.evictionpolicy=LRU

# specifies root cache folder for all cached files


media.default.local.cache.rootCacheFolder=cache
# specifies max size of media cache in MB
media.default.local.cache.maxSize=500
Cache - cleanup Cache Overview 10

Data is removed from the cache..

When the cache is full - Displacement


When the item has changed – Invalidation
11
1
2

hybris Developer Training Part I - Core Platform

Validation Framework
3

Data Validation Framework


Validation service
Administration cockpit
Cockpit integration

hybris Developer Training Part I - Core Platform


Overview Data Validation Framework 4

The hybris Data Validation Framework is based on the JSR 303 Java
validation specification

It offers an easy and extensible way to validate data

User-friendly and meaningful notifications allow users to provide or re-


enter valid input

Only validated data is passed on to the persistence layer

In contrast to the JSR 303 specification, constraints can be created


and modified at runtime
Overview (continued) Data Validation Framework 5

Constraint definitions are written in Java or XML

Constraint instances are persisted in the hybris database as items

You may define your own constraint types

hybris Data Validation consists of the three following areas:


The Validation Service is a service in the ServiceLayer which defines constraints
and performs data validation

The Administration Cockpit allows you to create and manage constraints

Cockpit integration provides validation feedback to the user


Definition and use Data Validation Framework 6

Administration Cockpit Cockpit Integration

Managing instantiated constraints

Validation
FrameworkValidation Engine
ValidationService
7

Data Validation Framework


Validation Service
Administration Cockpit
Cockpit Integration

hybris Developer Training Part I - Core Platform


Key Features Validation Service 8

The Validation Service loads the validation engine with constraints

Data is validated based on a set of validation constraints

All modelService.save calls are intercepted aborting save operations


where necessary

Validation methods may be called explicitly


Architecture Validation Service 9

Validation is performed by the DefaultValidationService

This service uses a JSR 303-compliant validation engine

The Validation Service contains two groups of methods:


Validation methods to validate items, properties or values

Control methods to alter the behavior of the validation engine


Example Validation Service 10

interface ValidationService {
void reloadValidationEngine();
<T> Set<HybrisConstraintViolation> validate(T object,
Collection<ConstraintGroupModel> g);
<T> Set<“> validateProperty(T object, String propertyName,
Collection<ConstraintGroupModel> g);
<T> Set<“> validateValue(Class<T> beanType, String propertyName, Object o,
Collection<ConstraintGroupModel> g);
void setActiveConstraintGroups(Collection<ConstraintGroupModel> groups);
...}

Example usage:
ProductModel model = new ProductModel();
Set<HybrisConstraintViolation> constraintViolations = validationService.validate(model);
Validation Engine Validation Service 11

The Validation Service is loaded with JSR 303-compliant constraint


instances at run-time
It can be reloaded with new or modified constraint instances
All JSR 303 constraint types are supported
New constraint types may be created but require new files,
recompilation and a system initialization or update.
Constraints Validation Service 12

All JSR 303-compliant validation constraints can be used:

NotNullConstraint Java annotation:


public class User {
@NotNull
private String
firstname; }
OOTB Constraints Validation Service 13

The Data Validation framework provides implementations of all


constraint types defined in the JSR 303 specification:
PatternConstraint
PastConstraint, FutureConstraint
MinConstraint, MaxConstraint
DecimalMinConstraint, DecimalMaxConstraint
SizeConstraint
AssertTrueConstraint, AssertFalseConstraint
IsNullConstraint, IsNotNullConstraint
NotEmpty, NotBlank
XorNotNull Annotation
Dynamic Annotation
Constraint types Validation Service 14

Severity
Each constraint can be assigned an Error/Warning/Info severity level
Error constraints cause a save operation to be aborted
Users may choose to ignore Warning constraints and save anyway

Groups
Constraints can be assigned to zero or more groups (zero = default group)

The engine can be told which constraint group(s) to use for validation

There are attribute, type and dynamic constraints


16.2 Validation Service
Declaring Constraints Dynamically Validation Service 15

Constraints may be declared dynamically


Constraints are treated as hybris Items and are persisted in the hybris database

Constraints are retrieved from the database when the validation engine is loaded

Constraints are encoded in a JSR 303 XML file and loaded into the validation
engine

Because constraints are persistent, the constraint definition needs to be added the
extension’s items.xml file
Declaring Constraints Dynamically (continued) Validation Service 16

reloadValidationEngine():
• Constraints retrieved from
Database
• XML contents generated
• (Re)loaded into Validation Engine
17

Data Validation Framework


Validation Service
Administration Cockpit
Cockpit Integration

hybris Developer Training Part I - Core Platform


Administration Cockpit overview Administration Cockpit 18

List constraints

Reload the validation engine Create and manage constraints


Features Administration Cockpit 19

With the administration cockpit you can:

Create and manage constraints and constraint groups


Filter constraints
List constraint declarations
Reload the validation engine

Although this can also be done with the hMC, we recommend using the
administration cockpit which is more user-friendly and intuitive.
20

Data Validation Framework


Validation Service
Administration Cockpit
Cockpit Integration

hybris Developer Training Part I - Core Platform


Cockpit Integration Cockpit Integration 21

Data validation is integrated into the editing area of cockpits


Users are notified of all validation issues
Quiz questions 22

1. Explain the main features of the hybris Validation Framework and the
three areas of which it consists.

2. Name the specification on which the hybris Validation Framework is


based.

3. Give a short description of the Validation Service architecture.


4. Is it possible to create your own constraint types? If so, how do you
declare a custom constraint type?

5. What happens to a save operation if a constraint violation occurs?


6. What is the Administration Cockpit? What are its primary uses?
References 23

wiki.hybris.com/display/release5/Data+Validation+Framework

jcp.org/aboutJava/communityprocess/final/jsr303/index.html

wiki.hybris.com/display/release5/
Administration+Cockpit+-+Business+Guide
24
1
2

hybris Developer Training Part I - Core Platform

Process and task


engines
3

Architectural Overview
Features
Business analysis
Creating a Process
Task Extension

hybris Developer Training Part I - Core Platform


Architecture of the Process and Task Engines Architectural Overview 4
5

Architectural Overview
Features
Business analysis
Creating a Process
Task Extension

hybris Developer Training Part I - Core Platform


Process Engine Features Features 6

The hybris process engine extension allows you to model, support


and monitor business processes

The process engine interprets a process definition consisting of


nodes and transitions

A process is defined in an XML file and can be run asynchronously

Actions are performed in a certain order and are only carried out if
all predefined conditions are met

You can wait for events, notify users or user groups, fire specific
actions and determine subsequent actions based on action results
8

Architectural Overview
Features
Business analysis
Creating a Process
Task Extension

hybris Developer Training Part I - Core Platform


Business analysis Business Analysis 9

The first step in working with the process engine extension typically
consists of conducting a business analysis

A flowchart permits to define a step-by-step solution to a given


problem:
10

Architectural Overview
Features
Business analysis
Creating a Process
Task Extension

hybris Developer Training Part I - Core Platform


Process definition file Creating a Process 11

The workflow from the analysis is translated into a process definition


XML file:

<process name="Example" start="Action1">


<action id="Action1" bean="Action1">
<transition name="OK" to="Action2"/>
<transition name="NOK" to="Action3"/>
</action>
<action id="Action2" bean="Action2">
<transition name="OK" to="Action4"/>
</action>
<action id="Action3" bean="Action3">
<transition name="OK" to="Action4"/>
</action>
<action id="Action4" bean="Action4">
<transition name="OK" to="success"/>
</action>
<end id="success" state="SUCCEEDED">Everything OK</end>
</process>
Node Types (1) Creating a Process 12

There are several types of nodes:

Action nodes - carry out process logic and permit alternative actions
to be carried out
<action id="isProcessCompleted" bean="subprocessCompleted">
<transition name="OK" to="sendCompletedNotification"/>
<transition name="NOK" to="waitForSubprocessEnd"/>
</action>

Wait nodes - wait for a subprocess or an external process result


<wait id="waitForSubprocessEnd" then="isProcessCompleted">
<event>${process.code}_SubprocessEnd</event>
</wait>
Node Types (2) Creating a Process 13

Notify nodes - inform a user or user group of the state of a process


<notify id="notifyAdminGroup" then="split">
<usergroup name="admingroup" message="Do something!"/>
</notify>

Split nodes - split the process into parallel paths


<split id="split">
<targetNode name="doActionA"/>
<targetNode name="doActionB"/>
</split>

End nodes - end the process and store state in a process item
<end id="error" state="ERROR">All went wrong.</end>
<end id="success" state="SUCCEEDED">Everything is fine</end>
Process Actions Creating a Process 14

The next step consists in defining all actions specified in the bean
attribute of individual action nodes

Actions are the most important part of the process engine extension
and implement logic or call specialized services

An action performs a single piece of work and produces an action


result which is directed as input to the next action

All actions from the process definition XML file are implemented as
actions classes
AbstractSimpleDecisionAction Creating a Process 15

public class Action1 extends AbstractSimpleDecisionAction


{

@Override
public Transition executeAction(BusinessProcessModel process)
{
if(...)
return Transition.NOK;
else
return Transition.OK;
}
}
AbstractProceduralAction Creating a Process 16

public class Action1 extends AbstractProceduralAction


{
@Override
public void executeAction(BusinessProcessModel process)
{
modelService.save(process);
}
}
Using a common context Creating a Process 17

A common context can be used for all actions belonging to a particular


process

This is achieved with the class BusinessProcessModel or one of its


subclasses (e.g. ForgotPasswordProcessModel)

An instance of this class is passed as a parameter each time an action


is called:
public void executeAction(final ForgotPasswordProcessModel process)

The process fills this context with values

You may add your own attributes to BusinessProcessModel


Integration with Spring Creating a Process 18

Finally, we need to add the action classes to


<my-extension>-spring.xml file:

<bean id="Action1" class="org.training.actions.Action1"


parent="abstractAction"/>

<bean id="Action2"class="org.training.actions.Action2"
parent="abstractAction"/>

<bean id="Action3"class="org.training.actions.Action3"
parent="abstractAction"/>

<bean id="Action4"class="org.training.actions.Action4"
parent="abstractAction"/>
Creating and Starting a Process Creating a Process 19

To create a new process instance, you need to call the


BusinessProcessService method createProcess.
businessProcessService.createProcess( processName )

To start a process you need to call one of the available startProcess


methods of the same BusinessProcessService.
businessProcessService.startProcess( businessProcessModel )
20

Architectural Overview
Features
Business analysis
Creating a Process
Task Extension

hybris Developer Training Part I - Core Platform


Foundation used for single-process engine step Task Extension 21

The hybris Task extension:


allows you to schedule time- or event- driven tasks by placing them on a task queue

provides a lighter weight approach to tasks than CronJobs. But offers less
functionality

processes tasks asynchronously

tasks execution is distributed across the cluster to ensure reliable tasks processing
The Task Engine Task Extension 22

The Task extension is designed to be used in a ServiceLayer-based


application

It provides a service for scheduling new actions and triggering events:


TaskService

Actions are defined as Spring beans in an extension’s Spring


configuration file e.g. myextension-spring.xml

To define an action, you implement the TaskRunner interface

In a clustered environment you may specify which nodes should


process tasks:
task.workers.max=10
Quiz questions 23

1. Give a brief architectural overview of the process engine extension.


2. What is typically the first step in defining a new process for the process
engine extension?

3. How do you define a process?


4. Name three different types of nodes.
5. What is the most important field in a node?
6. How do you implement logic for the process engine extension?
7. Compare the hybris Task extension to a CronJob and highlight some of
the differences.
References 24

wiki.hybris.com/display/release5/
processengine+-+Technical+Guide

wiki.hybris.com/display/release5/
Order+Management+Tutorial+-+An+Example+Process

wiki.hybris.com/display/release5/task+-+Technical+Guide
25
1·1
1·2

hybris Developer Training Part I - Core Platform

Warm Up
1·3

Introduction
Product Line
Support & Release Strategy
Architecture overview
Spring overview

hybris Developer Training Part I - Core Platform


Personal Introduction Introduction

1·4

hybris Trainer
[email protected]

Name

Role Spring/JEE
Project experience

Company
Previous hybris
experience

Hobbies
Some Necessities Introduction

1·5

Participant list
USB Sticks
Training Content Introduction

1·6

This course aims to:


illustrate the core functionality and main concepts of the hybris Platform
demonstrate the software
give the idea of what’s available out-of-the-box and what has to be implemented
give you a chance to write a “hello world” for each area presented
answer your questions

This course won’t:


solve project-specific problems
show hybris Commerce or PCM functionality
for that, there is hybris Developer Training Part II
talk in detail about hybris administration
for that, there is hybris System Administrator Training
Hardware requirements Introduction

1·7

Laptop or personal computer


Windows, Linux or Mac-OS X
Minimum 8 GB of RAM available
One free USB Slot
Administrator Rights
Internet access (practical exercises are online)
Latest Java 7 (oracle JDK preferred)
An IDE (eclipse preferred)
Working Hours – Day 1 Introduction

1·8

9:00 1. Introduction & Warm Up

2. Setting up a Development Environment

Day 1
1. Preparation(T)

2. Goal (T)
12:30
Lunch

13:30 3. New Extension (T)

3. Data Modeling

4. hMC

3. New Data Model (T)

- New Data Model II (T) (optional)

17:00 - Integration in the hMC (T) (optional)


Working Hours – Day 2 Introduction

1·9

9:00 1. PCM basics

2. Import and Export

5. Population the Data Model (T)


Day 2

12:30 3. Service Layer programming

Lunch

4. Flexible Search
13:30
6. Testing the DAOs (T)

7. Testing the Services (T)

3. Java Beans

8. Testing the Facades (T)

9. Front end (T)


17:00
Working Hours – Day 3 Introduction

1·10

9:00 1. Cronjobs

2. Cockpit Framework

10. Cronjobs (T)


Day 3 11. Cockpit Basics (T)

12:30 3. Workflows

Lunch

13. Events (T)


13:30 4. Security

5. Cache

14. Create a Workflow (T)

3. Cockpits NG
12. hybris Commerce Cockpit (T)

17:00 - Cockpit NG (T) – (optional)


Working Hours – Day 4 Introduction

1·11

9:00 1. Validation

2. Process Engine

15. Validation(T)
Day 4

12:30 3. Webservices

Lunch

4. Accelerator
13:30
14. Dynamic Attributes (T)

15. Media Conversion (T)

5. Translation

- Webservices (T) – (optional)

17:00 - Catalogs (T) – (optional)


Hands-On Introduction

1·12

The lab work for this class is based on the hybris developer trail:
A self-paced, guided walk-through with solution
Available at wiki:

wiki.hybris.com/display/tr50/
hybris+v5.0+Developer+Training+Trails+-+Part+I+Core

Accessible with your wiki account (or with hybris_training account)

It is an online football betting application (In the US, that's soccer)


Trail is purposefully not a commerce site to help you fully understand
core concepts before applying them to your own domain

Are you stuck in a lab?


Please ask the trainer
Also feel free to post comments at trail pages
hybris Wiki – Knowledge Online Resources

1·13

wiki.hybris.com – Knowledge space


Documentation (!)
Trails (!)
Certification
Training
Forum
1·14

Introduction
Product Line
Support & Release Strategy
Architecture overview
Spring overview

hybris Developer Training Part I - Core Platform


The industry’s most modern, agile, comprehensive Product Line
commerce suite.
1·15

orders
commerce

content

channel

platform

Full description and documentation can be found here:


wiki.hybris.com/display/release5/Release+5+Documentation+Home
hybris Platform Product Line

1·16

Subject of this training


Standard set of extensions with main functionality
An extension:
Represents the technical structure of a module
Can contain business logic, type definitions, a web application, or other

Database and application server abstraction layer


ORM framework
Build framework
Cockpit framework
Data modeling, validation and imports
Web services
Configuration files
hybris Server
1·17

Introduction
Product Line
Support & Release Strategy
Architecture overview
Spring overview

hybris Developer Training Part I - Core Platform


Support Packages Support & Release Strategy

1·18

Hybris service desk


[email protected]
EMEA: +49-89-558930700
North America: +1-514-9076158

Support Packages come in different Service Level Agreements (SLA):


Pricing
Response time
Number of annual incidents etc.

How to submit and issue and more info at:


wiki.hybris.com/display/SUP/Home
Releases Support & Release Strategy

1·19

Epic Release

5.3.2.1
New architecture, new build system etc.
Every 1-2 years
Major Release Epic. Major. Feature. Patch
New features
Every 6 months
Feature Release
New features which can be released without API changes
Every 2 months
Patch Release
Critical bugs fixed - released when necessary, no API changes

Migration guides provided for Epic and Major releases


Release notes are available on the wiki under Download page
1·20

Introduction
Product Line
Support & Release Strategy
Architecture overview
Spring overview

hybris Developer Training Part I - Core Platform


Architecture Overview Technical Architecture Overview

1·21

Client Back Office

Web Analysis Touch Points Cockpits hMC NG


Spring MVC BiRT RESTful
WebSvc Product Admin WCMS
Front End Accelerator iReport
Widgets in-Store apps
Flex Report Print CSR
… …

APIs ServiceLayer API WebService API VirtualJDBC API

Extension Payment Promotion Workflow BTG Print CMS …

Core Platform
Business Services (Classification, Catalog, price Calculation, …)
Platform Infrastructure Services (Authentication, User, i18n, …)
System Services (Session, Model, Tenant, Cluster, …)

Persistence Framework

Application
Server

Database
3rd party compatibility Technical Architecture Overview

1·22

3rd party compatibly matrix can be found at wiki:


wiki.hybris.com/display/release5/Third-Party+Compatibility+-+Release+5.0
Modes of operation Technical Architecture Overview

1·23

You can run the hybris Commerce Suite in three different modes of
operation
Single Node

JVM
hybris Platform

Single Node

Data for
hybris
db Platform
Modes of operation Technical Architecture Overview

1·24

Multi-tenant

JVM
hybris Platform

Tenant 1 Tenant 2 Tenant 3

Data for Data for Data for


Tenant 1 Tenant 2 Tenant 3
db
Modes of operation Technical Architecture Overview

1·25

Cluster

hybris Cluster

JVM JVM JVM

Node 1 Node 2 Node 3

db
1·26

Introduction
Product Line
Support & Release Strategy
Architecture overview
Spring overview

hybris Developer Training Part I - Core Platform


What is Spring? Spring Overview

1·27

The Spring Framework is a lightweight open source application framework


for the Java platform provided and maintained by SpringSource.

Provides many modules, not all of them used in hybris


The most important ones that are used by hybris:
Dependency Injection (also known as “Inversion of control”), used heavily, provides
better decoupling and improves testability
Aspect-Oriented Programming, not used by default, but usable for extending stuff
which isn’t customizable by default or implementing cross-cutting-concerns
Spring MVC, request based framework used in the accelerators
Spring Security, used for authentication and basic authorization
1·28
1
2

hybris Developer Training Part I - Core Platform

hybris Web Services


3

Overview
Demo

hybris Developer Training Part I - Core Platform


Overview Web Services Overview 4

REST based web services

Every item is exposed as a resource

Resource class is generated automatically

Attribute Selectors to save bandwidth

FlexibleSearch based pagination

Commands with customizable logic


Architecture Overview Web Services Overview 5
6

Overview
Demo

hybris Developer Training Part I - Core Platform


7
1
2

hybris Developer Training Part I - Core Platform

hybris commerce
Accelerator
3

Overview
Benefits
Features
A Long-Term Vision

hybris Developer Training Part I - Core Platform


The hybris Commerce Accelerator Commerce Accelerator Overview 4

The hybris Commerce Accelerator is a reference implementation of a Web


framework providing a fully functional storefront
It is based on the hybris Commerce Suite and comes with a pre-configured
foundation which incorporates good practice multichannel capabilities with
integrated Web, order management and call center capabilities
Using the Commerce Accelerator as a starting point allows you to greatly
reduce implementation time and cost
Purpose Commerce Accelerator Overview 5

The hybris Commerce Accelerator provides a collection of template extensions


that form a starting point for your new e-commerce implementation project
It is delivered completely as source code
The project development team simply uses the Accelerator’s source code,
modifies, adds or removes code
The Accelerator makes technical choices for you, such as which framework to
use, how to render HTML, and how to handle emails
Extensions Commerce Accelerator Overview 6

The Accelerator requires a specific set of extensions out of the box but does
not impose any limitations on adding further extensions
The modulegen functionality allows you to quickly generate a complete set of
Accelerator extensions
A flexible type system permits extensions to add additional attributes to
existing types
During build, model objects are generated and compiled from the type system
definition, located in the items.xml file
7

Overview
Benefits
Features
A Long-Term Vision

hybris Developer Training Part I - Core Platform


A Commerce platform, out of the box ! Benefits 8

 Deliverable is as
• E-commerce storefront close to a
working website
as possible
hybris Mgmt.
Search Console (hMC)  Including
WCMS Cockpit Promotions Cross-sell and Cockpits attention to
& Navigation
integration
Checkout Reviews Social networks Fraud engine points, e.g.
dataload
Shopping cart Product details Payment Reporting

 All Accelerator
components
Customer Order delivered as
Store Locator
service Management source code for
quick
development
Integration

Platform Functionality
Benefits – Best practice technology implementation Benefits 9

 Commerce
• E-commerce storefront Façade
• Best practice technology implementation  Web framework
Spring MVC 3
hybris Mgmt.  CSS/HTML
Search Console (hMC) (including
WCMS Cockpit Promotions Cross-sell and Cockpits
& Navigation blueprint css)
Checkout Reviews Social networks Fraud engine  AJAX/Javascript
(incl. jQuery)
Shopping cart Product details Payment Reporting  Tags, themes
 i18n, UTF-8
 Spring
Customer Order
Store Locator
Integration,
service Management Spring security
 Shipped as
Integration source with
extgen
Platform Functionality compatibility
Benefits – Extensive documentation Benefits 10

Documentation  In-line
documentation
 Code samples
• E-commerce storefront
and sample data
• Best practice technology implementation

hybris Mgmt.  Delivery


Search Console (hMC) Framework
WCMS Cockpit Promotions Cross-sell and Cockpits
& Navigation Guide
Checkout Reviews Social networks Fraud engine  Functional
Specification
Shopping cart Product details Payment Reporting Guide
 Technical Guide
 End User Guide
Customer Order
Store Locator
service Management

Integration

Platform Functionality
11

Overview
Benefits
Features
A Long-Term Vision

hybris Developer Training Part I - Core Platform


Commerce Accelerator Features Features 12

The Accelerator provides a working website, including:


A full implementation of SOLR functionality with additional configuration tools

Key pages that are WCMS enabled

Standardized batch loading of product files

Fully integrated promotions handling

Multi-currency, multi-language websites

Expanded product details

Links to social networks and social capabilities such as reviews

A fully integrated store locator

A user-friendly checkout process


Currently three storefronts out of the box Features
B2B self-service tools:
13

organization
management, quote
negotiation, order
management

Easy to re-skin

Ready for go-live


storefronts, e.g.
performance tested,
SEO friendly URLs
Multiple sites, languages, currencies Features 14

Multi-lingual, multi-currency
out of the box
Built with business users in mind Features 15

Most pages templated and


managed by our WCMS

Multiple, standard content


includes to merchandise the
included
site
sitehow want
as you like
Provides typical eCommerce functionality Features 16

SOLR-based text search fully


integrated Login and registration, store locator

Data driven catalogue hierarchy, AJAX On-screen basket


with opportunity to manage
additional links
Search and navigation Features 17

High quality, configurable search


function
Merchandise
Deals with misspelling, search
opportunities based on
stemming, etc.
search terms

Browse products or
refine search
results based on
key attributes;
Price, colour, top
rated, etc.

Order results based on relevancy, price,


name, top rated
Search results can be refined Features 18

Quickly adjust
search
selection by Keep track of your selections
removing
previously
made
selections

Refine search
or navigate by
category or
attributes.
Content
automatically
adjusts

Select multiple- attributes simultaneously


Merchandising Features 19

Links to social networks to share product


information

Ability
Ability for cross-sell and
to cross-sell and up-sell
up-sell
merchandise
Adding products to basket does not distract from buying Features 20
process

AJAX basket

Stock awareness
Straightforward checkout process Features 21
Email communication can be edited by business users Features 22
Easy registration for new users Features 23

Built-in field validation

Built-in password strength


indicator
24

Overview
Benefits
Features
A Long-Term Vision

hybris Developer Training Part I - Core Platform


Looking to the Future 25

BUYING
A fully working, fully tested,
good practice multichannel
storefront
 Quick time to market

EXPANDING
CONCEPTION
Switch to hybris enterprise
solution Functional and technical
specifications provided
Integrate external solutions
 Reduces risk in early
 Future-proof platform project stages

MAINTENANCE IMPLEMENTATION
Source code provided Design & architecture guidelines
Built to be customized Development process
Upgrade Tests
 Easy to maintain  Improved ramp-up time
Learn more! 26

To work with and learn more about the


hybris Commerce Accelerator
sign up for :

hybris Developer Training


Part II – Commerce
Quiz Questions 27

1. Give a brief outline of the hybris Commerce Accelerator.


2. Name three benefits of the hybris Accelerator.
3. What are the main features of the Accelerator?
Refernces 28

wiki.hybris.com/display/accdoc/
Getting+Started+with+the+hybris+Commerce+Accelerator
wiki.hybris.com/display/accdoc/
System+Architecture+of+the+hybris+Commerce+Accelerator
wiki.hybris.com/display/accdoc/User+Interface+and+Creatives+
in+the+hybris+Commerce+Accelerator
wiki.hybris.com/display/accdoc/Storefront+and+Catalog+
Modelling+in+the+hybris+Commerce+Accelerator
wiki.hybris.com/display/accdoc/Customization+
Possibilities+in+the+hybris+Commerce+Accelerator
29
2·1
2·2

hybris Developer Training Part I - Core Platform

Development
Environment Setup
2·3

Installing the hybris Commerce Suite


Build Framework
Basic Configuration
hybris server
hac
Initialization and Update
Extension Concept
Eclipse Integration

hybris Developer Training Part I - Core Platform


Quick Installation Guide Installing the hybris Commerce Suite

2·4

1. Install the most recent version of the Java Development Kit (JDK 7)
Enter “java –version” to test your Java installation

2. Install hybris platform by either:


Unzip from usb-stick
After training use wiki download pages:
wiki.hybris.com/display/release5/Download
Or by using the hybris Package Manager (rather at production)

Windows system users:


Unzip into a directory close to the drive root and with no whitespaces in the name,
such as C:\hybris
Quick Installation Guide Installing the hybris Commerce Suite

2·5

3. Open a console window and go to hybris/bin/platform


4. Call setantenv.bat (OSX/Linux: setantenv.sh)
5. Call ant to build
Select a default develop configuration template
(develop and production are available).
Quick Installation Guide Installing the hybris Commerce Suite

2·6

6. Call hybrisserver.bat (OSX/Linux: hybrisserver.sh) to start


hybris platform
7. Open localhost:9001 in your browser and hit “initialize”

8. Have fun:
localhost:9001/
localhost:9001/hmc
2·7

Installing the hybris Commerce Suite


Build Framework
Basic Configuration
hybris server
hac
Initialization and Update
Extension Concept
Eclipse Integration

hybris Developer Training Part I - Core Platform


Build Framework Build Framework

2·8

The hybris Platform has a build framework based on:


Apache Ant for automation tasks
The compiler from the Eclipse IDE

Scope: platform-wide or extension-wide


You can build the whole platform with all its extensions, or…
build just one extension (this shortens the build process).

There are predefined callbacks like


Before/after compile
Before/after build
Before/after clean
See buildcallbacks.xml for more
Building with ant Build Framework

2·9

When you call ant, the build framework:


generates and compiles “Model” classes
according to the definitions in the *-items.xml files
In order of extensions dependency (hierarchy)
collects localization property files (locales_XY.properties).
collects layout configuration files (hmc.xml).
updates configuration of the hybris Server
generates following folders (only in first run!)
Build Targets Build Framework

2·10

Ant Target Description


all Builds and configures the server
clean Cleans platform and all extensions
extensionsxml Generates complete extensions.xml
runcronjob Runs the specified cronjob
extgen Runs extension generation tool
initialize Initializes the hybris system with default settings
updatesystem Updates the system
server Configures hybris Server and restarts if running
startHybrisServer Runs Easter egg
unittests Executes all unittests
typecodetest Checks if any reserved typecodes are being used
-p Shows list of all Ant targets
2·11

Installing the hybris Commerce Suite


Build Framework
Basic Configuration
hybris server
hac
Initialization and Update
Extension Concept
Eclipse Integration

hybris Developer Training Part I - Core Platform


Configuration Files Basic Configuration

2·12

Each extension has:


project.properties with extension-specific configuration
extensioninfo.xml with extension dependencies configuration

For global settings and to override any extension specific configuration


always use the config folder, it contains:
local.properties
Overrides any properties specified in each extension project.properties file
Introduces global properties like database url and credentials
localextensions.xml
List of extensions used by build framework
Beside that: configuration templates for bundled servers, language packs, license,

To use different configuration e.g. for test server:


Run ant –Duseconfig=foobar
Then localfoobar.properties file will be used
Configuration changes Basic Configuration

2·13

Modify the local.properties file and restart the application server


No need to call ant in the console
Configuration files are read during startup.
All configuration files are inside the config directory

However if you change any Tomcat configuration settings (such as


tomcat.http.port), you need to call ant server

If in doubt, call ant all

It’s possible to change the properties on the runtime in hac


After server restart these changes are lost
localextensions.xml Basic Configuration

2·14

List of extensions used by build framework

Dependencies are resolved automatically using the path parameter.


Build will find dependent extensions which are not explicitly listed

Extensions can be listed by name instead of location path

It can be generated
Load Required Extensions Basic Configuration

2·15

Define a lookup folder with the <path> tag (lazy loading):

<extensions>
<path dir="${HYBRIS_BIN_DIR}/ext-cockpit"/>
<path dir="${HYBRIS_BIN_DIR}/ext-hybris/"/>
<extension dir="${HYBRIS_BIN_DIR}/ext-hybris/cmscockpit"/>
...

All extensions found inside dir=“…” are only pulled into the
current extension configuration if referenced by another
extension, or by name (see next slide).
Loading All Extensions in a Folder Basic Configuration

2·16

Auto-loading of dependant extentions by path tag


<extensions>
<path autoload="true" dir="${HYBRIS_BIN_DIR}/ext-cockpit" depth="3"/>
<extension dir="${HYBRIS_BIN_DIR}/ext-hybris/hmc"/>
<extension dir="${HYBRIS_BIN_DIR}/ext-hybris/basecommerce"/>
<extension dir="${HYBRIS_BIN_DIR}/ext-hybris/cms2"/>
<extension dir="${HYBRIS_BIN_DIR}/ext-hybris/cmscockpit"/>
</extensions>
Load Extension by Name Basic Configuration

2·17

Extensions can be configured by name, provided one or more lookup


folders have been specified:

<extensions>
<path dir="${HYBRIS_BIN_DIR}/ext-cockpit"/>
<path dir="${HYBRIS_BIN_DIR}/ext-hybris/"/>
<extension name="cmscockpit"/>
</extensions>
Quiz Questions Basic Configuration

2·18

1. What does ant –p do?

2. How can you build hybris?

3. What is configured in extensioninfo.xml?

4. Do you need to shut down the server while executing ant all?
2·19

Installing the hybris Commerce Suite


Build Framework
Basic Configuration
hybris server
hac
Initialization and Update
Extension Concept
Eclipse Integration

hybris Developer Training Part I - Core Platform


Bundled With hybris Bundled Servers

2·20

hybris comes with boundled hybris server and a


configuration templae for tcServer
hybris Server Bundled Servers

2·21

+ =
Apache Tomcat
What is the hybris Server? Bundled Servers

2·22

Optimized and pre-configured server based on Apache


Tomcat
Production-ready quality and best suited to run all
applications of the hybris Multichannel Suite
Configuration templates available for development and
production deployment
Independent of the operating system
Easy installation
Can be run as a system service under Microsoft Windows
or Linux
Contains a wrapper that automatically restarts the Apache
Tomcat Java Virtual Machine if the Apache Tomcat hangs
or stops.
Advantages of the hybris Server Bundled Servers

2·23

Advantages: compared to other application servers with


EAR deployment
Identical setup and usage for development, staging, and live system
Dramatically simplified installation, deployment, and configuration
Very small footprint – faster than WebLogic or WebSphere on the same
hardware
Complete support for virtualized environments (“Ready for the cloud”)

Free of charge, part of the hybris Multichannel Suite


(free security updates, for example)
Reduce hosting partners’ costs

hybris Server Support is included in the standard hybris


Service Level Agreements
Reduces customers’ cost for support and training
Deploying with the hybris Server Bundled Servers

2·24

Call ant production in the


${HYBRIS_BIN_DIR}/platform directory.
The system will generate two ZIP files:
hybrisServer-Platform.zip
hybrisServer-AllExtensions.zip

Copy both files onto the target machine.

Unzip them and start the hybris Server

For subsequent deployments:


The same as above
Deploying Onto a non-Tomcat Server (WebLogic or WebSphere)
2·25

Call ant all cleanear ear in the


${HYBRIS_BIN_DIR}/platform directory.
The system will generate:
{HYBRIS_TEMP_DIR}/EAR/hybrisplatform.ear

Deploy this file to the Application server, and start the


server normally

Access hybris using the port number configured in the


3rd-party application server.
Switching to tcServer Bundled Servers

2·26

Via the local.properties file, you can set


Which server type to use (hybris / tcServer)
Notice: you have to download the tcServer binaries yourself
Where the bundled server is located
How your server instance is named
Which template to use (in case you have no instance yet)
You have to use templates of bundled server
2·27

Installing the hybris Commerce Suite


Build Framework
Basic Configuration
hybris server
hac
Initialization and Update
Extension Concept
Eclipse Integration

hybris Developer Training Part I - Core Platform


hac - hybris Administration Console Server start modes & hac

2·28

Administration

Monitoring

Configuration

localhost:9001/
(by default)
2·29

Installing the hybris Commerce Suite


Build Framework
Basic Configuration
hybris server
hac
Initialization and Update
Extension Concept
Eclipse Integration

hybris Developer Training Part I - Core Platform


Initialize or Update the System Initialization and Update

2·30

System Initialization:
Entire type system is created from scratch.
ALL database tables are dropped.
Data model is created from scratch as defined in the items.xml files.
New tables with initial dataset are created
Existing data model definitions will be lost!

System Update:
Existing tables are updated to match changes in the domain model.
No loss of data!
Two major aspects:
Adding newly defined types to the type system definition in the database
Modifying type system definition in the database to match the definition in the
domain model
Initialization Initialization and Update

2·32

1. hac -> Platform -> Initialize 2. Ant view in eclipse + tenant

3. Command line
Initialization and Update
Essential Data vs. Project Data
2·33

Essential Data
Necessary during initialization:
Creates the Default catalog, restrictions, and basic CronJobs, for example.

Project Data:
Extension-specific project data

How to include:
Convention over Configuration essentialdata*.impex,
projectdata*.impex
Hook Service Layer code into hybris initialization and update life-cycle events
@SystemSetup annotation
Quiz Questions Initialization and Update

2·34

1. What are the main features of the hybris Administration Console?


2. How can you reach the hybris Administration Console?
3. Does the hybris Administration Console allow you to monitor the
system?

4. What is the difference between a system initialization and a system


update?

5. What is the difference between essential data and project data?


2·35

Installing the hybris Commerce Suite


Build Framework
Basic Configuration
hybris server
hac
Initialization and Update
Extension Concept
Eclipse Integration

hybris Developer Training Part I - Core Platform


Where to Begin Extension Concept

2·36

Developing a new project with its own data model and


business logic starts with the generation of a new extension.
That way your (project) code is separated from hybris (framework) code,
making your code easier to reuse and to migrate to future versions.
hybris bundles a proprietary code generator.

Examples:
Frontend extnesion: with all jsp pages, css, controllers
Testing extension: has all the test cases and data (such as testdata)
Infrastructure or utility extension (such as services)
Extension Basics Extension Concept

2·37

Extensions are encapsulated modules, which can contain


business logic
data model definition
web application

By default: independent from other extensions (except


platform)

Extension concept benefit: Easy to migrate and update

Always use your own extension to create, extend or to


overload existing hybris code !!!
Extension Dependency Management Extension Concept

2·38

Extensions depend on each other,


All extensions implicitly depend on the hybris Platform
Each extension is an individual Eclipse Project
Dependency Management is done the extensioninfo.xml file:

Eclipse projects dependency configuration must be done separately

Cyclic dependencies are prevented by build framework


Structure of an Extension Extension Concept

2·39

Compiled sources
Generated Java files
hMC module
External library files
Type definitions & localization
Resources folder for external data
Business logic
JUnit test classes
Web module
Files for Eclipse, Apache Ant, and
extension-specific configuration
Spring contexts
2·40

Global Context

Tenant Tenant Tenant


Tenant Context Tenant Context
Context Context Context
“master” “junit”
“master” “junit” “foo”

Web Context Web Context Web Context Web Context


“/shop_master” “/back_master” “/shop_foo” “/back_foo”
Spring configuration of extensions Extension Concept

2·41

Extension B
serviceB
Web Context
serviceA
controllerX
Tenant context

serviceA serviceB

Extension A
serviceA Web Context
controllerX

Beans from web context can access beans from tenant context
Spring configuration of extension Extension Concept

2·42

There are 3 xml files for your bean definitions


global-{ext-name}.xml
Beans are shared among all extensions

{ext-name}-spring.xml

Beans are shared among all extensions

Beans will have as many instances as there are tenants.

web-application-config.xml
Beans are available only for selected extension and per tenant
How to Create a New Extension Extension Concept

2·43

Invoke ant extgen <ENTER>

Select an extension template, such as:


yempty: A bare skeleton
ycockpit: Creates a new cockpit extension

Extension should be referenced in the localextensions.xml


file
<path dir="${HYBRIS_BIN_DIR}"/>
<extension name="myextension"/>

Call ant clean all <ENTER>


Platform and Technology Templates Extension Concept

2·44

Select template when creating a new extension


Template Description
yempty Empty extension with minimal implementations of core,
hmc, web
yaddon Basic template for writing AddOns.
ybackoffice Structure of the Custom Backoffice Extension
ycockpit Create a new cockpit extension
ycommerceweb Exposes parts of the commerce Façade as a REST-
services based web services.

Overview of all templates


wiki.hybris.com/display/release5/Creating+a+New+Extension#Cre
atingaNewExtension-availabletemplates
Quiz Questions Extension Concept

2·45

1. Explain the concept of extensions in hybris

2. Is it possible for an extension to have dependencies on other


extensions?

3. Where do you specify extension dependencies?

4. Explain the concepts of global context and web context

5. What does “ant extgen” do?

6. What are extension templates?

7. What does “autoload = true” do?


2·46

Installing the hybris Commerce Suite


Build Framework
Basic Configuration
hybris server
hac
Initialization and Update
Extension Concept
Eclipse Integration

hybris Developer Training Part I - Core Platform


Your Eclipse Installation Eclipse Integration

2·47

You can use an out-of-the-box Eclipse installation.


Be sure to use the latest Eclipse version with Web Tools
Platform is installed:
www.eclipse.org/downloads

Or Spring Tool Suite


Your Eclipse Installation Eclipse Integration

2·48

Before coding in Eclipse..


We advise familiarity with our development documentation in the Wiki. In
particular, check out “The coding landscape” under
wiki.hybris.com/display/general/Development+Landscape
and the links you find there.

Our approach to ensuring Code Quality – see also


wiki.hybris.com/display/general/Code+Quality:
Code Reviews
Code walkthroughs
Coding conventions
Test Suites
Eclipse Enhancements for Faster Development Eclipse Integration

2·49

The hybris Suite comes with configuration files for the


Eclipse IDE.

Changes in an items.xml file automatically trigger:


source file generation (for example, web service resources)
model generation
a refresh of the project in which the items.xml file was modified
a refresh of the gensrc directory of the ServiceLayer extension

This relies on general Eclipse tools.


Importing the hybris Suite as an Eclipse Project Eclipse Integration

2·50

Open the File menu and click on Import.

In the Select screen of the Import wizard:


Expand the General section.
Select Existing Projects into Workspace.
Click on the Next button to continue.

In the Import Projects screen of the Import wizard:


Click on the Browse button for the Select root
directory field.
Importing the hybris Suite as an Eclipse Project Eclipse Integration

2·51

Navigate to the hybris directory of your installation.


Select the hybris directory and click on the OK button.

Back on the Import Projects screen of the Import wizard:


Check or clear the projects Eclipse has located.
Make sure that Copy projects into workspace is NOT ticked.
Click on the Finish button.

Eclipse will now refresh the workspace.


Debugging with Eclipse IDE Eclipse Integration

2·52

Start the hybris Server in debug mode (hybrisserver.bat


debug).
You can change the debug settings in the local.properties file.

In Eclipse, go to Run -> Debug configurations …


Create a new Remote Java Application, Enter a name (such as training).
Connection type: Standard
Host:Port – localhost:8000 (default; configurable in local.properties)
Debugging with Eclipse IDE Eclipse Integration

2·53

Click on the Debug button.


Switch to the Debug perspective.
Open the file to be debugged (.java, .jsp).
Navigate to the line where you want to add a breakpoint.
Double-click on the gray border on the left hand side of the line
numbers.
A breakpoint icon should appear.
If that icon has a small check if it is synchronized with the hybris
Server.
Eclipse will now stop at this line.
Quiz Questions Eclipse Integration

2·54

1. Which version of Eclipse do you need?

2. How do you debug code using Eclipse?


2·55
3·1
3·2

hybris Developer Training Part I - Core Platform

Data Modeling
3·3

Introduction to the Type System


Collections & Relations
Deployment

hybris Developer Training Part I - Core Platform


hybris and Java Introduction to the Type System

3·4

Class
Java: is an is a blueprint
instance of of

Object

hybris: Type
is an is a blueprint
instance of of

Item
Java Classes vs hybris Types Introduction to the Type System

3·5

Java Type System

Product metatype
is represented as
ProductModel.java code : String
name : localized:String
ComposedType
subclass of subtype of

Car
is represented as fuel : Enumeration
CarModel.java
kwatt : Double metatype

by runtime, is represented
as an instance of

code : HistoricCar
name : Some Old Car
fuel : Gasoline
kwatt : 30
Types used in hybris Introduction to the Type System

3·6

AtomicType
Represents Java value objects which are mapped to database types
Java Primitives: int
Wrapper: Integer
Some Reference types: java.util.Date

CollectionType
Represents a typed collection

MapType
Represents a typed Map
Types used in hybris Introduction to the Type System

3·7

ComposedType
Composed object of other hybris types
Java Primitives: int
Wrapper: Integer
Some Reference types: java.util.Date

EnumerationMetaType
ComposedType which describes enumerations

RelationType
ComposedType which describes binary relations between items
Extending the Data Model Introduction to the Type System

3·8

Create new types:


Define a type by extending already existing types, such as:
<itemtype code="Car" extends="Product">
Define “completely new types”, such as:
<itemtype code="Car">
(implicitly extends from GenericItem)

Extend existing types:


Add attribute definitions to existing types (attribute injection), such as:
<itemtype code="Product" …>
...
<attribute qualifier="MyAttribute">
</itemtype>
Redefine inherited attribute definitions from super type
<attribute qualifier="code" redeclare="true">
If you change the attribute's java type, the new type must extend the original
type
2.9 (Data Mapping)
hybris Type System • Extending Introduction to the Type System

3·9

Product

code vehicle01
Car
name Ferrari F40

catalogVersion Online

<items>

<itemtypes>
<itemtype code="Car" extends="Product" autocreate="true" generate="true"
jaloclass="de.hybris.platform.lecture.jalo.Car">
...
hybris Type System • Attributes Introduction to the Type System

3·10

Product

code vehicle01
Car
name Ferrari F40

catalogVersion Online + hp: int


+ kw: int
hp 300

kw 212

<items>

<itemtypes>
<itemtype code="Car" extends="Product" autocreate="true" generate="true">
<attributes>
<attribute qualifier="hp" type="java.lang.Integer">
<description>Horse Power</description>
<persistence type="property" />
</attribute>
<attribute qualifier="kw" type="java.lang.Integer">
<description>Kilowatt</description>
<persistence type="dynamic"
attributeHandler="kwPowerAttributeHandler" />
<modifiers write="false" />
</attribute>
hybris Type System • Enumerated types Introduction to the Type System

3·11

Product

code vehicle01
Car
name Ferrari F40

catalogVersion Online + hp: int


+ kw: int
hp 300 + fuel: enumeration
kw 212

fuel gasoline
{ gasoline | diesel | ethanol }
<items>

<itemtypes>
<itemtype code="Car" extends="Product" autocreate="true" generate="true">
<attributes>
<attribute qualifier="hp" type="java.lang.Integer">
<enumtypes>
<description>Horse Power</description>
<enumtype code="FuelEnumeration"
<persistence type="property" />
generate="true"
</attribute>
autocreate="true"
<attribute qualifier="kw" type="java.lang.Integer">
dynamic="true">
<description>Kilowatt</description>
<value code="diesel"></value>
<persistence type="dynamic"
<value code="gasoline"></value>
attributeHandler="kwPowerAttributeHandler" />
<value code="ethanol"></value>
<modifiers write="false" />
</enumtype>
</attribute>
</enumtypes>
<attribute qualifier="fuel" type="FuelEnumeration">
<description>Fuel for this car</description>
<persistence type="property"></persistence>
</attribute>
hybris Type System • Composed Type reference Introduction to the Type System

3·12

Product

code vehicle01 mechanic


Car
name Ferrari F40
Employee + hp: int
catalogVersion Online
+ kw: int
hp 300 + fuel: enumeration
kw 212

fuel gasoline
{ gasoline | diesel | ethanol }
mechanic Nikola Tesla

<items
<itemtypes>
<itemtype code="Car" extends="Product" autocreate="true" generate="true">
<attributes>
...
<attribute qualifier="mechanic" type="Employee">
<modifiers read="true" write="true" search="true" />
<persistence type="property" />
</attribute>
hybris Type System • Relations Introduction to the Type System

3·13

Product

code vehicle01 mechanic


Car
name Ferrari F40
Employee + hp: int
catalogVersion Online * 1
+ kw: int
hp 300 drivers car + fuel: enumeration
kw 212

fuel gasoline
{ gasoline | diesel | ethanol }
mechanic Nikola Tesla

drivers Jacek Szybki, Drew Slowpoke

<items>
...
<relations>
<relation generate="true" localized="false" code="Car2EmployeeRelation" autocreate="true">
<sourceElement qualifier="car" type="Car" cardinality="one"></sourceElement>
<targetElement qualifier="drivers" type="Employee" cardinality="many"></targetElement>
</relation>
</relations>

<itemtypes>
...
2.14 (Data Mapping)
hybris Type System • Automatic Generation Introduction to the Type System

3·14

1. hybris item definitions are found in each


extension's extensionName-items.xml
Resources
DTOs

2. The ant process assembles type


definitions and generates Models,
DTOs, and Resources. ant build
process
3. hybris also creates the service layer
required tables. models

items
initialize
4. Invoking initialize or update
creates the required table.

update

ext-items.xml
DB tables
Quiz Questions Introduction to the Type System

3·15

1. What is the equivalent of a Java object in hybris?

2. What is the difference between a composed type and an atomic type in


hybris?

3. What file is used to configure types in hybris?

4. In hybris, can you create new types, or only extend existing types?

5. Do you have to define a model-class in Java after defining it in xml?


3·16

Introduction to the Type System


Collections & Relations
Deployment

hybris Developer Training Part I - Core Platform


Collectiontypes Relations

3·17

Collection of target type


Can be used as attribute type of a ComposedType
Allows you also to define AtomicTypes collections
Performance considerations: Accessing, Searching
Database integrity considerations

<collectiontype code="StringCollection"
elementtype="java.lang.String" autocreate="true“ />
<collectiontype code="LanguageCollection"
elementtype="Language" autocreate="true"/>

...

<itemtype code="..." ...


<attribute qualifier="urlPatterns" type="StringCollection">
<attribute qualifier="writeableLanguages" type="LanguageCollection">
...
Relations Relations

3·18

One2Many and Many2Many


Both sides are (can be) aware of the other

Category Product

products (List<Product>) categories


points to points to (List<Category>)

CategoryProductRelation

products is added source (Category) supercategories is added


to the Category type to the Product type
as an attribute target (Product) as an attribute
Role name at source: “products”

Role name at target: “supercategories”


What’s so Important About Relations? Relations

3·19

If in doubt: Use relations, not CollectionTypes, because:


Opposite side is not “aware” of the CollectionType
CollectionTypes are stored in a database field as a comma-separated
list of references (PKs) or atomic values
Can cause overflow
More difficult to search and generally lower performance
3·20

Introduction to the Type System


Collections & Relations
Deployment

hybris Developer Training Part I - Core Platform


Object Relational Mapping — Storing objects in the DB Deployment

3·21

By default, items for a given type are stored in the same database tables
as its supertype
Specify any item type's deployment to store its items in its own db tables.
hybris recommends that deployment be specified for the first layer of
GenericItem subtypes
Consider carefully the performance implications of specifying deployment for other
item types
Set build.development.mode = true in local.properties to mandate that all direct
children of GenericItem have deployment specified.

GenericItem genericitem

MyType Product product

mytypes
Car
O-R Mapping – Deployment Example Deployment

3·22

GenericItem genericitem

MyType Product product

mytypes
Car car

<itemtype code="Car" …
<deployment table="cars"
typecode="20100" …

0 .. 10000 are reserved by hybris


10000 .. 32767 are free for use,
with some exceptions
O-R Mapping – Table Structure Deployment

3·23

PK P1 P2 P3 C1 C2 C3 product
Product
… … … … … … …

product
Car

PK P1 P2 P3
… … … …

product product
Product

PK P1 P2 P3 C1 C2 C3 car
Car
… … … … … … …

car
O-R Mapping – Attributes of a (Composed) Type Deployment

3·24

PK code name … mechanic


8796256894977 vehicle01 Ferrari F40 … 8796128083972

product

Atomic type property – value


stored directly in db. For
instance, property of type
String is stored as VARCHAR Composed type property –
reference to another item. The
db column stores a PrimaryKey
(PK) value.

code vehicle01

name Ferrari F40 PK name …


mechanic Nikola Tesla 8796128083972 Nikola Tesla …

users
O-R Mapping – Deployment of Relations • 1 Deployment

3·25

One-to-Many
Additional column at the many side which holds the PK of the One side
Users table from the example below would have an additional column car

<relation generate="true" localized="false" code="Car2EmployeeRelation"


autocreate="true">
<sourceElement qualifier="car" type="Car“ cardinality="one" />
<targetElement qualifier="drivers" type="Employee"
cardinality="many"/>
</relation>

PK name car …
PK code … 8796128083972 André-Marie Ampère 5553620010023 …
8796256894977 vehicle01 … 5443669878887 C.-A. de Coulomb 5553620010023

5553620010023 rocket05 … users

product
O-R Mapping – Deployment of Relations • 2 Deployment

3·26

Many-to-Many
New database table which holds the source and target PKs

<relation code="CategoryProductRelation" autocreate="true" generate="true"


localized="false">
<deployment table="Cat2ProdRel" typecode="143"/>
<sourceElement qualifier="supercategories" type="Category" cardinality="many"
ordered="false">
<modifiers read="true" write="true" search="true" optional="true"/>
</sourceElement>
<targetElement qualifier="products" type="Product" cardinality="many"
collectiontype="list" ordered="true">
<modifiers read="true" write="true" search="true" optional="true"/>
</targetElement>
</relation>
Source Target

PK code …
8796256894977 3776876789221 PK code …

8796256894977 vehicle01 … 5553620010023 3776876789221 3776876789221 Commuting …

5553620010023 rocket05 … 5553620010023 6152677365115 6152677365115 Exploration …

product Cat2ProdRel category


O-R Mapping – Deployment of Collections Deployment

3·27

Collections
Stored in one database column
Comma separated list of PKs or Atomic Values

<collectiontype code="StringCollection"
elementtype="java.lang.String" autocreate="true“ />
<collectiontype code="LanguageCollection"
elementtype="Language" autocreate="true"/>

...

<itemtype code="..." ...


<attribute qualifier="urlPatterns" type="StringCollection">
<attribute qualifier="writeableLanguages" type="LanguageCollection">
...

PK code urlpatterns writeableLanguages …


8796256894977 Example1 http://ex1.com/a,http://ex2.com/b,http://ex3.com/c 93938293,93029304,01920394 …

product
Quiz Questions
3·28

1. Name the two ways to model a collection in hybris

2. How are collection types stored in the database?

3. Specify some advantages and disadvantages of collection types

4. Explain the notion of deployment in hybris. When should you use it?
References
3·29

/wiki.hybris.com/display/release5/Type+System+Documentatiom
wiki.hybris.com/display/release5/items.xml
wiki.hybris.com/display/release5/
Specifying+a+Deployment+for+hybris+Platform+Types
3·30
4·1
4·2

hybris Developer Training Part I - Core Platform

hybris Management
Console
4·3

hybris Management Console


Overview of the hMC
Storing Layout Configuration
hMC Localization
Type System Localization

hybris Developer Training Part I - Core Platform


What is the hybris Management Console? hybris Management Console

4·4

Highly generic
Component-based
Database-oriented view
Everything is displayed as it is defined in the items.xml
Easy to configure and customize via XML configuration
You can extend the hMC functionality by implementing
Actions: Allow running custom business logic
WebChips: MVC model-compliant stateful components
Wizards: Allow better control of the sequence in which a
user specifies data (e.g.: skipping tabs and
data validation)
Distributed as an extension
hMC – Use Cases hybris Management Console

4·5

Useful for developers during the implementation phase


Check the data model
Manage complex business processes (imports, automated tasks)
Manage user-related settings (access rights, groups)

Not recommended for business/end users (too complex,


too technical)
Use different Cockpits instead, such as the Product Cockpit
For more complex or proprietary processes, create your own
Cockpits
4·6

hybris Management Console


Overview of the hMC
Storing Layout Configuration
hMC Localization
Type System Localization

hybris Developer Training Part I - Core Platform


hMC – Components Overview of the hMC

4·7

Toolbar

Explorer Search Area


Tree

Result Area

History
hMC Tree Overview of the hMC

4·8
hMC Search Overview of the hMC

4·9
hMC Result Overview of the hMC

4·10
hMC Editor - Tab Overview of the hMC

4·11
hMC Editor - Essentials Overview of the hMC

4·12
hMC Editor - Section Overview of the hMC

4·13
hMC Editor - Attributes Overview of the hMC

4·14
4·15

hybris Management Console


Overview of the hMC
Storing Layout Configuration
hMC Localization
Type System Localization

hybris Developer Training Part I - Core Platform


Storage Location for XML Definition Storing Layout Configuration

4·16

All hmc.xml configuration files are assebled into one final


file during the system build

The final hmc.xml is loaded into database during the


system update

In order to avoid lengthy system update during the


development, it’s recomended to specify:
the hmc.structure.db=false property in the
local.properties file.

It’s possible to upload this file in the hMC manually:


Go to group "System“ -> "hMC configuration“
Click on the button "hmc.xml upload“
Clearing the hMC Configuration From the Database Storing Layout Configuration

4·17

You can clear the hMC layout definition stored in the database
manually via the hybris Administration Console:
4·18

hybris Management Console


Overview of the hMC
Storing Layout Configuration
hMC Localization
Type System Localization

hybris Developer Training Part I - Core Platform


hMC – Localization hMC Localization

4·19

hMC localizations are stored in locales_XY.properties


files in the directory:
${extension}/hmc/resources/${package}/hmc

XY indicates the ISO code of the language


(mandatory parameter when a language is created)
Can contain parameters (refer to the wiki for further information)
Unlike on type system localization, there is no convention here:

section.name = The name of a section


tab.name.more = The name of the tab
error.the.name.of.error = Error message
value.with.unicode = Asterisk is \u002A
4·20

hybris Management Console


Overview of the hMC
Storing Layout Configuration
hMC Localization
Type System Localization

hybris Developer Training Part I - Core Platform


Type System Localization Type System Localization

4·21

The localization strings for types and attributes are stored


in files named extension-locales_XY.properties
extension: the name of the extension
XY: the ISO code of the language
Properties convention:
type.{typename}.name=value
type.{typename}.description=value
type.{typename}.{attributename}.name=value
type.{typename}.{attributename}.description=value
type.{enumcode}.{valuecode}.name=value

Use generator from hmc to get all properties keys


generated for selected extensions
System Initialization / Update – Localize Types Type System Localization

4·22

Type localizations are stored in the database

Overrides type localizations in the database with the ones


from the locales_XY.properties files
Quiz Questions
4·23

1. What does the abbreviation hMC stand for?

2. When would you use the hMC and when would you use the
hybris Administration Console?

3. Which file is used to configure hMC layout?

4. What do you have to do after modifying the hMC


configuration-file?

5. What is the difference between type system localization and


hMC localization?
4·24
1
2

hybris Developer Training Part I - Core Platform

PCM basics
3

Internationalization
Catalogs
Media Management in hybris

hybris Developer Training Part I - Core Platform


Core I18N Features Internationalization 4

Out-of-the-box support for:


Languages (localizations of business objects)
Countries and Regions (tax regulations)
Currencies (currency formats, rounding)
Time Zones (online / offline dates, order dates)
Number Formats (separation characters)
Intuitive UI to manage localized items
Standards-based API (e.g use of Java Locale objects)
Advanced features, such as:
Language fallbacks
Note that the hierarchies of fallback languages are not resolved
Tenant-specific settings
Allows hybris to serve completely different stores from one platform
installation

The concept of localization is an essential part of the


hybris system
Other I18N-Relevant Areas Within hybris Systems Internationalization 5

Multi-Catalog
Create different catalogs in different versions and assign different
categories and products to them, such as:
Summer Sales 2010 vs Autumn Sales 2010
Staged vs Online
Synchronize these catalog versions
Grant different permissions to these catalogs and catalog versions

Multi-Site
Create different countries / locations / URLs and define which of your
defined product catalogs should be used there

Multi-Tenancy
Separate business objects by business (e.g. brand, location) and run
different tenants on one single hybris installation
Language packs Internationalization 6

The hybris commerce suite binary zip (5.1) contains


localization for several languages.

Support for additional languages


From the hybris wiki download appropriate language pack
(German, French, Polish…).

If desired language is missing at hybris website:


Copy and rename the existing language pack
Translate the content
Apply it
Language packs – how to apply them Internationalization 7

Place language pack zip in the config/languages folder


Provide additional language support lang.packs = en,
de , fr, pl
Run ant customize
New language items are be created
Content of given lang.packs is copied into apropraite locations
Update running system
Translations are copied to database

Remove language pack zip from config folder


Otherwise each system update will override any language
changes in db.
Language packs Internationalization 8

Further info at:


wiki.hybris.com/display/release5/
How+To+Add+New+Language+Translation+-
+Tutorial
9

Internationalization
Catalogs
Media Management in hybris

hybris Developer Training Part I - Core Platform


Catalog type structure Catalogs 10

Products are the basic elements of


each catalog. They have references to
one or more categories, and a catalog
version
Categories are held in catalog
versions
A catalog version represents the
product assortment offered at a given
point of time
A catalog typically holds two or more
catalog versions
Catalog Versions - Synchronization 11

Synchronization copies specified content from a source


catalog version to a target catalog version e.g. from a
staged to an online catalog version
Items referenced by the target catalog version are
updated to match the items referenced by the source
catalog version
A synchronizing operation can be applied to an entire
catalog version or to selected categories or products
Rules specifying how product data should be copied to
the target catalog version may be defined
Synchronization can be launched manually, or
automatically using a CronJob
12

Internationalization
Catalogs
Media Management in hybris

hybris Developer Training Part I - Core Platform


Media Management Media Management in hybris 13

hybris Media
Consist of:
A physical representation on a File system – possibly remote
A Media Item holding the reference to the physical file
Can be localized
One file can be referenced by
several Media items
Can be organized into
Media folders
Media Folders Media Management in hybris 14

Media Folders are hybris items that represent directories


on the file system.
You can define the Media Folder when you create a
Media, or you can move Media Items from one folder to
another after creation.
To move more than one Media to another Media Folder,
use hMC Actions.
Media folder storage strategy Media Management in hybris 15

There are 4 storage strategies for Media Folders


localFileMediaStorageStrategy – store medias locally
S3MediaStorageStrategy – store medias in Amazon
WindowsAzureBlobStorageStrategy – azure
GridFSMediaStorageStrategy – MongoDB based, good for
clusters and large data

Create your own strategy by implementing


MediaStorageStrategy

To specify storage strategy for your new folder:


folder.myFolder.storage.strategy=myStorageStrategy
Otherwise the default is used (Out of the box default: local):
media.default.storage.strategy=
localFileMediaStorageStrategy
Media folder storage strategy Media Management in hybris 17

If your MediaFolder is going to contain enormous number


of files then consider configuring hashing depth to speed
up files access:
folder.myFolder.hashing.depth=3

Possible values: 0-4

It’ll create up to 4 levels of system folders with 256


folders in each.
Media folder URL strategy Media Management in hybris 18

There are 3 URL strategies Out of the box:


LocalMediaWebURLStrategy
S3MediaUrlStrategy
WindowsAzureBlobURLStrategy

You may create your own by implementing


MediaURLStrategy

To specify URL strategy for your new folder :


folder.myFolder.url.strategy=myCustomURLStrategy
Otherwise default is used: LocalMediaWebURLStrategy
Media Formats and Containers Media Management in hybris 19

hybris can scale, convert, and modify bitmap image media using the
ImageMagick open source image manipulation toolkit.
Media Formats are only tags which can be assigned to Medias (Media
Models in the hybris type system)
Media Containers can be used to group the same MediaModels with
different formats.
There are convenient methods for extracting a stored MediaModel
into the right format, e.g.
MediaModel m1 = ...
MediaFormatModel printFM = ...
MediaModel m3 = m1.getInFormat( printFM );
Secure medias Media Management in hybris 20

Applies only to local media storage


Remote storage options like amazon S3 have their own
configurable permissions.
each folder has a security flag specified by
folder.myfolder.secured = true

add SecureMediaFilter to your filter chain in your webapp to


restrict media access
If above flag is set to 'true’ then the SecureMediaFilter will check
ACL permission for each media by following the URL
if access is denied then 'http access denied’ status is sent
MediaPermissionService – you can use it to grant or revoke
permissions for medias and users. Can also be done with ImpEx.
22
1
2

hybris Developer Training Part I - Core Platform

Flexible Search
3

Overview
Syntax
API examples

hybris Developer Training Part I - Core Platform


Overview Flexible Search Overview 4

SQL-like syntax
Abstracts a database query into a hybris Item query
Returns a list of objects (hybris Items)
Makes properties easily queryable
Is translated into native SQL statements on execution
Allows nearly every feature of SQL SELECT
statements
Queries go through cache
5

Overview
Syntax
API examples

hybris Developer Training Part I - Core Platform


Syntax Flexible Search Syntax 6

Basic Syntax:
SELECT <selects> FROM {types} (where <conditions>)
?(ORDER BY <order>)?

Mandatory:
SELECT <selects>
FROM {types}

Optional:
where <conditions>
ORDER BY <order>

SQL Command / Keywords:


ASC, DESC, DISTINCT, AND, OR, LIKE, LEFT JOIN, CONCAT, ..
Query examples Flexible Search Syntax 7

Simple queries:
Product
SELECT {code},{hp} FROM {Car}

Single type queries: Car

+ hp: int
SELECT {code} FROM {Product!} + kw: int
+ fuel: enumeration

Joins: 1 car

SELECT {c.code},{e.uid} FROM {


* drivers
Car as c JOIN Employee as e
ON {c.pk} = {e.car}
Employee
} WHERE {e.uid} LIKE ‘%Szybki’
More query examples Flexible Search Syntax 8

Inner queries:
SELECT {c.code} FROM {Car as c}
WHERE {c.mechanic} IN
({{
SELECT {pk} FROM {Employee}
WHERE {uid} LIKE ‘%Tesla’
}})

Parametrized queries:
SELECT count(*) FROM {Car}
WHERE {hp} > ?hpMin
AND {hp} < ?hpMax
9

Overview
Syntax
API examples

hybris Developer Training Part I - Core Platform


Querying with parameters Flexible Search API Examples 10

String fsq = "SELECT {PK} FROM {Car} WHERE {mechanic} =?mechanic”;


FlexibleSearchQuery query =
new FlexibleSearchQuery(fsq,
Collections.singletonMap( "mechanic", mechanic ) );
SearchResult<CarModel> result =
getFlexibleSearchService().search( query );
List<CarModel> cars = result.getResult();
Querying for other types than Models Flexible Search API Examples 11

String fsq = "SELECT COUNT( {PK} ) FROM {Car}”;


FlexibleSearchQuery query = new FlexibleSearchQuery( fsq );
query.setResultClassList( Arrays.asList( Integer.class ) );
SearchResult<Integer> result =
getFlexibleSearchService().search( query );
List<Integer> carsCount = result.getResult();
Pagination Flexible Search API Examples 12

public List<CarModel> getCars(int start, int range)


{
String fsq= "SELECT {PK} FROM {Car}";

FlexibleSearchQuery query = new FlexibleSearchQuery( fsq );

query.setNeedTotal( true );

query.setCount( range );

query.setStart( start );

return flexibleSearchService.<CarModel>search( query


).getResult();
}

Performance gain only if underlying DB supports pagination


GenericSearch Flexible Search API Examples 13

Similar to HibernateCriteriaSearches
Search for items as well as raw data fields
Unlimited number of conditions
Inner joins and outer joins between item types possible
Unlimited number of “order by” clauses
Sub-selects
GenericSearch Example Flexible Search API Examples 14

GenericQuery query = new GenericQuery(CarModel.PK);


GenericSerchField carField = new
GenericSearchField( CarModel.PK, CarModel.Name );
GenericCondition condition =
GenericCondition.createConditionForValueComparison(carField,
Operator.LIKE,
“BMW”);
query.addCondition( condition );
query.addOrderBy(new GenericSearchOrderBy( carField, true ));

List<CarModel> cars = genericSearchService.search( query );


15
1
2

hybris Developer Training Part I - Core Platform

Impex
3

Overview
Syntax and examples
Invoking

hybris Developer Training Part I - Core Platform


ImpEx – Overview InpEx Overview 4

ImpEx is an out-of-the-box import / export framework

It’s an interface between CSV files and the hybris


Multichannel Suite’s Type System
you can “import” instances of types from CSV.
you can “export” instances of types into CSV.

You can create, update, export, and remove items


ImpEx – Typical fields of use InpEx Overview 5

In live operation:
to import customer data into a production system
to synchronize data with other systems, such as an ERP or LDAP
to create backups
to update data at runtime
can be run from CronJobs

In migrations:
to migrate data from one hybris installation to another

In development:
to import sample data (e.g. on system initialization)
to import test data into testing system
ImpEx – Features InpEx Overview 6

Impex abstracts from database


No table information (deployment)
No foreign keys (use “business keys,” which we will discuss in a moment)
Impex simplifies imports
The order of the imported data is irrelevant! (Failed lines are retried)
Validation constraints may be disabled
impex.legacy.mode=true
ImpEx concerns
no transactional imports
Performance – use multithreaded imports:
impex.import.workers=4
Note: ImpEx does not provide XML import out-of-the-box
7

Overview
Syntax and Examples
Invoking

hybris Developer Training Part I - Core Platform


Syntax Basics ImpEx Syntax and Examples 8

Header syntax:
Operation itemType; attributes(refAttr)[modifiers];...

INSERT Product; code; name[lang=en];


UPDATE Product; code[unique=true]; name[lang=en];
INSERT_UPDATE Customer; customerID[unique=true]; groups(uid);
REMOVE Media; code[unique=true];

Data row syntax:


;attr1value; attr2value; ...
;iphone5; Apple iphone 5;
;Drew; customergroup;
;iphone5Pic;
Basic syntax example ImpEx Syntax and Examples 9

INSERT_UPDATE Promo; code[unique=true]; name[lang=en]; country(code)


;BKCampaign1;Burger King Antarctica Launch; AQ
;iphone5China;Apple iphone 5 China Campaign; CN

Key points:
The code[unique=true] is so called “key attribute” or “business key”.
Impex will search for product with code “BKCampaign1” before triggering import.
In this example we expect to find 1 or none.

The name[lang=en]indicates language of provided value. Only valid for localized


attributes.

The country(code) is a reference to another item using its code (“business key”)
In this example, the country property of Promo item “BKCampaign1” is linked to
another hybris item whose code is “AQ”
ImpEx Syntax Elements ImpEx Syntax and Examples 10

Macros
Allows aliases to stand in for frequently used statements

BeanShell
Allows script to be added to a CSV file.
Predefined hooks beforeEach, afterEach, getLastImportedItem() etc.

Translators
Implement custom ImpEx logic e.g to import medias (binary files).

Inclusion of data
Allows you to split your ImpEx operations over several files.

Collections and HashMaps:


Allows you to use these types as attributes

Different validation modes for export


E.g the mode “Strict (Re)Import” ensures that the export is re-importable
Catalog example ImpEx Syntax and Examples 11

$catalogVersion=catalogVersion(Catalog(id),version)[unique=true]

INSERT_UPDATE Product; code[unique=true]; name[lang=en];


unit(code); $catalogVersion
;W580i;Sony Ericsson W580i; pieces; Default:Staged
;iphone5;Apple iphone 5; pieces; Default:Online

Key Points:
This example uses a macro, which is substituted in the header
verbatim.
The Product is considered to have a composite key, since two
fields in the header are listed as unique (code and
catalogVersion).
For catalog-aware items (e.g. product), we must specify the
catalog version for the item. Since this is a double-key reference,
we separate the fields with a colon (:).
Catalog reference details ImpEx Syntax and Examples 12

$catalogVersion=catalogVersion(Catalog(id),version)[unique=true]
INSERT_UPDATE Product; code[unique=true]; name[lang=en]; unit(code); $catalogVersion
;W580i;Sony Ericsson W580i; pieces; Default:Staged
;iphone5;Apple iphone 5; pieces; Default:Online

References
The product item references a catalogVersion item, which is identified using two
keys: a catalog reference and a version string. The catalog reference, in turn, is
identified by an id string.

catalogVersion(Catalog(id),version) catalogVersion(Catalog(Default),Staged) Catalog(Default)


...; Default:Staged

product catalogVersion catalog

PK code catalogVersion … PK catalog version … PK id …


8796256 W580i 4592878 … 4592878 7756563 Staged … 7756563 Default …
Using macros and defaults ImpEx Syntax and Examples 13

$prodCat=myCatalog
$version=Staged
INSERT Category;code;catalogVersion(catalog(id),version)
;cars;$prodCat:$version
;convertibles;$prodCat;$version

$catVersion=catalogVersion(catalog(id[default=$prodCat]),version[default=$version])
INSERT Category;code;$catVersion
;cars;
;convertibles;

Notes
macros can be used in both header and data rows
use default values to simplify data rows
More examples ImpEx Syntax and Examples 14

Use ‘append’ mode to avoid overriding existing references

INSERT_UPDATE Employee; uid[unique=true]; groups(uid)[mode=append]


;Drew; approvers,dummygroup,reviewers

Use ‘translators’ for custom interpretation of imported values

INSERT_UPDATE Employee;@password[translator=PasswordTranslator]
;aVeryStrongPassword;

INSERT_UPDATE Media; @media[translator=MediaDataTranslator]


;/path/to/my/picture.jpg;
Advanced example ImpEx Syntax and Examples 15

Batch update
UPDATE Product [batchmode=true]; itemType(code)[unique=true];status
;Product; approved

Selective export
"#% impex.setTargetFile( ""Product.csv"" );"
INSERT_UPDATE Product; code[unique=true]; name[lang=en]
"#% impex.exportItemsFlexibleSearch(
""select {pk} from {Product} where {code} like '%happy%'"");"
ImpEx Script For Export ImpEx Syntax and Examples 16

Specify the target file:


"#% impex.setTargetFile( ""Product.csv"" );"

Specify the attributes to be exported via an ImpEx header:


INSERT_UPDATE Product; code[unique=true]; description[lang=en];
name[lang=en]; unit(code)
You can use the same header for re-import.

Start the export:


"#% impex.exportItems( ""Product"" , false );"

Hint:
You may use the “Script Generator” in the hMC.
17

Overview
Syntax and examples
Invoking

hybris Developer Training Part I - Core Platform


Where Can You Launch an Import? Invoking ImpEx 18

In the hybris Administration Console


Test area for ImpEx scripts
Multiple files cannot be imported by a single ImpEx script
No external data is allowable
Limitted configuration possibilities

In the hybris Management Console (hMC)


Create an ImpExImportCronJob

Via the API


You can use the ImportService
Where Can You Launch an Export? Invoking ImpEx 19

In the hybris Administration Console


Test area for ImpEx scripts

In the hybris Management Console


Select search results and export them via the context menu
Create an ImpExExportCronJob.

Via the API


Use the ExportService
Create an ImpExExportCronJob
Quiz Questions 20

1. What data can you import with ImpEx?

2. How do you trigger imports?

3. What happens if your header lines are broken?

4. What happens if some data lines are broken, e.g. referencing


unknown data?
21
1
2

hybris Developer Training Part I - Core Platform

Programming with the


hybris ServiceLayer
3

Architecture of the ServiceLayer


Services
Models
Interceptors
Events

hybris Developer Training Part I - Core Platform


Overview of the hybris ServiceLayer Architecture of the Service Layer 4

Web
Cockpits hmc Web Shop Other
Services
The hybris architectural layer
where you implement YOUR logic

hybris ServiceLayer
Provides a number of services, each Business Services
(Classification, CMS, Price Calculation, ...)
with its well defined responsibilities
Infrastructure Services Models
Service oriented architecture based (Cache, Security, Transaction, Session, ...)

on Spring framework hybris ServiceLayer Framework

Provides hooks into modellife-cycle


events for performing custom logic
Provides a framework for publishing hybris Persistence Items

and receiving events

Database
ServiceLayer – Structure and Data Objects Architecture of the Service Layer 5
6

Architecture of the ServiceLayer


Services
Models
Interceptors
Events

hybris Developer Training Part I - Core Platform


What Services Are There? Services 7

Services can be grouped logically into


Core Services
Business Services
Where to Find Services Services 8

Core services (No source provided)


${HYBRIS_BIN_PATH}/platform/ext/core/...

Business services
${HYBRIS_BIN_PATH}/platform/ext/platformservices/src/...

Services in extensions
${HYBRIS_BIN_PATH}/${EXTENSION}/src/${PACKAGES}/

More Info
wiki.hybris.com/display/release5/Key+Services+Overview
download.hybris.com/api/5.x.x
Using Services Services 9

To implement your own business logic, you can:


use existing services
create your own services
replace existing services

Replace existing services in the Spring application


context
<alias alias="cartService"
name="defaultCartService" />
10

Architecture of the ServiceLayer


Services
Models
Interceptors
Events

hybris Developer Training Part I - Core Platform


Overview of Models (I) Models 11

Data objects the ServiceLayer is based on


Each Item Type has a corresponding model class
POJO-like objects
Providing attributes with getter and setter methods
Generated during build
${HYBRIS_BIN_PATH}/platform/bootstrap/gensrc
Overview of Models (II) Models 12

Models represent a certain “snapshot” of data from the


database
No attachment to database: representation is not live
When modifying a model, you must explicitly save it back
You may influence loading of attributes
servicelayer.prefetch in advanced.properties

Never touch (hybris) models!


Lifecycle of a Model Models 13

Model Runtime

Instantiate a Model Modify Model Values

Model myModel = new Model();

Save Model Values

Load from Database

ModelService

modelService.get() modelService.remove() modelService.save()

Database
Using Models Models 14

The ModelService deals with all aspects of a model‘s life-


cycle:
Loading models by PK
Creating models
Updating / saving models
Deleting models

Factory Method:
ProductModel product = modelService.create(ProductModel.class);

Constructor:
ProductModel product = new ProductModel();
15

Architecture of the ServiceLayer


Services
Models
Interceptors
Events

hybris Developer Training Part I - Core Platform


Interceptors Overview Interceptors 16

There are various types of interceptors allowing you to


interrupt the intended course of a Model’s life cycle

An interceptor addresses a particular step in a Model's


life cycle

With interceptors, you can modify a Model or raise


exceptions to interrupt the current step e.g. certain values
may be validated before a Model is saved

An interceptor is registered as a Spring bean


Interceptors Overview - Lifecycle of a Model Interceptors 17

Model Runtime

Instantiate a Model Modify Model Values

Model myModel = new Model();


modelService.initDefaults();
InitDefaultsInterceptor
Save Model Values
modelService.create(Model.class);
PrepareInterceptor
Load from Database
ValidateInterceptor
LoadInterceptor

ModelService

modelService.get() modelService.remove() modelService.save()


RemoveInterceptor

Database
Implementing interceptors Interceptors 18

To create an interceptor, one the following interfaces needs to be


implemented:

LoadInterceptor is called whenever a model is loaded from the


database

InitDefaultsInterceptor is called to fill a model with its


default values

PrepareInterceptor is called before a model is saved to the


database and before it is validated by ValidateInterceptor

ValidateInterceptor is called before a model is saved to the


database and after it has been prepared by the
PrepareInterceptor

RemoveInterceptor is called before a model is removed from


the database
Implementation - Registering an interceptor Interceptors 19

After implementing an interceptor, the interceptor is registered as


a spring bean in myextension-spring.xml:
<bean id="myLoadInterceptor"
class="my.package.MyLoadInterceptor"/>

public class MyLoadInterceptor implements LoadInterceptor


{
public void onLoad(Object model, InterceptorContext ctx)
throws InterceptorException
{
….
}
}
Implementation – mapping the interceptor Interceptors 20

The interceptor is then mapped in myextension-spring.xml:

<bean id="myLoadMapping"
class="de...interceptor.impl.InterceptorMapping">

<property name="interceptor" ref="myLoadInterceptor"/>


<property name="typeCode" value="Stadium"/>
<property name="order" value="1"/>
<property name="replacedInterceptors" ref="a,b,c"/>
</bean>
21

Architecture of the ServiceLayer


Services
Models
Interceptors
Events

hybris Developer Training Part I - Core Platform


The Event System – Overview Events 22

The hybris Event System is based on the Spring event


system

One software component acts as a source and publishes


an event that is received by registered listeners

Event listeners are objects that are notified of events and


perform business logic corresponding to the event that
occurred

Events can be published locally or across cluster nodes

Events might be transaction aware


Implementing Events Events 23

An Event is an instance of a subclass of AbstractEvent


and contains a source object:

public class AfterItemCreationEvent extends


AbstractPersistenceEvent
{
private final String typeCode;

public AfterItemCreationEvent(final String typeCode, final


PK pkCreated)
{
super(pkCreated);
this.typeCode = typeCode;
}
}
Implementing Event Listeners Events 24

Event listeners allow you to react to an event


To implement an event listener:
Extend the AbstractEventListener class
Override the onEvent() method

public class AfterInitializationEndEventListener extends


AbstractEventListener<AfterInitializationEndEvent>
{
...
@Override
protected void onEvent(final AfterInitializationEndEvent event)
{
getValidationService().reloadValidationEngine();
LOG.info("Reloaded validation framework.");
}
}
Registering Event Listeners Events 25

Two options to register the event listener:


as a bean in the Spring application context:

<bean id="myEventListener"
class="my.package.MyEventListener"/>

by dynamically adding listeners at runtime using eventService:

@Resource
EventService eventService;
eventService.registerEventListener( new MyEventListener() );
Event Service Events 26

The Service Layer’s EventService allows you to:


Register event listeners with
eventService.registerEventListener( myEventListener )

Publish events using the method


eventService.publishEvent( myEvent )

To access this service, add a Spring resource to your


class:
@Resource;
private EventService eventService;
Asynchronous events Events 27

Events are processed synchronously be default


This is often undesirable as the main thread waits until
events are processed, and this may impede performance
There are two possible ways to force events to be
processed asynchronously:
by configuring PlatformClusterEventSender
by using ClusterAwareEvents
For each asynchronous event, network traffic occurs.
Asynchronous events - Implementing ClusterAwareEvent Events 28

To implement a ClusterAwareEvent, adding the


following method to your event class causes events to be
published only to the source node of the event:

@Override
public boolean publish(final int sourceNodeId,
final int targetNodeId)
{
return (sourceNodeId == targetNodeId);
}
Transaction-Aware Events Events 29

Events that are published only at the end of a transaction

Implement the TransactionAwareEvent interface

publishOnCommitOnly: Event will be published depending on the


success of the transaction

getId: two events with the same id will be published only once
Predefined Events – ClusterAware and TransactionAware Events Events 30

There are predefined ClusterAware and


TransactionAware events that are processed
asynchronously:
AfterItemCreationEvent – Triggered after an item is created

AfterItemRemovalEvent – Triggered after an item is removed


Predefined Events – Non-Cluster Aware Events Events 31

Non-ClusterAware Events are only published


synchronously

AfterInitializationEndEvent Triggered after initialization has ended

AfterInitializationStartEvent Triggered after the initialization has


started

AfterSessionCreationEvent Triggered after the session was created

AfterSessionUserChangeEvent Triggered after a new user is assigned


to the session

BeforeSessionCloseEvent Triggered before a session is closed


Quiz-Questions 32

1. What is the hybris ServiceLayer?

2. Name 3 services

3. What is a ModelService and why should you use it?

4. How to create an interceptor?

5. How do you publish an event?

6. Explain how you can force events to be published asynchronously.


33

You might also like