Sling Models Using Sightly
and JSP
DEEPAK KHETAWAT
About the Speaker
What & Why Sling Models
- What are Sling Models
- Design Goals
- Why Sling Models ?
Sling Model Annotations
- Annotations Usage
Sling Model Injectors
- What are Injectors
- Injectors available in 1.0.x and 1.1.x
- Injector-specific Annotations
Agenda
Usage of Sling Models
- Prerequisite
- How to use Sling Models with JSP ?
- How to use Sling Models with Sightly?
Demo
- Functionality Demo
Appendix and Q&A
- Appendix
- Q&A
What & Why Sling Models
• Sling Models are POJO’s which are automatically
mapped from Sling objects, typically resources, request
objects. Sometimes these POJOs need OSGi services
as well
What are Sling Models?
• Entirely annotation driven. "Pure" POJOs
• Adapt multiple objects
• Work with existing Sling infrastructure
• Client doesn't know/care that these objects are different than any
other adapter factory
• Support both classes and interfaces
• Pluggable
Design Goals
Development :
• Saves from creating own adapters
• Situation Based Dependency Injection Framework
• Do More with less code making code readable and Removing
redundant (boilerplate) code
Testing :
• Highly Testable Code
- Sling Model Inject Annotations defines binding to
dependencies
- Mock dependencies with tools like Mockito using
@InjectMocks
Why Sling Models ?
Sling Model Annotations
Annotations Usage
Sling Model Annotation Code Snippet Description
@Model @Model(adaptables = Resource.class) Class is annotated with @Model and the adaptable class
@Inject
@Inject private String propertyName; (class )
@Inject String getPropertyName(); (interface )
A property named "propertyName" will be looked up from the
Resource (after first adapting it to a ValueMap) and it is injected ,
else will return null if property not found .
@Default @Inject @Default(values = "AEM") private String technology; A default value (for Strings , Arrays , primitives etc. )
@Optional @Inject @Optional private String otherName.
@Injected fields/methods are assumed to be required. To mark
them as optional, use @Optional i.e resource or adaptable may or
may not have property .
Annotations Usage
Sling Model Annotation Code Snippet Description
@Named @Inject @Named("title") private String pageTitle;
Inject a property whose name does NOT match the Model field
name
@Via
@Model(adaptables=SlingHttpServletRequest.class)
public interface SlingModelDemo {
@Inject @Via("resource") String getPropertyName(); }
Use a JavaBean property of the adaptable as the source of the
injection
// Code Snippet will return
request.getResource().adaptTo(ValueMap.class).get("propertyNam
e", String.class)
@Source
@Model(adaptables=SlingHttpServletRequest.class)
@Inject @Source("script-bindings") Resource
getResource(); }
Explicitly tie an injected field or method to a particular injector (by
name). Can also be on other annotations
//Code snippet will ensure that "resource" is retrieved from the
bindings, not a request attribute
@PostConstruct
@PostConstruct
protected void sayHello() { logger.info("hello"); }
Methods to call upon model option creation (only for model classes)
Sling Model Injectors
• Injectors are OSGi services implementing the
org.apache.sling.models.spi.Injector interface
• Injectors are invoked in order of their service ranking, from lowest to
highest.
What are Injectors ?
• Script Bindings (script-bindings)
• Value Map (valuemap)
• Child Resources (child-resources)
• Request Attributes (request-attributes)
• OSGI Service References (osgi-services)
Standard Injectors in 1.0.x
Injectors (with @Source names)
Injects adaptable itself or an object that can be adapted from
adaptable
@Self privateResource resource;
@Model(adaptables = SlingHttpServletRequest.class)
public class SlingModelDemo {
@SlingObject private Resource resource;
@SlingObject private SlingHttpServletRequest request;
}
Injects resource from given path , applicable to Resource or
SlingHttpServletRequest objects
@ResourcePath(path="/resource-path") private Resource resource;
• Self Injector (self)
• Sling Object Injector (sling-object)
• Resource Path Injector (resource-path)
Standard Injectors in 1.1.x
Injectors (with @Source names)
• Supported since Sling Models Impl 1.0.6
• Can use customized annotations with following advantages over
using the standard annotations:
- Less code to write (only one annotation is necessary in most of
the cases)
- More robust
• Injector Specific Annotation specifies source explicitly
• Example
@ValueMapValue String propertyName;
@ValueMapValue (name="jcr:title", optional=true)
String title;
Injector-specific Annotations
Annotation
Supported Optional
Elements
Injector
@ScriptVariable optional and name script-bindings
@ValueMapValue optional, name and via valuemap
@ChildResource optional, name and via child-resources
@RequestAttribute optional, name and via request-attributes
@ResourcePath
optional, path,
and name
resource-path
@OSGiService optional, filter osgi-services
@Self optional self
@SlingObject optional sling-object
Injectors depicted in Felix Console
Using Sling Models with Sightly and JSP
• Need org.apache.sling.models.api package
- OOTB supported in AEM 6 and above version , with
org.apache.sling.models.api package already present in AEM
instance
- For other versions download package from
http://sling.apache.org/downloads.cgi and install in AEM instance
• Maven dependency can be found at
http://<host>:<port>/system/console/depfinder , search for
org.apache.sling.models.annotations.Model
<dependency> <groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.models.api</artifactId>
<version>1.0.0</version> <scope>provided</scope>
</dependency>
Prerequisite
• Search for maven-bundle-plugin in pom.xml file , update it with
following
- <Sling-Model-Packages> com.slingmodels.core </Sling-Model-
Packages>
- It is because for Sling Model classes to be picked up this header
must be added to the bundle's manifest
Prerequisite
• Supported as of Sling Models 1.1.0
• Name of a constructor argument parameter cannot be detected
via the Java Reflection API
• @Named annotation is mandatory for injectors that require a
name for resolving the injection
• @Model(adaptables=Resource.class)
public class MyModel {
@Inject public MyModel(@Named("propertyName") String
propertyName)
{ // constructor code }
}
Constructor Injections
• Sling Model class object can be used in JSP by either
- <c:set var = "slingModel" value="<%=
resource.adaptTo(SlingModelDemo.class)%>" />
Or
- <sling:adaptTo adaptable="${resource}"
adaptTo="com.slingmodels.core.SlingModelDemo"
var=“slingModel"/>
Sling Models with JSP
• Sightly is a beautiful mark up language providing advantages like
separation of concerns , prevents xss vulnerabilities .
• Sling Model class object can be used in Sightly by :
<div data-sly-use.slingModel ="
com.slingmodels.core.SlingModelDemo">
Sling Models with Sightly
Demo
• Retrieving dialog values of a component
• Retrieving recent pages/articles under a content path
• Many more 
Groovifying Demo UseCases :
Code can be found at:
https://github.com/deepakkhetawat/Sling-Model-Demo.git
Where is the Code ?
Appendix and Q&A
• https://sling.apache.org/documentation/bundles/models.html
• http://slideshare.net/justinedelson/sling-models-overview
• https://sling.apache.org/documentation/bundles/sling-scripting-jsp-
taglib.html
Appendix
Q&A
For more information contact:
DEEPAK KHETAWAT
M +91-9910941818
deepak.khetawat@tothenew.com
Thank you

Deepak khetawat sling_models_sightly_jsp

