SlideShare a Scribd company logo
1 of 34
Download to read offline
Sling Models
Justin Edelson – Technical Architect, Adobe
Sling models by Justin Edelson
Let’s say you want to adapt a Resource into some domain object…
public class OldModel {
private String title;
private String description;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
@Component
@Service
@Properties({
@Property(name=AdapterFactory.ADAPTABLE_CLASSES, value="org.apache.sling.api.Resource"),
@Property(name=AdapterFactory.ADAPTER_CLASSES,
value="com.adobe.people.jedelson.slingmodels.demo.OldModel")
})
public class OldModelAdapterFactory implements AdapterFactory {
@SuppressWarnings("unchecked")
public <AdapterType> AdapterType getAdapter(Object adaptable, Class<AdapterType> type) {
if (adaptable instanceof Resource && type.equals(OldModel.class)) {
OldModel model = new OldModel();
ValueMap map = ResourceUtil.getValueMap((Resource) adaptable);
model.setTitle(map.get(”title", String.class));
model.setDescription(map.get(”description", String.class));
return (AdapterType) model;
} else {
return null;
}
}
}
OldModel myModel = resource.adaptTo(OldModel.class)
<sling:adaptTo adaptable="${resource}" adaptTo=”…
OldModel" var=”myModel" />
<div data-sly-use.myModel =“…OldModel”></div>
@Model(adaptables = Resource.class)
public class NewModel {
@Inject
private String title;
@Inject
private String description;
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
}
NewModel myModel = resource.adaptTo(NewModel.class)
<sling:adaptTo adaptable="${resource}" adaptTo=”…
NewModel" var=”myModel" />
<div data-sly-use.myModel=“…NewModel”></div>
• The “old” way: 30+ LOC
• The “new” way: 13 LOC
– Plus one extra bundle header:
<Sling-Model-Packages>com.adobe.people.jedelson.slingmodels.demo</Sling-Model-Packages>
@Model(adaptables = Resource.class)
public interface NewModel2 {
@Inject
public String getTitle();
@Inject
public String getDescription();
}
• Entirely annotation driven. "Pure" POJOs.
• Use standard annotations where possible.
• Pluggable
• OOTB, support resource properties (via ValueMap), SlingBindings, OSGi services, request
attributes
• Adapt multiple objects - minimal required Resource and SlingHttpServletRequest
• Client doesn't know/care that these objects are different than any other adapter factory
• Support both classes and interfaces.
• Work with existing Sling infrastructure (i.e. not require changes to other bundles).
• December 2013 – YAMF prototype
announced on sling-dev
• January 2014 – API formalized and renamed
to Sling Models
• Feburary 2014 – 1.0.0 release; Included in
AEM 6.0 Beta
• March 2014 – 1.0.2 release; Included in AEM
6.0 Release
• Standard Injectors
– SlingBindings objects
– ValueMap properties
– Child Resources
– Request Attributes
– OSGi Services
• @org.apache.sling.models.annotations.Model
• @javax.inject.Inject
• @javax.inject.Named
• @org.apache.sling.models.annotations.Optional
• @org.apache.sling.models.annotations.Source
• @org.apache.sling.models.annotations.Filter
• @javax.inject.PostConstruct
• @org.apache.sling.models.annotations.Via
• @org.apache.sling.models.annotations.Default
• @Model(adaptables = Resource.class)
• @Model(adaptables = SlingHttpServletRequest.class)
• @Model(adaptables = { Resource.class, ValueMap.class })
• @Inject private String title;
– valueMap.get(“title”, String.class);
• @Inject public String getTitle();
– valueMap.get(“title”, String.class);
• @Inject private String[] columnNames;
– valueMap.get(“columnNames”, String[].class);
• @Inject private List<Filter> filters;
– bundleContext.getServiceReferences(“javax.servlet.Filter”)
• By default, the name of the field or method is
used to perform the injection.
• @Inject @Named(“jcr:title”) private String
title;
– valueMap.get(“jcr:title”, String.class);
• By default, all @Inject points are required.
• resource.adaptTo(Model.class) <- returns null
• @Inject @Optional private String title;
• request.getAttribute(“text”) <- returns “goodbye”
• slingBindings.get(“text”) <- returns “hello”
• @Inject
private String text; <- “hello” (SlingBindings is checked first)
• @Inject @Source(“request-attributes”)
private String text; <- “goodbye”
Sling models by Justin Edelson
• Specifically for OSGi services:
• @Inject @Filter("(sling.servlet.extensions=json)") private
List<Servlet> servlets;
• Implicitly applies @Source(“osgi-services”)
• @Inject private String text;
• @PostConstruct
protected void doSomething() { log.info("text = {}", text); };
• Superclass @PostConstruct methods called first.
@Model(adaptables = SlingHttpServletRequest.class)
public class ViaModel {
@Inject @Via("resource")
private String firstProperty;
public String getFirstProperty() {
return firstProperty;
}
}
• @Inject @Default(values=“default text”)
private String text;
• Also
– booleanValues
– doubleValues
– floatValues
– intValues
– longValues
– shortValues
If you need the adaptable itself:
@Model(adaptables = SlingHttpServletRequest.class)
public class ConstructorModel {
private final SlingHttpServletRequest request;
public ConstructorModel(SlingHttpServletRequest r) {
this.request = r;
}
public SlingHttpServletRequest getRequest() {
return request;
}
}
@Model(adaptables = Resource.class)
public interface ChildValueMapModel {
@Inject
public ValueMap getFirstChild();
}
resource.getChild(“firstChild”).adaptTo(ValueMap.class)
@Model(adaptables = Resource.class)
public interface ParentModel {
@Inject
public ChildModel getFirstChild();
}
Works even if resource.adaptTo(ChildModel.class) isn’t done
by Sling Models
• Injectors are OSGi services implementing the
org.apache.sling.models.spi.Injector interface
• Object getValue(Object adaptable, String name, Type
type, AnnotatedElement element, DisposalCallbackRegistry
callbackRegistry)
• adaptable – the object being adapted
• name – the name (either using @Named or the default
name)
• element – the method or field
• callbackRegistry – Injector gets notified when the adapted
model is garbage collected
public Object getValue(Object adaptable, String name,
Type type, AnnotatedElement element, DisposalCallbackRegistry callbackRegistry) {
Resource resource = getResource(adaptable);
if (resource == null) {
return null;
} else if (type instanceof Class<?>) {
InheritanceValueMap map = new
HierarchyNodeInheritanceValueMap(resource);
return map.getInherited(name, (Class<?>) type);
} else {
return null;
}
}
• Some injectors need extra data
– Example: OSGi service filters
@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
@Source("resource-path")
public @interface ResourcePath {
String value();
}
public Object getValue(Object adaptable, String name,
Type declaredType, AnnotatedElement element,
DisposalCallbackRegistry callbackRegistry) {
ResourcePath path =
element.getAnnotation(ResourcePath.class);
if (path == null) {
return null;
}
ResourceResolver resolver = getResourceResolver(adaptable);
if (resolver == null) {
return null;
}
return resolver.getResource(path.value());
}
@Model(adaptables = Resource.class)
public interface ResourcePathModel {
@Inject @ResourcePath("/content/dam")
Resource getResource();
}
• More Standard Injectors
• AEM-specific injectors in ACS AEM Commons
• Pluggable @Via support
Questions?

More Related Content

What's hot

JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?connectwebex
 
HTL(Sightly) - All you need to know
HTL(Sightly) - All you need to knowHTL(Sightly) - All you need to know
HTL(Sightly) - All you need to knowPrabhdeep Singh
 
Introduction to Sightly
Introduction to SightlyIntroduction to Sightly
Introduction to SightlyAnkit Gubrani
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 
Sling Models Using Sightly and JSP by Deepak Khetawat
Sling Models Using Sightly and JSP by Deepak KhetawatSling Models Using Sightly and JSP by Deepak Khetawat
Sling Models Using Sightly and JSP by Deepak KhetawatAEM HUB
 
AEM Rich Text Editor (RTE) Deep Dive
AEM Rich Text Editor (RTE) Deep DiveAEM Rich Text Editor (RTE) Deep Dive
AEM Rich Text Editor (RTE) Deep DiveHanish Bansal
 
Adobe AEM - From Eventing to Job Processing
Adobe AEM - From Eventing to Job ProcessingAdobe AEM - From Eventing to Job Processing
Adobe AEM - From Eventing to Job ProcessingCarsten Ziegeler
 
Mastering the Sling Rewriter
Mastering the Sling RewriterMastering the Sling Rewriter
Mastering the Sling RewriterJustin Edelson
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 formsEyal Vardi
 
Omnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the ThingsOmnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the ThingsJustin Edelson
 
Angular Interview Questions & Answers
Angular Interview Questions & AnswersAngular Interview Questions & Answers
Angular Interview Questions & AnswersRatnala Charan kumar
 
Apache Sling Generic Validation Framework
Apache Sling Generic Validation FrameworkApache Sling Generic Validation Framework
Apache Sling Generic Validation FrameworkRadu Cotescu
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 

What's hot (20)

JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?
 
HTL(Sightly) - All you need to know
HTL(Sightly) - All you need to knowHTL(Sightly) - All you need to know
HTL(Sightly) - All you need to know
 
Introduction to Sightly
Introduction to SightlyIntroduction to Sightly
Introduction to Sightly
 
AEM - Client Libraries
AEM - Client LibrariesAEM - Client Libraries
AEM - Client Libraries
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Sling Models Using Sightly and JSP by Deepak Khetawat
Sling Models Using Sightly and JSP by Deepak KhetawatSling Models Using Sightly and JSP by Deepak Khetawat
Sling Models Using Sightly and JSP by Deepak Khetawat
 
Sightly - Part 2
Sightly - Part 2Sightly - Part 2
Sightly - Part 2
 
AEM Rich Text Editor (RTE) Deep Dive
AEM Rich Text Editor (RTE) Deep DiveAEM Rich Text Editor (RTE) Deep Dive
AEM Rich Text Editor (RTE) Deep Dive
 
Adobe AEM - From Eventing to Job Processing
Adobe AEM - From Eventing to Job ProcessingAdobe AEM - From Eventing to Job Processing
Adobe AEM - From Eventing to Job Processing
 
Mastering the Sling Rewriter
Mastering the Sling RewriterMastering the Sling Rewriter
Mastering the Sling Rewriter
 
Osgi
OsgiOsgi
Osgi
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Omnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the ThingsOmnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the Things
 
Angular Interview Questions & Answers
Angular Interview Questions & AnswersAngular Interview Questions & Answers
Angular Interview Questions & Answers
 
React js
React jsReact js
React js
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
Apache Sling Generic Validation Framework
Apache Sling Generic Validation FrameworkApache Sling Generic Validation Framework
Apache Sling Generic Validation Framework
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
 
An Intro into webpack
An Intro into webpackAn Intro into webpack
An Intro into webpack
 

Similar to Sling models by Justin Edelson

Deepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jspDeepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jspDEEPAK KHETAWAT
 
Integration patterns in AEM 6
Integration patterns in AEM 6Integration patterns in AEM 6
Integration patterns in AEM 6Yuval Ararat
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto UniversitySC5.io
 
Framework prototype
Framework prototypeFramework prototype
Framework prototypeDevMix
 
Framework prototype
Framework prototypeFramework prototype
Framework prototypeDevMix
 
Framework prototype
Framework prototypeFramework prototype
Framework prototypeDevMix
 
Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags AdvancedAkramWaseem
 
13 java beans
13 java beans13 java beans
13 java beanssnopteck
 
java beans
java beansjava beans
java beanslapa
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxtutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized projectFabio Collini
 
Application Frameworks: The new kids on the block
Application Frameworks: The new kids on the blockApplication Frameworks: The new kids on the block
Application Frameworks: The new kids on the blockRichard Lord
 
Core Data Migrations and A Better Option
Core Data Migrations and A Better OptionCore Data Migrations and A Better Option
Core Data Migrations and A Better OptionPriya Rajagopal
 

Similar to Sling models by Justin Edelson (20)

Deepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jspDeepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jsp
 
Integration patterns in AEM 6
Integration patterns in AEM 6Integration patterns in AEM 6
Integration patterns in AEM 6
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto University
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
 
Jersey
JerseyJersey
Jersey
 
Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags Advanced
 
13 java beans
13 java beans13 java beans
13 java beans
 
Prototype-1
Prototype-1Prototype-1
Prototype-1
 
Prototype-1
Prototype-1Prototype-1
Prototype-1
 
java beans
java beansjava beans
java beans
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized project
 
Application Frameworks: The new kids on the block
Application Frameworks: The new kids on the blockApplication Frameworks: The new kids on the block
Application Frameworks: The new kids on the block
 
Core Data Migrations and A Better Option
Core Data Migrations and A Better OptionCore Data Migrations and A Better Option
Core Data Migrations and A Better Option
 

More from AEM HUB

Microservices for AEM by Maciej Majchrzak
Microservices for AEM by Maciej MajchrzakMicroservices for AEM by Maciej Majchrzak
Microservices for AEM by Maciej MajchrzakAEM HUB
 
When dispatcher caching is not enough by Jakub Wądołowski
When dispatcher caching is not enough by Jakub WądołowskiWhen dispatcher caching is not enough by Jakub Wądołowski
When dispatcher caching is not enough by Jakub WądołowskiAEM HUB
 
PhoneGap Enterprise Viewer by Anthony Rumsey
PhoneGap Enterprise Viewer by Anthony RumseyPhoneGap Enterprise Viewer by Anthony Rumsey
PhoneGap Enterprise Viewer by Anthony RumseyAEM HUB
 
Integrating Apache Wookie with AEM by Rima Mittal and Ankit Gubrani
Integrating Apache Wookie with AEM by Rima Mittal and Ankit GubraniIntegrating Apache Wookie with AEM by Rima Mittal and Ankit Gubrani
Integrating Apache Wookie with AEM by Rima Mittal and Ankit GubraniAEM HUB
 
Mastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin EdelsonMastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin EdelsonAEM HUB
 
Building Quality into the AEM Publication Workflow with Active Standards by D...
Building Quality into the AEM Publication Workflow with Active Standards by D...Building Quality into the AEM Publication Workflow with Active Standards by D...
Building Quality into the AEM Publication Workflow with Active Standards by D...AEM HUB
 
Touching the AEM component dialog by Mateusz Chromiński
Touching the AEM component dialog by Mateusz ChromińskiTouching the AEM component dialog by Mateusz Chromiński
Touching the AEM component dialog by Mateusz ChromińskiAEM HUB
 
How to build a Social Intranet with Adobe Sites and 3rd Party products ... us...
How to build a Social Intranet with Adobe Sites and 3rd Party products ... us...How to build a Social Intranet with Adobe Sites and 3rd Party products ... us...
How to build a Social Intranet with Adobe Sites and 3rd Party products ... us...AEM HUB
 
How do you build flexible platforms that focuses on business needs? by Fahim...
How do you build flexible platforms that focuses on business needs?  by Fahim...How do you build flexible platforms that focuses on business needs?  by Fahim...
How do you build flexible platforms that focuses on business needs? by Fahim...AEM HUB
 
AEM Apps Enhanced: In-app Messaging and Beacons by John Fait
AEM Apps Enhanced: In-app Messaging and Beacons by John FaitAEM Apps Enhanced: In-app Messaging and Beacons by John Fait
AEM Apps Enhanced: In-app Messaging and Beacons by John FaitAEM HUB
 
Effectively Scale and Operate AEM with MongoDB by Norberto Leite
Effectively Scale and Operate AEM with MongoDB by Norberto LeiteEffectively Scale and Operate AEM with MongoDB by Norberto Leite
Effectively Scale and Operate AEM with MongoDB by Norberto LeiteAEM HUB
 
Adobe Managed Services: Complicated Cloud Deployments by Adam Pazik, Mike Til...
Adobe Managed Services: Complicated Cloud Deployments by Adam Pazik, Mike Til...Adobe Managed Services: Complicated Cloud Deployments by Adam Pazik, Mike Til...
Adobe Managed Services: Complicated Cloud Deployments by Adam Pazik, Mike Til...AEM HUB
 
Adobe Marketing Cloud Integrations: Myth or Reality? by Holger Marsen
Adobe Marketing Cloud Integrations: Myth or Reality? by Holger MarsenAdobe Marketing Cloud Integrations: Myth or Reality? by Holger Marsen
Adobe Marketing Cloud Integrations: Myth or Reality? by Holger MarsenAEM HUB
 
Responsive Websites and Grid-Based Layouts by Gabriel Walt
Responsive Websites and Grid-Based Layouts by Gabriel Walt Responsive Websites and Grid-Based Layouts by Gabriel Walt
Responsive Websites and Grid-Based Layouts by Gabriel Walt AEM HUB
 
When Sightly Meets Slice by Tomasz Niedźwiedź
When Sightly Meets Slice by Tomasz NiedźwiedźWhen Sightly Meets Slice by Tomasz Niedźwiedź
When Sightly Meets Slice by Tomasz NiedźwiedźAEM HUB
 
Creativity without comprise by Cleve Gibbon
Creativity without comprise by Cleve Gibbon Creativity without comprise by Cleve Gibbon
Creativity without comprise by Cleve Gibbon AEM HUB
 
REST in AEM by Roy Fielding
REST in AEM by Roy FieldingREST in AEM by Roy Fielding
REST in AEM by Roy FieldingAEM HUB
 
Adobe Summit 2015 - Penguin Random House - Accelerating Digital Transformation
Adobe Summit 2015 - Penguin Random House - Accelerating Digital TransformationAdobe Summit 2015 - Penguin Random House - Accelerating Digital Transformation
Adobe Summit 2015 - Penguin Random House - Accelerating Digital TransformationAEM HUB
 
Socialize your Exceptional Web Experience – Adobe AEM & IBM Connections by He...
Socialize your Exceptional Web Experience – Adobe AEM & IBM Connections by He...Socialize your Exceptional Web Experience – Adobe AEM & IBM Connections by He...
Socialize your Exceptional Web Experience – Adobe AEM & IBM Connections by He...AEM HUB
 
Sightly Beautiful Markup by Senol Tas
Sightly Beautiful Markup by Senol Tas Sightly Beautiful Markup by Senol Tas
Sightly Beautiful Markup by Senol Tas AEM HUB
 

More from AEM HUB (20)

Microservices for AEM by Maciej Majchrzak
Microservices for AEM by Maciej MajchrzakMicroservices for AEM by Maciej Majchrzak
Microservices for AEM by Maciej Majchrzak
 
When dispatcher caching is not enough by Jakub Wądołowski
When dispatcher caching is not enough by Jakub WądołowskiWhen dispatcher caching is not enough by Jakub Wądołowski
When dispatcher caching is not enough by Jakub Wądołowski
 
PhoneGap Enterprise Viewer by Anthony Rumsey
PhoneGap Enterprise Viewer by Anthony RumseyPhoneGap Enterprise Viewer by Anthony Rumsey
PhoneGap Enterprise Viewer by Anthony Rumsey
 
Integrating Apache Wookie with AEM by Rima Mittal and Ankit Gubrani
Integrating Apache Wookie with AEM by Rima Mittal and Ankit GubraniIntegrating Apache Wookie with AEM by Rima Mittal and Ankit Gubrani
Integrating Apache Wookie with AEM by Rima Mittal and Ankit Gubrani
 
Mastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin EdelsonMastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin Edelson
 
Building Quality into the AEM Publication Workflow with Active Standards by D...
Building Quality into the AEM Publication Workflow with Active Standards by D...Building Quality into the AEM Publication Workflow with Active Standards by D...
Building Quality into the AEM Publication Workflow with Active Standards by D...
 
Touching the AEM component dialog by Mateusz Chromiński
Touching the AEM component dialog by Mateusz ChromińskiTouching the AEM component dialog by Mateusz Chromiński
Touching the AEM component dialog by Mateusz Chromiński
 
How to build a Social Intranet with Adobe Sites and 3rd Party products ... us...
How to build a Social Intranet with Adobe Sites and 3rd Party products ... us...How to build a Social Intranet with Adobe Sites and 3rd Party products ... us...
How to build a Social Intranet with Adobe Sites and 3rd Party products ... us...
 
How do you build flexible platforms that focuses on business needs? by Fahim...
How do you build flexible platforms that focuses on business needs?  by Fahim...How do you build flexible platforms that focuses on business needs?  by Fahim...
How do you build flexible platforms that focuses on business needs? by Fahim...
 
AEM Apps Enhanced: In-app Messaging and Beacons by John Fait
AEM Apps Enhanced: In-app Messaging and Beacons by John FaitAEM Apps Enhanced: In-app Messaging and Beacons by John Fait
AEM Apps Enhanced: In-app Messaging and Beacons by John Fait
 
Effectively Scale and Operate AEM with MongoDB by Norberto Leite
Effectively Scale and Operate AEM with MongoDB by Norberto LeiteEffectively Scale and Operate AEM with MongoDB by Norberto Leite
Effectively Scale and Operate AEM with MongoDB by Norberto Leite
 
Adobe Managed Services: Complicated Cloud Deployments by Adam Pazik, Mike Til...
Adobe Managed Services: Complicated Cloud Deployments by Adam Pazik, Mike Til...Adobe Managed Services: Complicated Cloud Deployments by Adam Pazik, Mike Til...
Adobe Managed Services: Complicated Cloud Deployments by Adam Pazik, Mike Til...
 
Adobe Marketing Cloud Integrations: Myth or Reality? by Holger Marsen
Adobe Marketing Cloud Integrations: Myth or Reality? by Holger MarsenAdobe Marketing Cloud Integrations: Myth or Reality? by Holger Marsen
Adobe Marketing Cloud Integrations: Myth or Reality? by Holger Marsen
 
Responsive Websites and Grid-Based Layouts by Gabriel Walt
Responsive Websites and Grid-Based Layouts by Gabriel Walt Responsive Websites and Grid-Based Layouts by Gabriel Walt
Responsive Websites and Grid-Based Layouts by Gabriel Walt
 
When Sightly Meets Slice by Tomasz Niedźwiedź
When Sightly Meets Slice by Tomasz NiedźwiedźWhen Sightly Meets Slice by Tomasz Niedźwiedź
When Sightly Meets Slice by Tomasz Niedźwiedź
 
Creativity without comprise by Cleve Gibbon
Creativity without comprise by Cleve Gibbon Creativity without comprise by Cleve Gibbon
Creativity without comprise by Cleve Gibbon
 
REST in AEM by Roy Fielding
REST in AEM by Roy FieldingREST in AEM by Roy Fielding
REST in AEM by Roy Fielding
 
Adobe Summit 2015 - Penguin Random House - Accelerating Digital Transformation
Adobe Summit 2015 - Penguin Random House - Accelerating Digital TransformationAdobe Summit 2015 - Penguin Random House - Accelerating Digital Transformation
Adobe Summit 2015 - Penguin Random House - Accelerating Digital Transformation
 
Socialize your Exceptional Web Experience – Adobe AEM & IBM Connections by He...
Socialize your Exceptional Web Experience – Adobe AEM & IBM Connections by He...Socialize your Exceptional Web Experience – Adobe AEM & IBM Connections by He...
Socialize your Exceptional Web Experience – Adobe AEM & IBM Connections by He...
 
Sightly Beautiful Markup by Senol Tas
Sightly Beautiful Markup by Senol Tas Sightly Beautiful Markup by Senol Tas
Sightly Beautiful Markup by Senol Tas
 

Recently uploaded

Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfJamie (Taka) Wang
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsSafe Software
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 

Recently uploaded (20)

Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 

Sling models by Justin Edelson

  • 1. Sling Models Justin Edelson – Technical Architect, Adobe
  • 3. Let’s say you want to adapt a Resource into some domain object…
  • 4. public class OldModel { private String title; private String description; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
  • 5. @Component @Service @Properties({ @Property(name=AdapterFactory.ADAPTABLE_CLASSES, value="org.apache.sling.api.Resource"), @Property(name=AdapterFactory.ADAPTER_CLASSES, value="com.adobe.people.jedelson.slingmodels.demo.OldModel") }) public class OldModelAdapterFactory implements AdapterFactory { @SuppressWarnings("unchecked") public <AdapterType> AdapterType getAdapter(Object adaptable, Class<AdapterType> type) { if (adaptable instanceof Resource && type.equals(OldModel.class)) { OldModel model = new OldModel(); ValueMap map = ResourceUtil.getValueMap((Resource) adaptable); model.setTitle(map.get(”title", String.class)); model.setDescription(map.get(”description", String.class)); return (AdapterType) model; } else { return null; } } }
  • 6. OldModel myModel = resource.adaptTo(OldModel.class) <sling:adaptTo adaptable="${resource}" adaptTo=”… OldModel" var=”myModel" /> <div data-sly-use.myModel =“…OldModel”></div>
  • 7. @Model(adaptables = Resource.class) public class NewModel { @Inject private String title; @Inject private String description; public String getTitle() { return title; } public String getDescription() { return description; } }
  • 8. NewModel myModel = resource.adaptTo(NewModel.class) <sling:adaptTo adaptable="${resource}" adaptTo=”… NewModel" var=”myModel" /> <div data-sly-use.myModel=“…NewModel”></div>
  • 9. • The “old” way: 30+ LOC • The “new” way: 13 LOC – Plus one extra bundle header: <Sling-Model-Packages>com.adobe.people.jedelson.slingmodels.demo</Sling-Model-Packages>
  • 10. @Model(adaptables = Resource.class) public interface NewModel2 { @Inject public String getTitle(); @Inject public String getDescription(); }
  • 11. • Entirely annotation driven. "Pure" POJOs. • Use standard annotations where possible. • Pluggable • OOTB, support resource properties (via ValueMap), SlingBindings, OSGi services, request attributes • Adapt multiple objects - minimal required Resource and SlingHttpServletRequest • Client doesn't know/care that these objects are different than any other adapter factory • Support both classes and interfaces. • Work with existing Sling infrastructure (i.e. not require changes to other bundles).
  • 12. • December 2013 – YAMF prototype announced on sling-dev • January 2014 – API formalized and renamed to Sling Models • Feburary 2014 – 1.0.0 release; Included in AEM 6.0 Beta • March 2014 – 1.0.2 release; Included in AEM 6.0 Release
  • 13. • Standard Injectors – SlingBindings objects – ValueMap properties – Child Resources – Request Attributes – OSGi Services
  • 14. • @org.apache.sling.models.annotations.Model • @javax.inject.Inject • @javax.inject.Named • @org.apache.sling.models.annotations.Optional • @org.apache.sling.models.annotations.Source • @org.apache.sling.models.annotations.Filter • @javax.inject.PostConstruct • @org.apache.sling.models.annotations.Via • @org.apache.sling.models.annotations.Default
  • 15. • @Model(adaptables = Resource.class) • @Model(adaptables = SlingHttpServletRequest.class) • @Model(adaptables = { Resource.class, ValueMap.class })
  • 16. • @Inject private String title; – valueMap.get(“title”, String.class); • @Inject public String getTitle(); – valueMap.get(“title”, String.class); • @Inject private String[] columnNames; – valueMap.get(“columnNames”, String[].class); • @Inject private List<Filter> filters; – bundleContext.getServiceReferences(“javax.servlet.Filter”)
  • 17. • By default, the name of the field or method is used to perform the injection. • @Inject @Named(“jcr:title”) private String title; – valueMap.get(“jcr:title”, String.class);
  • 18. • By default, all @Inject points are required. • resource.adaptTo(Model.class) <- returns null • @Inject @Optional private String title;
  • 19. • request.getAttribute(“text”) <- returns “goodbye” • slingBindings.get(“text”) <- returns “hello” • @Inject private String text; <- “hello” (SlingBindings is checked first) • @Inject @Source(“request-attributes”) private String text; <- “goodbye”
  • 21. • Specifically for OSGi services: • @Inject @Filter("(sling.servlet.extensions=json)") private List<Servlet> servlets; • Implicitly applies @Source(“osgi-services”)
  • 22. • @Inject private String text; • @PostConstruct protected void doSomething() { log.info("text = {}", text); }; • Superclass @PostConstruct methods called first.
  • 23. @Model(adaptables = SlingHttpServletRequest.class) public class ViaModel { @Inject @Via("resource") private String firstProperty; public String getFirstProperty() { return firstProperty; } }
  • 24. • @Inject @Default(values=“default text”) private String text; • Also – booleanValues – doubleValues – floatValues – intValues – longValues – shortValues
  • 25. If you need the adaptable itself: @Model(adaptables = SlingHttpServletRequest.class) public class ConstructorModel { private final SlingHttpServletRequest request; public ConstructorModel(SlingHttpServletRequest r) { this.request = r; } public SlingHttpServletRequest getRequest() { return request; } }
  • 26. @Model(adaptables = Resource.class) public interface ChildValueMapModel { @Inject public ValueMap getFirstChild(); } resource.getChild(“firstChild”).adaptTo(ValueMap.class)
  • 27. @Model(adaptables = Resource.class) public interface ParentModel { @Inject public ChildModel getFirstChild(); } Works even if resource.adaptTo(ChildModel.class) isn’t done by Sling Models
  • 28. • Injectors are OSGi services implementing the org.apache.sling.models.spi.Injector interface • Object getValue(Object adaptable, String name, Type type, AnnotatedElement element, DisposalCallbackRegistry callbackRegistry) • adaptable – the object being adapted • name – the name (either using @Named or the default name) • element – the method or field • callbackRegistry – Injector gets notified when the adapted model is garbage collected
  • 29. public Object getValue(Object adaptable, String name, Type type, AnnotatedElement element, DisposalCallbackRegistry callbackRegistry) { Resource resource = getResource(adaptable); if (resource == null) { return null; } else if (type instanceof Class<?>) { InheritanceValueMap map = new HierarchyNodeInheritanceValueMap(resource); return map.getInherited(name, (Class<?>) type); } else { return null; } }
  • 30. • Some injectors need extra data – Example: OSGi service filters @Target({ ElementType.FIELD, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Qualifier @Source("resource-path") public @interface ResourcePath { String value(); }
  • 31. public Object getValue(Object adaptable, String name, Type declaredType, AnnotatedElement element, DisposalCallbackRegistry callbackRegistry) { ResourcePath path = element.getAnnotation(ResourcePath.class); if (path == null) { return null; } ResourceResolver resolver = getResourceResolver(adaptable); if (resolver == null) { return null; } return resolver.getResource(path.value()); }
  • 32. @Model(adaptables = Resource.class) public interface ResourcePathModel { @Inject @ResourcePath("/content/dam") Resource getResource(); }
  • 33. • More Standard Injectors • AEM-specific injectors in ACS AEM Commons • Pluggable @Via support