SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Sling Models
Justin Edelson – Technical Architect, Adobe
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”
• 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?

Weitere ähnliche Inhalte

Was ist angesagt?

AEM Sightly Template Language
AEM Sightly Template LanguageAEM Sightly Template Language
AEM Sightly Template LanguageGabriel Walt
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep DiveGabriel Walt
 
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
 
Integration patterns in AEM 6
Integration patterns in AEM 6Integration patterns in AEM 6
Integration patterns in AEM 6Yuval Ararat
 
Rest and Sling Resolution
Rest and Sling ResolutionRest and Sling Resolution
Rest and Sling ResolutionDEEPAK KHETAWAT
 
Adobe Experience Manager Core Components
Adobe Experience Manager Core ComponentsAdobe Experience Manager Core Components
Adobe Experience Manager Core ComponentsGabriel Walt
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Aem asset optimizations & best practices
Aem asset optimizations & best practicesAem asset optimizations & best practices
Aem asset optimizations & best practicesKanika Gera
 
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
 
Dynamically Generate a CRUD Admin Panel with Java Annotations
Dynamically Generate a CRUD Admin Panel with Java AnnotationsDynamically Generate a CRUD Admin Panel with Java Annotations
Dynamically Generate a CRUD Admin Panel with Java AnnotationsBroadleaf Commerce
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Aem dispatcher – tips & tricks
Aem dispatcher – tips & tricksAem dispatcher – tips & tricks
Aem dispatcher – tips & tricksAshokkumar T A
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Modernizing Adobe Experience Manager (AEM)
Modernizing Adobe Experience Manager (AEM)Modernizing Adobe Experience Manager (AEM)
Modernizing Adobe Experience Manager (AEM)Gabriel Walt
 

Was ist angesagt? (20)

AEM Sightly Template Language
AEM Sightly Template LanguageAEM Sightly Template Language
AEM Sightly Template Language
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep Dive
 
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
 
Sightly - Part 2
Sightly - Part 2Sightly - Part 2
Sightly - Part 2
 
Osgi
OsgiOsgi
Osgi
 
AEM - Client Libraries
AEM - Client LibrariesAEM - Client Libraries
AEM - Client Libraries
 
Integration patterns in AEM 6
Integration patterns in AEM 6Integration patterns in AEM 6
Integration patterns in AEM 6
 
Rest and Sling Resolution
Rest and Sling ResolutionRest and Sling Resolution
Rest and Sling Resolution
 
Adobe Experience Manager Core Components
Adobe Experience Manager Core ComponentsAdobe Experience Manager Core Components
Adobe Experience Manager Core Components
 
slingmodels
slingmodelsslingmodels
slingmodels
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Aem asset optimizations & best practices
Aem asset optimizations & best practicesAem asset optimizations & best practices
Aem asset optimizations & best practices
 
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
 
Dynamically Generate a CRUD Admin Panel with Java Annotations
Dynamically Generate a CRUD Admin Panel with Java AnnotationsDynamically Generate a CRUD Admin Panel with Java Annotations
Dynamically Generate a CRUD Admin Panel with Java Annotations
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Aem dispatcher – tips & tricks
Aem dispatcher – tips & tricksAem dispatcher – tips & tricks
Aem dispatcher – tips & tricks
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Broadleaf Presents Thymeleaf
Broadleaf Presents ThymeleafBroadleaf Presents Thymeleaf
Broadleaf Presents Thymeleaf
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Modernizing Adobe Experience Manager (AEM)
Modernizing Adobe Experience Manager (AEM)Modernizing Adobe Experience Manager (AEM)
Modernizing Adobe Experience Manager (AEM)
 

Ähnlich wie 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
 
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
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptzand3rs
 

Ähnlich wie 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
 
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
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 

Kürzlich hochgeladen (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 

Sling models by Justin Edelson

  • 1. Sling Models Justin Edelson – Technical Architect, Adobe
  • 2.
  • 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”
  • 20.
  • 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