SlideShare a Scribd company logo
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

More Related Content

PDF
Broadleaf Presents Thymeleaf
PDF
PoP - “Platform of Platforms”: Framework for building Single-Page Application...
PPT
MVC ppt presentation
PDF
JPA and Hibernate
PPT
JDBC Java Database Connectivity
PDF
Spring Framework - MVC
PDF
Hands-On Java web passando por Servlets, JSP, JSTL, JDBC, Hibernate, DAO, MV...
PPTX
ASP.NET MVC.
 
Broadleaf Presents Thymeleaf
PoP - “Platform of Platforms”: Framework for building Single-Page Application...
MVC ppt presentation
JPA and Hibernate
JDBC Java Database Connectivity
Spring Framework - MVC
Hands-On Java web passando por Servlets, JSP, JSTL, JDBC, Hibernate, DAO, MV...
ASP.NET MVC.
 

What's hot (20)

DOCX
How to launch workflow from plsql
PDF
Support de cours entrepise java beans ejb m.youssfi
PDF
Web Services PHP Tutorial
PDF
Ibm web sphere_job_interview_preparation_guide
PPTX
Introduction à spring boot
PDF
Curso de Enterprise JavaBeans (EJB) (JavaEE 7)
PDF
PHP and Web Services
PPT
ASP.NET MVC Presentation
PPTX
Mongoose and MongoDB 101
PPTX
Model view controller (mvc)
PDF
Hibernate Presentation
PDF
3. Java Script
PPT
jpa-hibernate-presentation
PPT
Introduction To PHP
PDF
JAX-RS 2.0: RESTful Web Services
PDF
Solid NodeJS with TypeScript, Jest & NestJS
PDF
Architecture java j2 ee a partager
PDF
Php Tutorials for Beginners
PPTX
Chp4 - Composition, Orchestration et Choregraphie de services
PDF
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
How to launch workflow from plsql
Support de cours entrepise java beans ejb m.youssfi
Web Services PHP Tutorial
Ibm web sphere_job_interview_preparation_guide
Introduction à spring boot
Curso de Enterprise JavaBeans (EJB) (JavaEE 7)
PHP and Web Services
ASP.NET MVC Presentation
Mongoose and MongoDB 101
Model view controller (mvc)
Hibernate Presentation
3. Java Script
jpa-hibernate-presentation
Introduction To PHP
JAX-RS 2.0: RESTful Web Services
Solid NodeJS with TypeScript, Jest & NestJS
Architecture java j2 ee a partager
Php Tutorials for Beginners
Chp4 - Composition, Orchestration et Choregraphie de services
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
Ad

Viewers also liked (8)

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

Similar to Dynamically Generate a CRUD Admin Panel with Java Annotations (20)

PPTX
Tge how-to-add-quotes-and-offers-to-jira-issues
DOCX
© 2014 Laureate Education, Inc. Page 1 of 4 Retail Trans.docx
PDF
Hidden rocks in Oracle ADF
PDF
How to customize views & menues of OpenERP online in a sustainable way. Frede...
PDF
Howtocustomizeviewsmenuesofopenerponlineinasustainablewayfredericgilson 13070...
DOCX
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
PDF
PPT. Introduction & Views - Documentation.pdf
PPTX
How to add Many2Many fields in odoo website form.pptx
DOCX
please code in c#- please note that im a complete beginner- northwind.docx
PDF
13088674 oracle-adf-11g-learning-application-my-procurement-application
PDF
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
DOCX
R13_QP_Customer_Account_Specific_Pricing_Solution_V2 .docx
PPT
OfficeCentral CRM
PDF
Magento Attributes - Fresh View
PPTX
How to Bring Common UI Patterns to ADF
PPTX
HIBERNATE For Databases java presentation.pptx
PPTX
Crm 4.0 customizations basics
PDF
Working With The Symfony Admin Generator
PDF
Django admin
PPTX
Create Custom Entity in CRM to Track Expenses! Okay, well maybe two custom en...
Tge how-to-add-quotes-and-offers-to-jira-issues
© 2014 Laureate Education, Inc. Page 1 of 4 Retail Trans.docx
Hidden rocks in Oracle ADF
How to customize views & menues of OpenERP online in a sustainable way. Frede...
Howtocustomizeviewsmenuesofopenerponlineinasustainablewayfredericgilson 13070...
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
PPT. Introduction & Views - Documentation.pdf
How to add Many2Many fields in odoo website form.pptx
please code in c#- please note that im a complete beginner- northwind.docx
13088674 oracle-adf-11g-learning-application-my-procurement-application
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
R13_QP_Customer_Account_Specific_Pricing_Solution_V2 .docx
OfficeCentral CRM
Magento Attributes - Fresh View
How to Bring Common UI Patterns to ADF
HIBERNATE For Databases java presentation.pptx
Crm 4.0 customizations basics
Working With The Symfony Admin Generator
Django admin
Create Custom Entity in CRM to Track Expenses! Okay, well maybe two custom en...

Recently uploaded (20)

PPTX
Mastering-Cybersecurity-The-Crucial-Role-of-Antivirus-Support-Services.pptx
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
PDF
Become an Agentblazer Champion Challenge Kickoff
PPTX
Introduction to Artificial Intelligence
PPTX
Transform Your Business with a Software ERP System
PDF
Best Practices for Rolling Out Competency Management Software.pdf
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
A REACT POMODORO TIMER WEB APPLICATION.pdf
PPTX
ai tools demonstartion for schools and inter college
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
medical staffing services at VALiNTRY
PDF
Understanding Forklifts - TECH EHS Solution
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
FLIGHT TICKET RESERVATION SYSTEM | FLIGHT BOOKING ENGINE API
PPTX
L1 - Introduction to python Backend.pptx
PDF
System and Network Administraation Chapter 3
Mastering-Cybersecurity-The-Crucial-Role-of-Antivirus-Support-Services.pptx
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
The Role of Automation and AI in EHS Management for Data Centers.pdf
Become an Agentblazer Champion Challenge Kickoff
Introduction to Artificial Intelligence
Transform Your Business with a Software ERP System
Best Practices for Rolling Out Competency Management Software.pdf
How Creative Agencies Leverage Project Management Software.pdf
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
2025 Textile ERP Trends: SAP, Odoo & Oracle
A REACT POMODORO TIMER WEB APPLICATION.pdf
ai tools demonstartion for schools and inter college
Upgrade and Innovation Strategies for SAP ERP Customers
medical staffing services at VALiNTRY
Understanding Forklifts - TECH EHS Solution
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
FLIGHT TICKET RESERVATION SYSTEM | FLIGHT BOOKING ENGINE API
L1 - Introduction to python Backend.pptx
System and Network Administraation Chapter 3

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

Editor's Notes

  • #51: 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