  • 1.
    Sling Models UsingSightly and JSP DEEPAK KHETAWAT
  • 2.
  • 3.
    What & WhySling Models - What are Sling Models - Design Goals - Why Sling Models ? Sling Model Annotations - Annotations Usage Sling Model Injectors - What are Injectors - Injectors available in 1.0.x and 1.1.x - Injector-specific Annotations Agenda Usage of Sling Models - Prerequisite - How to use Sling Models with JSP ? - How to use Sling Models with Sightly? Demo - Functionality Demo Appendix and Q&A - Appendix - Q&A
  • 4.
    What & WhySling Models
  • 5.
    • Sling Modelsare POJO’s which are automatically mapped from Sling objects, typically resources, request objects. Sometimes these POJOs need OSGi services as well What are Sling Models?
  • 6.
    • Entirely annotationdriven. "Pure" POJOs • Adapt multiple objects • Work with existing Sling infrastructure • Client doesn't know/care that these objects are different than any other adapter factory • Support both classes and interfaces • Pluggable Design Goals
  • 7.
    Development : • Savesfrom creating own adapters • Situation Based Dependency Injection Framework • Do More with less code making code readable and Removing redundant (boilerplate) code Testing : • Highly Testable Code - Sling Model Inject Annotations defines binding to dependencies - Mock dependencies with tools like Mockito using @InjectMocks Why Sling Models ?
  • 8.
  • 9.
    Annotations Usage Sling ModelAnnotation Code Snippet Description @Model @Model(adaptables = Resource.class) Class is annotated with @Model and the adaptable class @Inject @Inject private String propertyName; (class ) @Inject String getPropertyName(); (interface ) A property named "propertyName" will be looked up from the Resource (after first adapting it to a ValueMap) and it is injected , else will return null if property not found . @Default @Inject @Default(values = "AEM") private String technology; A default value (for Strings , Arrays , primitives etc. ) @Optional @Inject @Optional private String otherName. @Injected fields/methods are assumed to be required. To mark them as optional, use @Optional i.e resource or adaptable may or may not have property .
  • 10.
    Annotations Usage Sling ModelAnnotation Code Snippet Description @Named @Inject @Named("title") private String pageTitle; Inject a property whose name does NOT match the Model field name @Via @Model(adaptables=SlingHttpServletRequest.class) public interface SlingModelDemo { @Inject @Via("resource") String getPropertyName(); } Use a JavaBean property of the adaptable as the source of the injection // Code Snippet will return request.getResource().adaptTo(ValueMap.class).get("propertyNam e", String.class) @Source @Model(adaptables=SlingHttpServletRequest.class) @Inject @Source("script-bindings") Resource getResource(); } Explicitly tie an injected field or method to a particular injector (by name). Can also be on other annotations //Code snippet will ensure that "resource" is retrieved from the bindings, not a request attribute @PostConstruct @PostConstruct protected void sayHello() { logger.info("hello"); } Methods to call upon model option creation (only for model classes)
  • 11.
  • 12.
    • Injectors areOSGi services implementing the org.apache.sling.models.spi.Injector interface • Injectors are invoked in order of their service ranking, from lowest to highest. What are Injectors ?
  • 13.
    • Script Bindings(script-bindings) • Value Map (valuemap) • Child Resources (child-resources) • Request Attributes (request-attributes) • OSGI Service References (osgi-services) Standard Injectors in 1.0.x Injectors (with @Source names)
  • 14.
    Injects adaptable itselfor an object that can be adapted from adaptable @Self privateResource resource; @Model(adaptables = SlingHttpServletRequest.class) public class SlingModelDemo { @SlingObject private Resource resource; @SlingObject private SlingHttpServletRequest request; } Injects resource from given path , applicable to Resource or SlingHttpServletRequest objects @ResourcePath(path="/resource-path") private Resource resource; • Self Injector (self) • Sling Object Injector (sling-object) • Resource Path Injector (resource-path) Standard Injectors in 1.1.x Injectors (with @Source names)
  • 15.
    • Supported sinceSling Models Impl 1.0.6 • Can use customized annotations with following advantages over using the standard annotations: - Less code to write (only one annotation is necessary in most of the cases) - More robust • Injector Specific Annotation specifies source explicitly • Example @ValueMapValue String propertyName; @ValueMapValue (name="jcr:title", optional=true) String title; Injector-specific Annotations Annotation Supported Optional Elements Injector @ScriptVariable optional and name script-bindings @ValueMapValue optional, name and via valuemap @ChildResource optional, name and via child-resources @RequestAttribute optional, name and via request-attributes @ResourcePath optional, path, and name resource-path @OSGiService optional, filter osgi-services @Self optional self @SlingObject optional sling-object
  • 16.
    Injectors depicted inFelix Console
  • 17.
    Using Sling Modelswith Sightly and JSP
  • 18.
    • Need org.apache.sling.models.apipackage - OOTB supported in AEM 6 and above version , with org.apache.sling.models.api package already present in AEM instance - For other versions download package from http://sling.apache.org/downloads.cgi and install in AEM instance • Maven dependency can be found at http://<host>:<port>/system/console/depfinder , search for org.apache.sling.models.annotations.Model <dependency> <groupId>org.apache.sling</groupId> <artifactId>org.apache.sling.models.api</artifactId> <version>1.0.0</version> <scope>provided</scope> </dependency> Prerequisite
  • 19.
    • Search formaven-bundle-plugin in pom.xml file , update it with following - <Sling-Model-Packages> com.slingmodels.core </Sling-Model- Packages> - It is because for Sling Model classes to be picked up this header must be added to the bundle's manifest Prerequisite
  • 20.
    • Supported asof Sling Models 1.1.0 • Name of a constructor argument parameter cannot be detected via the Java Reflection API • @Named annotation is mandatory for injectors that require a name for resolving the injection • @Model(adaptables=Resource.class) public class MyModel { @Inject public MyModel(@Named("propertyName") String propertyName) { // constructor code } } Constructor Injections
  • 21.
    • Sling Modelclass object can be used in JSP by either - <c:set var = "slingModel" value="<%= resource.adaptTo(SlingModelDemo.class)%>" /> Or - <sling:adaptTo adaptable="${resource}" adaptTo="com.slingmodels.core.SlingModelDemo" var=“slingModel"/> Sling Models with JSP
  • 22.
    • Sightly isa beautiful mark up language providing advantages like separation of concerns , prevents xss vulnerabilities . • Sling Model class object can be used in Sightly by : <div data-sly-use.slingModel =" com.slingmodels.core.SlingModelDemo"> Sling Models with Sightly
  • 23.
  • 24.
    • Retrieving dialogvalues of a component • Retrieving recent pages/articles under a content path • Many more  Groovifying Demo UseCases :
  • 25.
    Code can befound at: https://github.com/deepakkhetawat/Sling-Model-Demo.git Where is the Code ?
  • 26.
  • 27.
    • https://sling.apache.org/documentation/bundles/models.html • http://slideshare.net/justinedelson/sling-models-overview •https://sling.apache.org/documentation/bundles/sling-scripting-jsp- taglib.html Appendix
  • 28.
  • 29.
    For more informationcontact: DEEPAK KHETAWAT M +91-9910941818 deepak.khetawat@tothenew.com Thank you