SlideShare ist ein Scribd-Unternehmen logo
1 von 56
Discussion document – Strictly Confidential & Proprietary
Dynamically Generate a
CRUD Admin Panel with
Java Annotations
2
About me
• https://github.com/phillipuniverse, @phillipuniverse, Phillip Verheyden
• Architect at Broadleaf Commerce
• I like playground equipment and one time I saw Colbert
3
Customizing the Broadleaf Admin …
Overview
Annotations
– Basics
– Supported Field Types
– Broadleaf Enumerations
– Lookup Fields
– Collection Types
– Help, Tooltips
– Validation Support
– Overriding Annotations
Other Topics
• Security Model
• Persistence API View Layer
4
Broadleaf Open Admin
• Why?
– Broadleaf Commerce
 broadleaf-admin-module vs broadleaf-open-admin-platform
– Extensible and generic at every level (frontend, backend, controller)
• Open Admin frontend history
– Open Admin v1 – Adobe Flex (~2010)
– Open Admin v2 – GWT (~2011)
– Open Admin v3 (current) – Spring MVC + Thymeleaf (~2013)
5
Admin Customizations … Overview …
Open Admin Benefits
• Quickly build and modify CRUD screens using metadata
• Rich, extensible security model
• Easy customizations are easy
– Hide / show fields
– Change labels, field ordering, and grouping
– Adding new managed fields and managed entities
– Add new actions, menu items, validations
Admin Annotation Basics
6
7
Admin Customizations … Annotation Basics …
Let’s start by looking at some basic annotations …
@Column(name = "FIRST_NAME")
protected String firstName;
CustomerImpl.java
No annotations on
firstName field …
Results in no input field
on the customer form.
8
Admin Customizations … Annotation Basics …
Next, let’s add in an empty “AdminPresentation”
annotation …
@Column(name = "FIRST_NAME")
@AdminPresentation()
protected String firstName;
CustomerImpl.java
Added @AdminPresentation
annotation
Field was added to the
form using the property
name in the default
“group” on the default
“tab”
9
Admin Customizations … Annotation Basics …
Add a “friendlyName” to fix the label …
@Column(name = "FIRST_NAME")
@AdminPresentation(friendlyName = “First Name”)
protected String firstName;
CustomerImpl.java
Added friendlyName …
Label is now “First
Name”
Note:
Broadleaf attempts to resolve
the friendlyName from a messages
file to allow for i18n labels.
10
Admin Customizations … Annotation Basics …
Finally, let’s position the field just before the Last
Name field on the form …
@Column(name = "FIRST_NAME")
@AdminPresentation(
friendlyName = “First Name”,
order = 2000,
group = “Customer”
) protected String firstName;
CustomerImpl.java
That’s what we want!
Why 2,000 for the order?
We looked at the emailAddress and
lastName properties in
CustomerImpl.java whose orders were
set to 1,000 and 3,000 and chose a
number in between the two.
We could have used 1,001 or 2,999.
Added “order” and
“group”
11
Admin Customizations … Annotation Basics …
You can also annotate fields to show up on the
Admin list grids …
List Grid Before
And After …
@Column(name = "FIRST_NAME")
@AdminPresentation(
friendlyName = “First Name”,
prominent = true,
gridOrder = “2000”
) protected String firstName;
CustomerImpl.java
“prominent=true” means show
on list grids
Supported Field Types
12
13
Admin Customizations … Supported Field Types …
The admin has support for common field types …
Related Entity LookupsMoney Fields
Radio Selectors
Drop Down Selectors
Date Fields
Media LookupsBoolean Fields
14
Admin Customizations … Supported Field Types …
Supported Field Types (cont.)
• For simple types, the supported field type is derived from the property
type (String, Integer, Date, etc.)
• Other field types require configuration and additional annotations.
We’ll cover some of those on the upcoming slides …
• For a complete list of supported field types, see
SupportedFieldType.java
Broadleaf Enumerations
15
public class OfferDiscountType implements BroadleafEnumerationType {
private static final Map<String, OfferDiscountType> TYPES =
new LinkedHashMap<String, OfferDiscountType>();
public static final OfferDiscountType PERCENT_OFF =
new OfferDiscountType("PERCENT_OFF", "Percent Off");
public static final OfferDiscountType AMOUNT_OFF =
new OfferDiscountType("AMOUNT_OFF", "Amount Off");
public static final OfferDiscountType FIX_PRICE =
new OfferDiscountType("FIX_PRICE", "Fixed Price");
public static OfferDiscountType getInstance(final String type) {
return TYPES.get(type);
}
16
Admin Customizations … Broadleaf Enumerations …
Broadleaf provides support for extensible
enumerations
A Broadleaf Enumeration
– Is used for many of the radio and drop-down selection lists in the admin
– Allows the framework to provide enum like functionality in a way that can
be extended by custom implementations
Example
17
Admin Customizations … Broadleaf Enumerations …
You can use an enumeration for String types
@Column(name = "OFFER_DISCOUNT_TYPE")
@AdminPresentation(
friendlyName = ”Discount Type”,
fieldType=SupportedFieldType.BROADLEAF_ENUMERATION,
broadleafEnumeration=”org...OfferDiscountType")
protected String type;
public OfferDiscountType getDiscountType() {
return OfferDiscountType.getInstance(type);
}
public void setDiscountType(OfferDiscountType type) {
this.type = type.getType();
}
Example from OfferImpl.java
Getters and setters return
the enumeration type
Specify the enumeration
type and the class
Produces This …
By default, if less than 5
options, a radio is displayed.
Otherwise the system shows a
dropdown selector.
18
Admin Customizations … Broadleaf Enumerations …
Broadleaf also provides support for “data-driven”
enumerations
• Allow selection values in the admin to come from a database table
• Allows system to add new values without a deployment
• Used with the @AdminPresentationDataDrivenEnumeration
annotation
• Values are stored in BLC_DATA_DRVN_ENUM and
BLC_DATA_DRVN_ENUM_VALUE tables
@Column(name = ”TAX_CODE")
@AdminPresentation(friendlyName = ”Tax Code”)
@AdminPresentationDataDrivenEnumeration(
optionFilterParams = {
@OptionFilterParam(
param = "type.key", value = "TAX_CODE",
paramType = OptionFilterParamType.STRING) })
Example from SkuImpl.java
Lookup Fields
19
Admin Customizations … Lookup Fields …
Adding a lookup to a JPA ManyToOne related fields
can be done with a simple annotation
@ManyToOne(targetEntity=CategoryImpl.class)
Column(name = ”DEFAULT_CATEGORY_ID”)
@AdminPresentation(friendlyName=‘Default Category’)
@AdminPresentationToOneLookup()
protected Category defaultCategory;
ProductImpl.java
Products have a category lookup
to set the default category.
Produces This Field … Click
lookup
Click here to show a popup with
a read view of the entity detail
21
Admin Customizations … Lookup Fields …
Lookup fields can also show up on list grids …
When a lookup field (like defaultCategory) is marked as “prominent”,
additional features surface …
List grids can be filtered by the
corresponding related entity.
Collections
22
23
Admin Customizations … Collections …
The admin supports a wide variety of grid
interactions with annotations …
Most @OneToMany and @ManyToMany JPA relationships can be
modeled as functional list grids in the admin with annotations …
Examples (we’ll cover each of these)
• Add items to a list
• Create items and then add to a list
• Add items to a “Map” collection where a key must also be provided
• Add items to a list with additional mapping attributes
24
Admin Customizations … Collections … Product Options …
Adding product options to a product, shows an
example of choosing from a list of existing items
@ManyToMany(targetEntity = ProductOptionImpl.class)
@JoinTable(name=“BLC_PRODUCT_OPTION_XREF …)
@AdminPresentationCollection(
friendlyName = ”Product Options",
manyToField = "products”,
addType = AddMethodType.LOOKUP,
operationTypes = @AdminPresentationOperationTypes(
removeType = OperationType.NONDESTRUCTIVEREMOVE)
)
protected List<ProductOption> productOptions;
ProductImpl.java
Indicates that we will be
looking up existing values
instead of creating new ones
If the option is deleted from
the product, it will not also
attempt to delete the option
Hit
Add
25
Admin Customizations … Collections … Product Options …
When adding offer codes to an offer, we want to
create the code first and then add it …
@OneToMany(targetEntity = OfferCodeImpl.class)
@AdminPresentationCollection(
friendlyName = ”Offer Codes”,
addType = AddMethodType.PERSIST)
protected List<OfferCode> offerCodes;
OfferImpl.java
Indicates that we will be
creating new “Offer Codes”
Hit
Add
26
Admin Customizations … Collections … Product Attributes …
For Map collections like Product Attributes, we
need to also provide a key when adding the item …
@ManyToMany(targetEntity = ProductAttributeImpl.class)
@MapKey(name=“name”)
@AdminPresentationMap(
friendlyName = ”Product Attributes”,
deleteEntityOnRemove = true,
forceFreeFormKeys = true,
keyPropertyFriendlyName = “Key”
addType = AddMethodType.PERSIST)
protected Map<String, ProductAttribute>;
ProductImpl.java
Map properties introduce a few new
properties to control delete
behavior and how keys are
managed.
Hit
Add
27
Admin Customizations … Collections … Category Media Map …
The Map used for Category Media uses a bit more
of the “Map” functionality …
@ManyToMany(targetEntity = MediaImpl.class)
@JoinTable(…)
@MapKeyColumn(name=“MAP_KEY”)
@AdminPresentationMap(
friendlyName = ”Media”,
deleteEntityOnRemove = true,
keyPropertyFriendlyName = “Key” ,
mediaField = “url”,
keys = {
@AdminPresentationMapKey(
keyName = “primary”),
@AdminPresentationMapKey(
keyName = “alt1”),
... })
protected Map<String, Media> categoryMedia;
CategorytImpl.java
Category media, shows an example
of explicitly defined Map keys.
Media
fields
Key
28
Admin Customizations … Collections … Adorned Collections …
Some collections need additional properties as part
of the join … referred to as “adorned” collections
@OneToMany(targetEntity = FeaturedProductImpl.class)
@AdminPresentationAdornedTargetCollection (
friendlyName = ”Featured Products”,
targetObjectProperty = product,
maintainedAdornedTargetFields = {
“promotionMessage”})
protected List<FeaturedProduct> featuredProducts;
CategoryImpl.java
To add a featured product, we are
looking up the product and
providing values to additional fields
on the FeaturedProduct class.
Hit
Add
Select
Product
Help and Tooltips
29
30
Admin Customizations … Help and Tooltips …
You can add contextual help to fields in the admin …
@Column(name = "FIRST_NAME")
@AdminPresentation(
friendlyName = “First Name”,
helpText = "This is help text",
hint = "This is a hint.",
tooltip = "This is a tooltip.”
)
protected String firstName;
CustomerImpl.java
Validation
31
32
Admin Customizations … Validation …
There are several approaches to adding validation
to fields managed in the admin …
Via @ValidationConfiguration Annotations
Broadleaf provides an admin annotation to add validations along with
several out-of-box implementations
Using JSR 303 Style Validations
Broadleaf can leverage Spring MVC JSR-303 validations
By adding validation logic in a Custom Persistence Handler
More on Custom Persistence Handlers later
33
Admin Customizations … Validation … Required Fields …
A field can be marked as required via annotation
@Column(name = "FIRST_NAME")
@AdminPresentation(
requiredOverride = RequiredOverride.REQUIRED)
protected String firstName;
CustomerImpl.java
Result
Required fields are noted in the
admin with an asterisk.
Normally, required or not-required
is derived based on the database
column (e.g. non-null = required).
You can override this as shown.
34
Admin Customizations … Validation … Example Annotation …
Example : Add a RegEx validator to customer
name
@Column(name = "FIRST_NAME")
@AdminPresentation(
validationConfigurations = {
@ValidationConfiguration(
validationImplementation=“blRegExPropertyValidator”,
configurationItems={
@ConfigurationItem(itemName="regularExpression", itemValue = "w+"),
@ConfigurationItem(itemName=ConfigurationItem.ERROR_MESSAGE,
itemValue = ”Only word chars are allowed.”)
}
)
protected String firstName;
CustomerImpl.java
Result 
In this example, first name
must be valid for this Regular
Expression
35
Admin Customizations … Validation … Custom Validators …
You can create custom admin validators …
To create a custom property validator, implement the PropertyValidator
interface …
public PropertyValidationResult validate(
Entity entity,
Serializable instance,
Map<String, FieldMetadata> entityFieldMetadata,
Map<String, String> validationConfiguration,
BasicFieldMetadata propertyMetadata,
String propertyName,
String value);
This interface looks a bit daunting but is easy to implement. See the
JavaDocs or just go straight to an out of box implementation like …
org.broadleafcommerce.openadmin.server.
service.persistence.validation.RegexPropertyValidator
36
Admin Customizations … Validation … JSR 303 …
You can add support for JSR-303 validation by
modifying your application context
• Allows for @Email, @URL etc. from hibernate-validator
– Same structure as Spring MVC @Valid annotation
• Add two lines to applicationContext.xml to enable support for JSR-303
<bean id="blEntityValidatorService"
class="org.broadleafcommerce.openadmin.server.service.persistence.
validation.BeanValidationEntityValidatorServiceImpl" />
<bean class="org.springframework.validation.beanvalidation.
LocalValidatorFactoryBean" />
applicationContext.xml
Admin Customizations ... View Layer
Frontend Validation
BLCAdmin.addPreValidationSubmitHandler(function($form) {
// modify the form data prior to sending to the server
});
BLCAdmin.addValidationSubmitHandler(function($form) {
// return false to stop the form from submitting
});
BLCAdmin.addPostValidationSubmitHandler(function($form) {
// do work after receiving a response from the server
});
Annotation Overrides
38
39
Admin Customizations … Annotation Overrides …
Broadleaf provides two methods for overriding
annotations
• In the examples so far, the annotations changes were directly made as part
of the @AdminPresentation
• Since you cannot modify Broadleaf classes, additional mechanisms are
provided to allow you to override (or add to) the out of box annotations
• Method 1 : Override Using XML
- Add overrides to adminApplicationContext.xml
- Use the mo schema (see mo-3.0.xsd for info)
• Method 2 : Use the class level annotation
“@AdminPresentationMergeOverride”
- Convenient when extending a Broadleaf class
40
Admin Customizations … Annotation Overrides … Using XML …
Override Using XML …
The example below makes the Customer firstName property required
and adds help text.
<mo:override id="blMetadataOverrides">
<mo:overrideItem ceilingEntity = "org.broadleafcommerce…Customer">
<mo:field name=“firstName”>
<mo:property name="requiredOverride” value="true"/>
<mo:property name="helpText" value="This is help text"/>
</mo:field>
</mo:overrideItem>
</mo:override>
applicationContext.xml
Get IDE auto-completion by updating your applicationContext-admin.xml file beans tag
to include …
• Update schemaLocations with
http://schema.broadleafcommerce.org/mo and
http://schema.broadleafcommerce.org/mo/mo-3.0.xsd
• Add the namespace … xmlns:mo="http://schema.broadleafcommerce.org/mo
41
Admin Customizations … Annotation Overrides … Using Extended Class Annotation …
Override using Extended Class Annotation …
The example below makes the Customer firstName property required
and adds help text using annotations on a derived class
@AdminPresentationMergeOverrides(
{
@AdminPresentationMergeOverride(name = ”firstName", mergeEntries =
{
@AdminPresentationMergeEntry(
propertyType=PropertyType.AdminPresentation.REQUIREDOVERRIDE,
booleanOverrideValue = true)
@AdminPresentationMergeEntry(
propertyType=PropertyType.AdminPresentation.HELPTEXT,
overrideValue = “This is help text”)
}
}
)
public class MyCustomerImpl extends CustomerImpl {
MyCustomer.java
Demo
42
Admin Security
43
44
Admin Customizations ... Admin Security
Security Model
• Entity-based permissions – permission to perform a CRUD operation
• If the admin user has no permissions in a particular section, that
section is not shown
• All permissions are rolled up into the Spring Security Principal’s
GrantedAuthorities
45
Admin Customizations ... Admin Security
Role Management
Admin Customizations ... Admin Security
Invisible Modules/Sections
47
Admin Customizations ... Admin Security
Row-level Security
• Finer-grained control over security on a particular row vs an entity type
as a whole
• Additional fetch criteria, readonly rows, prevent deletions of rows
• Javadocs for RowLevelSecurityProvider
@Component
public class ProductStoreRowSecurityProvider {
public void addFetchRestrictions(AdminUser currentUser,
String ceilingEntity,
List<Predicate> restrictions,
Root root,
CriteriaQuery criteria,
CriteriaBuilder criteriaBuilder) {
Store adminStore = ((MyAdminuser) currentUser).getStore();
Predicate storeRestriction = criteriaBuilder.equal(root.get("store"),
adminStore);
restrictions.add(storeRestriction);
}
48
Admin Customizations ... Admin Security
Other security features
• CSRF protection
– Token automatically generated and checked
• XSS protection
– Turned off by default for CMS functionality
– OWASP AntiSamy
 Example Broadleaf Myspace AntiSamy configuration file
<bean id="blExploitProtectionService"
class="org.broadleafcommerce.common.security.service.ExploitProtectionServiceImpl
">
<property name="xsrfProtectionEnabled”
value="true" />
<property name="xssProtectionEnabled”
value="false" />
<property name="antiSamyPolicyFileLocation”
value="the_location_of_your_file" />
</bean>
Other Extension Points
49
Admin Spring MVC Controller
50
Admin Customizations ... Admin persistence APIs
Admin Persistence – Request Flow
DynamicEntityRemoteService
PersistenceManager
PersistenceModuleCustomPersistenceHandler
DynamicEntityDao
FieldMetadataProvider
FieldPersistenceProvider
Transaction boundary starts here
Database
EntityValidatorService
PersistenceEventHandler
51
Admin Customizations ... View Layer
Spring MVC
• AdminBasicEntityController
– Provides facilities for all CRUD operations
– Generic request mapping using path parameters
 @RequestMapping("/{sectionKey:.+}")
– Custom controllers can override the request mapping with a specific URL
Generic Broadleaf admin controller
Specific customer controller (intercepts all methods to “/customer/”)…
@Controller("blAdminBasicEntityController")
@RequestMapping("/{sectionKey:.+}”)
public class AdminBasicEntityController extends AdminAbstractController {
...
}
@Controller
@RequestMapping("/customer”)
public class AdminCustomerController extends AdminBasicEntityController {
...
}
52
Admin Customizations ... View Layer
Admin Template Overrides
• Thymeleaf template resolution (TemplateResolver)
– Create custom templates in /WEB-INF/templates/admin
– Add custom resolvers to the blAdminWebTemplateResolvers list bean
– Example – override all strings entity fields to always load an HTML editor
/WEB-INF/templates/admin/fields/string.html
classpath:open_admin_style/templates/fields/string.html
classpath:/common_style/templates/fields/string.html
<div th:include=“fields/string.html” th:remove=“tag” />
locate fields/string.html
could not find
could not find
53
Admin Customizations ... View Layer
ListGrid
• Relationships (subgrids) as well as main grids
• Toolbar buttons
• ListGrid.Type
54
Admin Customizations ... View Layer
HTML Fields
• WYSIWYG editor by Redactor
• Redactor has its own extensible plugin API
• Additional extensions and/or customizations should add an
initialization handler
55
Admin Customizations ... View Layer
Example frontend customizations
Broadleaf Commerce Admin Demo
56

Weitere ähnliche Inhalte

Was ist angesagt?

Grails Simple Login
Grails Simple LoginGrails Simple Login
Grails Simple Login
moniguna
 

Was ist angesagt? (20)

Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
Logback
LogbackLogback
Logback
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Meetup angular http client
Meetup angular http clientMeetup angular http client
Meetup angular http client
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
 
Grails Simple Login
Grails Simple LoginGrails Simple Login
Grails Simple Login
 
AngularJS
AngularJSAngularJS
AngularJS
 
React
React React
React
 
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling StrategiesWebscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
 
Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
 
Angular tutorial
Angular tutorialAngular tutorial
Angular tutorial
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
 
Grails Connecting to MySQL
Grails Connecting to MySQLGrails Connecting to MySQL
Grails Connecting to MySQL
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 

Andere mochten auch

Andere mochten auch (8)

Open Admin
Open AdminOpen Admin
Open Admin
 
Temparate Broadleaf Deciduous Forest
Temparate Broadleaf Deciduous ForestTemparate Broadleaf Deciduous Forest
Temparate Broadleaf Deciduous Forest
 
What The Flask? and how to use it with some Google APIs
What The Flask? and how to use it with some Google APIsWhat The Flask? and how to use it with some Google APIs
What The Flask? and how to use it with some Google APIs
 
Broadleaf health and Education pitch for Gravity Payments- Gravity Gives
Broadleaf health and Education pitch for Gravity Payments- Gravity GivesBroadleaf health and Education pitch for Gravity Payments- Gravity Gives
Broadleaf health and Education pitch for Gravity Payments- Gravity Gives
 
Play Framework on Google App Engine
Play Framework on Google App EnginePlay Framework on Google App Engine
Play Framework on Google App Engine
 
мир без Jsp. thymeleaf 2.0
мир без Jsp. thymeleaf 2.0мир без Jsp. thymeleaf 2.0
мир без Jsp. thymeleaf 2.0
 
Setting up a free open source java e-commerce website
Setting up a free open source java e-commerce websiteSetting up a free open source java e-commerce website
Setting up a free open source java e-commerce website
 
How Global Trends are Shaping the Retail Technology of the Future
How Global Trends are Shaping the Retail Technology of the FutureHow Global Trends are Shaping the Retail Technology of the Future
How Global Trends are Shaping the Retail Technology of the Future
 

Ähnlich wie Dynamically Generate a CRUD Admin Panel with Java Annotations

Breaking down data silos with the open data protocol
Breaking down data silos with the open data protocolBreaking down data silos with the open data protocol
Breaking down data silos with the open data protocol
Woodruff Solutions LLC
 
sfDay Cologne - Sonata Admin Bundle
sfDay Cologne - Sonata Admin BundlesfDay Cologne - Sonata Admin Bundle
sfDay Cologne - Sonata Admin Bundle
th0masr
 
Deep dive formatting
Deep dive formattingDeep dive formatting
Deep dive formatting
Thomas Lee
 

Ähnlich wie Dynamically Generate a CRUD Admin Panel with Java Annotations (20)

Breaking down data silos with the open data protocol
Breaking down data silos with the open data protocolBreaking down data silos with the open data protocol
Breaking down data silos with the open data protocol
 
sfDay Cologne - Sonata Admin Bundle
sfDay Cologne - Sonata Admin BundlesfDay Cologne - Sonata Admin Bundle
sfDay Cologne - Sonata Admin Bundle
 
Reflection Slides by Zubair Dar
Reflection Slides by Zubair DarReflection Slides by Zubair Dar
Reflection Slides by Zubair Dar
 
Reflection in C Sharp
Reflection in C SharpReflection in C Sharp
Reflection in C Sharp
 
A Tour to MySQL Commands
A Tour to MySQL CommandsA Tour to MySQL Commands
A Tour to MySQL Commands
 
Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3
 
Reflection
ReflectionReflection
Reflection
 
DJango admin interface
DJango admin interfaceDJango admin interface
DJango admin interface
 
VB_ERROR CONTROL_FILE HANDLING.ppt
VB_ERROR CONTROL_FILE HANDLING.pptVB_ERROR CONTROL_FILE HANDLING.ppt
VB_ERROR CONTROL_FILE HANDLING.ppt
 
Clean Code
Clean CodeClean Code
Clean Code
 
L0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsL0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard Views
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Django design-patterns
Django design-patternsDjango design-patterns
Django design-patterns
 
S313431 JPA 2.0 Overview
S313431 JPA 2.0 OverviewS313431 JPA 2.0 Overview
S313431 JPA 2.0 Overview
 
Swift as an OOP Language
Swift as an OOP LanguageSwift as an OOP Language
Swift as an OOP Language
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Working With The Symfony Admin Generator
Working With The Symfony Admin GeneratorWorking With The Symfony Admin Generator
Working With The Symfony Admin Generator
 
Practical Google App Engine Applications In Py
Practical Google App Engine Applications In PyPractical Google App Engine Applications In Py
Practical Google App Engine Applications In Py
 
Deep dive formatting
Deep dive formattingDeep dive formatting
Deep dive formatting
 
Two scoopsofdjango ch16 dealing with the user model
Two scoopsofdjango ch16   dealing with the user modelTwo scoopsofdjango ch16   dealing with the user model
Two scoopsofdjango ch16 dealing with the user model
 

Kürzlich hochgeladen

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Kürzlich hochgeladen (20)

AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

Dynamically Generate a CRUD Admin Panel with Java Annotations

  • 1. Discussion document – Strictly Confidential & Proprietary Dynamically Generate a CRUD Admin Panel with Java Annotations
  • 2. 2 About me • https://github.com/phillipuniverse, @phillipuniverse, Phillip Verheyden • Architect at Broadleaf Commerce • I like playground equipment and one time I saw Colbert
  • 3. 3 Customizing the Broadleaf Admin … Overview Annotations – Basics – Supported Field Types – Broadleaf Enumerations – Lookup Fields – Collection Types – Help, Tooltips – Validation Support – Overriding Annotations Other Topics • Security Model • Persistence API View Layer
  • 4. 4 Broadleaf Open Admin • Why? – Broadleaf Commerce  broadleaf-admin-module vs broadleaf-open-admin-platform – Extensible and generic at every level (frontend, backend, controller) • Open Admin frontend history – Open Admin v1 – Adobe Flex (~2010) – Open Admin v2 – GWT (~2011) – Open Admin v3 (current) – Spring MVC + Thymeleaf (~2013)
  • 5. 5 Admin Customizations … Overview … Open Admin Benefits • Quickly build and modify CRUD screens using metadata • Rich, extensible security model • Easy customizations are easy – Hide / show fields – Change labels, field ordering, and grouping – Adding new managed fields and managed entities – Add new actions, menu items, validations
  • 7. 7 Admin Customizations … Annotation Basics … Let’s start by looking at some basic annotations … @Column(name = "FIRST_NAME") protected String firstName; CustomerImpl.java No annotations on firstName field … Results in no input field on the customer form.
  • 8. 8 Admin Customizations … Annotation Basics … Next, let’s add in an empty “AdminPresentation” annotation … @Column(name = "FIRST_NAME") @AdminPresentation() protected String firstName; CustomerImpl.java Added @AdminPresentation annotation Field was added to the form using the property name in the default “group” on the default “tab”
  • 9. 9 Admin Customizations … Annotation Basics … Add a “friendlyName” to fix the label … @Column(name = "FIRST_NAME") @AdminPresentation(friendlyName = “First Name”) protected String firstName; CustomerImpl.java Added friendlyName … Label is now “First Name” Note: Broadleaf attempts to resolve the friendlyName from a messages file to allow for i18n labels.
  • 10. 10 Admin Customizations … Annotation Basics … Finally, let’s position the field just before the Last Name field on the form … @Column(name = "FIRST_NAME") @AdminPresentation( friendlyName = “First Name”, order = 2000, group = “Customer” ) protected String firstName; CustomerImpl.java That’s what we want! Why 2,000 for the order? We looked at the emailAddress and lastName properties in CustomerImpl.java whose orders were set to 1,000 and 3,000 and chose a number in between the two. We could have used 1,001 or 2,999. Added “order” and “group”
  • 11. 11 Admin Customizations … Annotation Basics … You can also annotate fields to show up on the Admin list grids … List Grid Before And After … @Column(name = "FIRST_NAME") @AdminPresentation( friendlyName = “First Name”, prominent = true, gridOrder = “2000” ) protected String firstName; CustomerImpl.java “prominent=true” means show on list grids
  • 13. 13 Admin Customizations … Supported Field Types … The admin has support for common field types … Related Entity LookupsMoney Fields Radio Selectors Drop Down Selectors Date Fields Media LookupsBoolean Fields
  • 14. 14 Admin Customizations … Supported Field Types … Supported Field Types (cont.) • For simple types, the supported field type is derived from the property type (String, Integer, Date, etc.) • Other field types require configuration and additional annotations. We’ll cover some of those on the upcoming slides … • For a complete list of supported field types, see SupportedFieldType.java
  • 16. public class OfferDiscountType implements BroadleafEnumerationType { private static final Map<String, OfferDiscountType> TYPES = new LinkedHashMap<String, OfferDiscountType>(); public static final OfferDiscountType PERCENT_OFF = new OfferDiscountType("PERCENT_OFF", "Percent Off"); public static final OfferDiscountType AMOUNT_OFF = new OfferDiscountType("AMOUNT_OFF", "Amount Off"); public static final OfferDiscountType FIX_PRICE = new OfferDiscountType("FIX_PRICE", "Fixed Price"); public static OfferDiscountType getInstance(final String type) { return TYPES.get(type); } 16 Admin Customizations … Broadleaf Enumerations … Broadleaf provides support for extensible enumerations A Broadleaf Enumeration – Is used for many of the radio and drop-down selection lists in the admin – Allows the framework to provide enum like functionality in a way that can be extended by custom implementations Example
  • 17. 17 Admin Customizations … Broadleaf Enumerations … You can use an enumeration for String types @Column(name = "OFFER_DISCOUNT_TYPE") @AdminPresentation( friendlyName = ”Discount Type”, fieldType=SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration=”org...OfferDiscountType") protected String type; public OfferDiscountType getDiscountType() { return OfferDiscountType.getInstance(type); } public void setDiscountType(OfferDiscountType type) { this.type = type.getType(); } Example from OfferImpl.java Getters and setters return the enumeration type Specify the enumeration type and the class Produces This … By default, if less than 5 options, a radio is displayed. Otherwise the system shows a dropdown selector.
  • 18. 18 Admin Customizations … Broadleaf Enumerations … Broadleaf also provides support for “data-driven” enumerations • Allow selection values in the admin to come from a database table • Allows system to add new values without a deployment • Used with the @AdminPresentationDataDrivenEnumeration annotation • Values are stored in BLC_DATA_DRVN_ENUM and BLC_DATA_DRVN_ENUM_VALUE tables @Column(name = ”TAX_CODE") @AdminPresentation(friendlyName = ”Tax Code”) @AdminPresentationDataDrivenEnumeration( optionFilterParams = { @OptionFilterParam( param = "type.key", value = "TAX_CODE", paramType = OptionFilterParamType.STRING) }) Example from SkuImpl.java
  • 20. Admin Customizations … Lookup Fields … Adding a lookup to a JPA ManyToOne related fields can be done with a simple annotation @ManyToOne(targetEntity=CategoryImpl.class) Column(name = ”DEFAULT_CATEGORY_ID”) @AdminPresentation(friendlyName=‘Default Category’) @AdminPresentationToOneLookup() protected Category defaultCategory; ProductImpl.java Products have a category lookup to set the default category. Produces This Field … Click lookup Click here to show a popup with a read view of the entity detail
  • 21. 21 Admin Customizations … Lookup Fields … Lookup fields can also show up on list grids … When a lookup field (like defaultCategory) is marked as “prominent”, additional features surface … List grids can be filtered by the corresponding related entity.
  • 23. 23 Admin Customizations … Collections … The admin supports a wide variety of grid interactions with annotations … Most @OneToMany and @ManyToMany JPA relationships can be modeled as functional list grids in the admin with annotations … Examples (we’ll cover each of these) • Add items to a list • Create items and then add to a list • Add items to a “Map” collection where a key must also be provided • Add items to a list with additional mapping attributes
  • 24. 24 Admin Customizations … Collections … Product Options … Adding product options to a product, shows an example of choosing from a list of existing items @ManyToMany(targetEntity = ProductOptionImpl.class) @JoinTable(name=“BLC_PRODUCT_OPTION_XREF …) @AdminPresentationCollection( friendlyName = ”Product Options", manyToField = "products”, addType = AddMethodType.LOOKUP, operationTypes = @AdminPresentationOperationTypes( removeType = OperationType.NONDESTRUCTIVEREMOVE) ) protected List<ProductOption> productOptions; ProductImpl.java Indicates that we will be looking up existing values instead of creating new ones If the option is deleted from the product, it will not also attempt to delete the option Hit Add
  • 25. 25 Admin Customizations … Collections … Product Options … When adding offer codes to an offer, we want to create the code first and then add it … @OneToMany(targetEntity = OfferCodeImpl.class) @AdminPresentationCollection( friendlyName = ”Offer Codes”, addType = AddMethodType.PERSIST) protected List<OfferCode> offerCodes; OfferImpl.java Indicates that we will be creating new “Offer Codes” Hit Add
  • 26. 26 Admin Customizations … Collections … Product Attributes … For Map collections like Product Attributes, we need to also provide a key when adding the item … @ManyToMany(targetEntity = ProductAttributeImpl.class) @MapKey(name=“name”) @AdminPresentationMap( friendlyName = ”Product Attributes”, deleteEntityOnRemove = true, forceFreeFormKeys = true, keyPropertyFriendlyName = “Key” addType = AddMethodType.PERSIST) protected Map<String, ProductAttribute>; ProductImpl.java Map properties introduce a few new properties to control delete behavior and how keys are managed. Hit Add
  • 27. 27 Admin Customizations … Collections … Category Media Map … The Map used for Category Media uses a bit more of the “Map” functionality … @ManyToMany(targetEntity = MediaImpl.class) @JoinTable(…) @MapKeyColumn(name=“MAP_KEY”) @AdminPresentationMap( friendlyName = ”Media”, deleteEntityOnRemove = true, keyPropertyFriendlyName = “Key” , mediaField = “url”, keys = { @AdminPresentationMapKey( keyName = “primary”), @AdminPresentationMapKey( keyName = “alt1”), ... }) protected Map<String, Media> categoryMedia; CategorytImpl.java Category media, shows an example of explicitly defined Map keys. Media fields Key
  • 28. 28 Admin Customizations … Collections … Adorned Collections … Some collections need additional properties as part of the join … referred to as “adorned” collections @OneToMany(targetEntity = FeaturedProductImpl.class) @AdminPresentationAdornedTargetCollection ( friendlyName = ”Featured Products”, targetObjectProperty = product, maintainedAdornedTargetFields = { “promotionMessage”}) protected List<FeaturedProduct> featuredProducts; CategoryImpl.java To add a featured product, we are looking up the product and providing values to additional fields on the FeaturedProduct class. Hit Add Select Product
  • 30. 30 Admin Customizations … Help and Tooltips … You can add contextual help to fields in the admin … @Column(name = "FIRST_NAME") @AdminPresentation( friendlyName = “First Name”, helpText = "This is help text", hint = "This is a hint.", tooltip = "This is a tooltip.” ) protected String firstName; CustomerImpl.java
  • 32. 32 Admin Customizations … Validation … There are several approaches to adding validation to fields managed in the admin … Via @ValidationConfiguration Annotations Broadleaf provides an admin annotation to add validations along with several out-of-box implementations Using JSR 303 Style Validations Broadleaf can leverage Spring MVC JSR-303 validations By adding validation logic in a Custom Persistence Handler More on Custom Persistence Handlers later
  • 33. 33 Admin Customizations … Validation … Required Fields … A field can be marked as required via annotation @Column(name = "FIRST_NAME") @AdminPresentation( requiredOverride = RequiredOverride.REQUIRED) protected String firstName; CustomerImpl.java Result Required fields are noted in the admin with an asterisk. Normally, required or not-required is derived based on the database column (e.g. non-null = required). You can override this as shown.
  • 34. 34 Admin Customizations … Validation … Example Annotation … Example : Add a RegEx validator to customer name @Column(name = "FIRST_NAME") @AdminPresentation( validationConfigurations = { @ValidationConfiguration( validationImplementation=“blRegExPropertyValidator”, configurationItems={ @ConfigurationItem(itemName="regularExpression", itemValue = "w+"), @ConfigurationItem(itemName=ConfigurationItem.ERROR_MESSAGE, itemValue = ”Only word chars are allowed.”) } ) protected String firstName; CustomerImpl.java Result  In this example, first name must be valid for this Regular Expression
  • 35. 35 Admin Customizations … Validation … Custom Validators … You can create custom admin validators … To create a custom property validator, implement the PropertyValidator interface … public PropertyValidationResult validate( Entity entity, Serializable instance, Map<String, FieldMetadata> entityFieldMetadata, Map<String, String> validationConfiguration, BasicFieldMetadata propertyMetadata, String propertyName, String value); This interface looks a bit daunting but is easy to implement. See the JavaDocs or just go straight to an out of box implementation like … org.broadleafcommerce.openadmin.server. service.persistence.validation.RegexPropertyValidator
  • 36. 36 Admin Customizations … Validation … JSR 303 … You can add support for JSR-303 validation by modifying your application context • Allows for @Email, @URL etc. from hibernate-validator – Same structure as Spring MVC @Valid annotation • Add two lines to applicationContext.xml to enable support for JSR-303 <bean id="blEntityValidatorService" class="org.broadleafcommerce.openadmin.server.service.persistence. validation.BeanValidationEntityValidatorServiceImpl" /> <bean class="org.springframework.validation.beanvalidation. LocalValidatorFactoryBean" /> applicationContext.xml
  • 37. Admin Customizations ... View Layer Frontend Validation BLCAdmin.addPreValidationSubmitHandler(function($form) { // modify the form data prior to sending to the server }); BLCAdmin.addValidationSubmitHandler(function($form) { // return false to stop the form from submitting }); BLCAdmin.addPostValidationSubmitHandler(function($form) { // do work after receiving a response from the server });
  • 39. 39 Admin Customizations … Annotation Overrides … Broadleaf provides two methods for overriding annotations • In the examples so far, the annotations changes were directly made as part of the @AdminPresentation • Since you cannot modify Broadleaf classes, additional mechanisms are provided to allow you to override (or add to) the out of box annotations • Method 1 : Override Using XML - Add overrides to adminApplicationContext.xml - Use the mo schema (see mo-3.0.xsd for info) • Method 2 : Use the class level annotation “@AdminPresentationMergeOverride” - Convenient when extending a Broadleaf class
  • 40. 40 Admin Customizations … Annotation Overrides … Using XML … Override Using XML … The example below makes the Customer firstName property required and adds help text. <mo:override id="blMetadataOverrides"> <mo:overrideItem ceilingEntity = "org.broadleafcommerce…Customer"> <mo:field name=“firstName”> <mo:property name="requiredOverride” value="true"/> <mo:property name="helpText" value="This is help text"/> </mo:field> </mo:overrideItem> </mo:override> applicationContext.xml Get IDE auto-completion by updating your applicationContext-admin.xml file beans tag to include … • Update schemaLocations with http://schema.broadleafcommerce.org/mo and http://schema.broadleafcommerce.org/mo/mo-3.0.xsd • Add the namespace … xmlns:mo="http://schema.broadleafcommerce.org/mo
  • 41. 41 Admin Customizations … Annotation Overrides … Using Extended Class Annotation … Override using Extended Class Annotation … The example below makes the Customer firstName property required and adds help text using annotations on a derived class @AdminPresentationMergeOverrides( { @AdminPresentationMergeOverride(name = ”firstName", mergeEntries = { @AdminPresentationMergeEntry( propertyType=PropertyType.AdminPresentation.REQUIREDOVERRIDE, booleanOverrideValue = true) @AdminPresentationMergeEntry( propertyType=PropertyType.AdminPresentation.HELPTEXT, overrideValue = “This is help text”) } } ) public class MyCustomerImpl extends CustomerImpl { MyCustomer.java
  • 44. 44 Admin Customizations ... Admin Security Security Model • Entity-based permissions – permission to perform a CRUD operation • If the admin user has no permissions in a particular section, that section is not shown • All permissions are rolled up into the Spring Security Principal’s GrantedAuthorities
  • 45. 45 Admin Customizations ... Admin Security Role Management
  • 46. Admin Customizations ... Admin Security Invisible Modules/Sections
  • 47. 47 Admin Customizations ... Admin Security Row-level Security • Finer-grained control over security on a particular row vs an entity type as a whole • Additional fetch criteria, readonly rows, prevent deletions of rows • Javadocs for RowLevelSecurityProvider @Component public class ProductStoreRowSecurityProvider { public void addFetchRestrictions(AdminUser currentUser, String ceilingEntity, List<Predicate> restrictions, Root root, CriteriaQuery criteria, CriteriaBuilder criteriaBuilder) { Store adminStore = ((MyAdminuser) currentUser).getStore(); Predicate storeRestriction = criteriaBuilder.equal(root.get("store"), adminStore); restrictions.add(storeRestriction); }
  • 48. 48 Admin Customizations ... Admin Security Other security features • CSRF protection – Token automatically generated and checked • XSS protection – Turned off by default for CMS functionality – OWASP AntiSamy  Example Broadleaf Myspace AntiSamy configuration file <bean id="blExploitProtectionService" class="org.broadleafcommerce.common.security.service.ExploitProtectionServiceImpl "> <property name="xsrfProtectionEnabled” value="true" /> <property name="xssProtectionEnabled” value="false" /> <property name="antiSamyPolicyFileLocation” value="the_location_of_your_file" /> </bean>
  • 50. Admin Spring MVC Controller 50 Admin Customizations ... Admin persistence APIs Admin Persistence – Request Flow DynamicEntityRemoteService PersistenceManager PersistenceModuleCustomPersistenceHandler DynamicEntityDao FieldMetadataProvider FieldPersistenceProvider Transaction boundary starts here Database EntityValidatorService PersistenceEventHandler
  • 51. 51 Admin Customizations ... View Layer Spring MVC • AdminBasicEntityController – Provides facilities for all CRUD operations – Generic request mapping using path parameters  @RequestMapping("/{sectionKey:.+}") – Custom controllers can override the request mapping with a specific URL Generic Broadleaf admin controller Specific customer controller (intercepts all methods to “/customer/”)… @Controller("blAdminBasicEntityController") @RequestMapping("/{sectionKey:.+}”) public class AdminBasicEntityController extends AdminAbstractController { ... } @Controller @RequestMapping("/customer”) public class AdminCustomerController extends AdminBasicEntityController { ... }
  • 52. 52 Admin Customizations ... View Layer Admin Template Overrides • Thymeleaf template resolution (TemplateResolver) – Create custom templates in /WEB-INF/templates/admin – Add custom resolvers to the blAdminWebTemplateResolvers list bean – Example – override all strings entity fields to always load an HTML editor /WEB-INF/templates/admin/fields/string.html classpath:open_admin_style/templates/fields/string.html classpath:/common_style/templates/fields/string.html <div th:include=“fields/string.html” th:remove=“tag” /> locate fields/string.html could not find could not find
  • 53. 53 Admin Customizations ... View Layer ListGrid • Relationships (subgrids) as well as main grids • Toolbar buttons • ListGrid.Type
  • 54. 54 Admin Customizations ... View Layer HTML Fields • WYSIWYG editor by Redactor • Redactor has its own extensible plugin API • Additional extensions and/or customizations should add an initialization handler
  • 55. 55 Admin Customizations ... View Layer Example frontend customizations

Hinweis der Redaktion

  1. All of the framework jars are versioned together Your site includes the framework jars as well as 3rd-party addon modules Addon modules utilize different framework functionalities