Hybris Developer Training Guide
Hybris Developer Training Guide
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.
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
Internet connection
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)”.
1.1.4. Warm-Up
Introduction
Online Resources
Product Line
Support & Release Strategy
Architecture overview
Spring overview
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
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
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.21. Accelerator
Overview
Benefits
Features
A long term vision
Page 4 of 4
1
2
Generation of Java
Beans
3
Overview
Java Beans are used as transport objects for the frontend layer
<bean class="org.training.data.MyPojo">
<property name="id" type="String"/>
</bean>
public MyPojo()
{
// default constructor
}
...
}
Why? Java Beans Overview 6
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>
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
CronJobs
3
Overview
Automated tasks
A CronJob consists of a:
Job: What to do
Trigger: When to run
CronJob: Runtime information
INSERT_UPDATE Trigger;cronjob(code)[unique=true];cronExpression
; myCronJob; 0 0 0 * * ?
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 Ant
Email template
notify certain user using given email template
User
to empower restrictions
Node id
to specify server for job execution
10
1
2
Cockpit Framework
3
Theoretical Background
Layout Configuration
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
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
3-11
Browser Area
Navigation Editor
Area Area
Context Area
Configuration Schema Layout Configuration 12
consists of returned to
looks up and
assembles
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
<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
<base>
...
<search-properties>
<property qualifier="CatalogVersion.version"/>
<property qualifier="CatalogVersion.catalog.name"/>
</search-properties>
...
</base>
20
1
2
Overview
Widget development
Application orchestrator
Business role/process-centric
Runtime configurable
Platform independent
Key concepts Cockpit NG Overview 5
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
Overview
Widget Development
Application Orchestrator
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>
</widget>
Example widget controller: Product List Widget Development 14
@SocketEvent(socketId = “products”)
public void setProducts(final List<? extends Object> products)
{
gridList.setModel(new SimpleListModel(products));
definition.xml
<widget-definition id="org.mybackoffice.widgets.productdetail">
<name>Product Detail</name>
<defaultTitle>Details</defaultTitle>
<author>hybris</author>
<version>0.1</version>
<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
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
mybackoffice/backoffice/resources/mybackoffice-backoffice-widgets.xml: Configuration
of components on the mybackoffice extension level.
21
Overview
Widget development
Application orchestrator
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
Workflows
3
Overview
Data Model
Working with workflows
Automated steps
Track a workflow
Overview
Data Model
Working with workflows
Automated steps
Overview
Data Model
Working with workflows
Automated steps
Through API
ImpEx
Through API
Activation Script
In Product Cockpit
Overview
Data Model
Working with workflows
Automated steps
Implementation steps
2. Create a bean
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
Security
3
Basics
Type-Based Access Rights
Restrictions
Spring security
Custom Access Rights
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
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
Advantages Disadvantages
$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
PermissionsConstants.REMOVE).isDenied();
permissionCRUDService.canReadType( typeCode );
permissionCRUDService.canChangeAttribute( typeCode,
attributeQualifier );
11
Basics
Type-Based Access Rights
Restrictions
Spring security
Custom Access Rights
Advantages Disadvantages
Advantages Disadvantages
cockpit.disableRestrictions=false
ImpEx example Restrictions 15
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
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" />
Restrictions:
wiki.hybris.com/display/release5/Restrictions
Basics
Type-Based Access Rights
Restrictions
Spring security
Custom Access Rights
More info:
wiki.hybris.com/display/release5/
Managing+and+Checking+Access+Rights
25
1
2
Transactions
3
Overview
@Transactional(propagation=Propagation.REQUIRES_NEW,
isolation=SERIALIZABLE)
public void provideService()
{
repo1.retrieveFoo();
repo2.retrieveFoo();
}
Cache
3
Overview
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)
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
# Change eviction policy used by entity region. Possible vales are FIFO
(default), LFU and LRU.
regioncache.entityregion.evictionpolicy=LRU
Validation Framework
3
The hybris Data Validation Framework is based on the JSR 303 Java
validation specification
Validation
FrameworkValidation Engine
ValidationService
7
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
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
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
List constraints
Although this can also be done with the hMC, we recommend using the
administration cockpit which is more user-friendly and intuitive.
20
1. Explain the main features of the hybris Validation Framework and the
three areas of which it consists.
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
Architectural Overview
Features
Business analysis
Creating a Process
Task Extension
Architectural Overview
Features
Business analysis
Creating a Process
Task Extension
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
The first step in working with the process engine extension typically
consists of conducting a business analysis
Architectural Overview
Features
Business analysis
Creating a Process
Task Extension
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>
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
All actions from the process definition XML file are implemented as
actions classes
AbstractSimpleDecisionAction Creating a Process 15
@Override
public Transition executeAction(BusinessProcessModel process)
{
if(...)
return Transition.NOK;
else
return Transition.OK;
}
}
AbstractProceduralAction Creating a Process 16
<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
Architectural Overview
Features
Business analysis
Creating a Process
Task Extension
provides a lighter weight approach to tasks than CronJobs. But offers less
functionality
tasks execution is distributed across the cluster to ensure reliable tasks processing
The Task Engine Task Extension 22
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
Warm Up
1·3
Introduction
Product Line
Support & Release Strategy
Architecture overview
Spring overview
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
1·7
1·8
Day 1
1. Preparation(T)
2. Goal (T)
12:30
Lunch
3. Data Modeling
4. hMC
1·9
Lunch
4. Flexible Search
13:30
6. Testing the DAOs (T)
3. Java Beans
1·10
9:00 1. Cronjobs
2. Cockpit Framework
12:30 3. Workflows
Lunch
5. Cache
3. Cockpits NG
12. hybris Commerce Cockpit (T)
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)
5. Translation
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
1·13
Introduction
Product Line
Support & Release Strategy
Architecture overview
Spring overview
orders
commerce
content
channel
platform
1·16
Introduction
Product Line
Support & Release Strategy
Architecture overview
Spring overview
1·18
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
Introduction
Product Line
Support & Release Strategy
Architecture overview
Spring overview
1·21
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
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
1·25
Cluster
hybris Cluster
db
1·26
Introduction
Product Line
Support & Release Strategy
Architecture overview
Spring overview
1·27
Overview
Demo
Overview
Demo
hybris commerce
Accelerator
3
Overview
Benefits
Features
A Long-Term Vision
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
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
Integration
Platform Functionality
11
Overview
Benefits
Features
A Long-Term Vision
organization
management, quote
negotiation, order
management
Easy to re-skin
Multi-lingual, multi-currency
out of the box
Built with business users in mind Features 15
Browse products or
refine search
results based on
key attributes;
Price, colour, top
rated, etc.
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
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
Overview
Benefits
Features
A Long-Term Vision
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
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
Development
Environment Setup
2·3
2·4
1. Install the most recent version of the Java Development Kit (JDK 7)
Enter “java –version” to test your Java installation
2·5
2·6
8. Have fun:
localhost:9001/
localhost:9001/hmc
2·7
2·8
2·9
2·10
2·12
2·13
2·14
It can be generated
Load Required Extensions Basic Configuration
2·15
<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
2·17
<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
4. Do you need to shut down the server while executing ant all?
2·19
2·20
2·21
+ =
Apache Tomcat
What is the hybris Server? Bundled Servers
2·22
2·23
2·24
2·26
2·28
Administration
Monitoring
Configuration
localhost:9001/
(by default)
2·29
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
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
2·36
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
2·38
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
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
{ext-name}-spring.xml
web-application-config.xml
Beans are available only for selected extension and per tenant
How to Create a New Extension Extension Concept
2·43
2·44
2·45
2·47
2·48
2·49
2·50
2·51
2·52
2·53
2·54
Data Modeling
3·3
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
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
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
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
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
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
fuel gasoline
{ gasoline | diesel | ethanol }
mechanic Nikola Tesla
<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
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
4. In hybris, can you create new types, or only extend existing types?
3·17
<collectiontype code="StringCollection"
elementtype="java.lang.String" autocreate="true“ />
<collectiontype code="LanguageCollection"
elementtype="Language" autocreate="true"/>
...
3·18
Category Product
CategoryProductRelation
3·19
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
mytypes
Car
O-R Mapping – Deployment Example Deployment
3·22
GenericItem genericitem
mytypes
Car car
<itemtype code="Car" …
<deployment table="cars"
typecode="20100" …
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
product
code vehicle01
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
PK name car …
PK code … 8796128083972 André-Marie Ampère 5553620010023 …
8796256894977 vehicle01 … 5443669878887 C.-A. de Coulomb 5553620010023
product
O-R Mapping – Deployment of Relations • 2 Deployment
3·26
Many-to-Many
New database table which holds the source and target PKs
PK code …
8796256894977 3776876789221 PK code …
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"/>
...
product
Quiz Questions
3·28
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 Management
Console
4·3
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
4·7
Toolbar
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
4·16
4·17
You can clear the hMC layout definition stored in the database
manually via the hybris Administration Console:
4·18
4·19
4·21
4·22
2. When would you use the hMC and when would you use the
hybris Administration Console?
PCM basics
3
Internationalization
Catalogs
Media Management in hybris
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
Internationalization
Catalogs
Media Management in hybris
Internationalization
Catalogs
Media Management in hybris
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
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
Flexible Search
3
Overview
Syntax
API examples
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
Basic Syntax:
SELECT <selects> FROM {types} (where <conditions>)
?(ORDER BY <order>)?
Mandatory:
SELECT <selects>
FROM {types}
Optional:
where <conditions>
ORDER BY <order>
Simple queries:
Product
SELECT {code},{hp} FROM {Car}
+ hp: int
SELECT {code} FROM {Product!} + kw: int
+ fuel: enumeration
Joins: 1 car
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
query.setNeedTotal( true );
query.setCount( range );
query.setStart( start );
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
Impex
3
Overview
Syntax and examples
Invoking
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
Overview
Syntax and Examples
Invoking
Header syntax:
Operation itemType; attributes(refAttr)[modifiers];...
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 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.
$catalogVersion=catalogVersion(Catalog(id),version)[unique=true]
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.
$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
INSERT_UPDATE Employee;@password[translator=PasswordTranslator]
;aVeryStrongPassword;
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
Hint:
You may use the “Script Generator” in the hMC.
17
Overview
Syntax and examples
Invoking
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, ...)
Database
ServiceLayer – Structure and Data Objects Architecture of the Service Layer 5
6
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
Model Runtime
ModelService
Database
Using Models Models 14
Factory Method:
ProductModel product = modelService.create(ProductModel.class);
Constructor:
ProductModel product = new ProductModel();
15
Model Runtime
ModelService
Database
Implementing interceptors Interceptors 18
<bean id="myLoadMapping"
class="de...interceptor.impl.InterceptorMapping">
<bean id="myEventListener"
class="my.package.MyEventListener"/>
@Resource
EventService eventService;
eventService.registerEventListener( new MyEventListener() );
Event Service Events 26
@Override
public boolean publish(final int sourceNodeId,
final int targetNodeId)
{
return (sourceNodeId == targetNodeId);
}
Transaction-Aware Events Events 29
getId: two events with the same id will be published only once
Predefined Events – ClusterAware and TransactionAware Events Events 30
2. Name 3 services