Sling Basic Concepts
Sling Basic Concepts
adaptTo() 2012
adaptTo() 2012
Agenda
General
Architecture
Request Handling
URL decomposition
Dispatching Requests
Servlets and Scripts
Filters
Resources
Resources
Resource Provider and Resource Resolver
Resource Resolution Mapping
Sling API
Adapters
Sling API
adaptTo() 2012
Sling Architecture
adaptTo() 2012
adaptTo() 2012
Roy Fielding
adaptTo() 2012
adaptTo() 2012
Agenda
General
Architecture
Request Handling
URL decomposition
Dispatching Requests
Servlets and Scripts
Filters
Resources
Resources
Resource Provider and Resource Resolver
Resource Resolution Mapping
Sling API
Adapters
Sling API
adaptTo() 2012
10
adaptTo() 2012
11
URL Decomposition
adaptTo() 2012
12
adaptTo() 2012
13
adaptTo() 2012
14
adaptTo() 2012
15
adaptTo() 2012
16
URI
Resource Path
Selectors
Extension
Suffix Path
/a/b
/a/b
null
null
null
/a/b.html
/a/b
null
html
null
/a/b.s1.html
/a/b
s1
html
null
/a/b.html/c/d
/a/b
null
html
/c/d
adaptTo() 2012
17
Resource Resolution
Now Slings tries to find the resource addressed
Mappings are applied
Registered ResourceProviders are asked for a
resource with the resulting path
Most of the time the default JcrResourceProvider will
end up delivering the resource by looking it up in the
backing repository
But the resource might also be provided by anything
mapped into the resource tree by a suitable
ResourceProvider
adaptTo() 2012
18
Resource Type
To allow for different processing for different kinds of resources,
Sling has the notion of a resource type
The resource type determines the script that is used for
processing the resource
Declaration of the resource type with sling:resourceType
Since resource types are treated as a path in the script selection
process you should use path-like, slash delimited resource types
like:
company/homepage
Fallback: converting of the primary node type of the resource to
a path (by replacing the colons with slashes) and trying that one
(e.g. nt:file becomes nt/file)
adaptTo() 2012
19
sling/servlet/default
20
Script Locations
To determine the location of the script to process the resource,
Sling converts the resource type to a path
If this path is absolute (i.e. starts with a slash), it is used as-is.
Resource Type: /apps/company/homepage
Search Locations: /apps/company/homepage
If the path is relative, the ResourceResolver prepends each of the
configured search paths to it and searches the resulting paths (in
the order they are configured)
Path [ "/apps", "/libs" ]
Resource Type: company/homepage
Search Locations:
/apps/company/homepage
/libs/company/homepage
adaptTo() 2012
21
Script Names
Depending on whether request selectors are considered, a script
name may have two forms:
Without selectors:
{resourceTypeLabel}.{requestExtension}.{requestMethod}.{scriptExtension}
With selectors:
{selectorStringPath}.{requestExtension}.{requestMethod}.{scriptExtension}
adaptTo() 2012
22
adaptTo() 2012
23
/content/adaptto/sling/basics/stock/overview.beverage.beer.html
with the resource type
adaptto/sling/basics/stock
Assuming we have the following list of scripts in the correct location
then the order of preference would be (7) - (6) - (5) - (4) - (3) - (2) - (1)
1. GET.jsp
2. stock.jsp
3. html.jsp
4. beverage.jsp
5. beverage.html.jsp
6. beverage/beer.jsp
7. beverage/beer/html.jsp
adaptTo() 2012
24
SlingRequestDispatcher
Include or forward a request to another resource:
forward() is like a server-side redirect where control is completely
handed over to another resource
include() is like a server-side include where the output of the targeted
resource is included into the response
adaptTo() 2012
25
adaptTo() 2012
26
Scripting Options
Sling supports scripting via JSR 223
Out of the box Sling provides these scripting languages:
JSP
Groovy
JavaScript
DefaultSlingScript acts as a facade for Servlets and Scripts
class DefaultSlingScript implements SlingScript, Servlet, ServletConfig {
adaptTo() 2012
27
Scripting Options
Some options that are available as contributions include:
Python
Ruby
Scala
Freemarker
Velocity
Java (as .java source files)
See http://localhost:8080/system/console/config in the Script
Engines tab for available script engines
adaptTo() 2012
28
uri=http://sling.apache.org/taglibs/sling/1.0
<sling:defineObjects>
request
response
resource
out
<sling:include>
Includes a resource rendering into the current page
adaptTo() 2012
29
Servlets
Registration via OSGi HTTP Service
Bare-bones OSGi way of registering servlets, used by the
SlingMainServlet
Servlets registered via the HTTP service bypass Sling
processing
Registration via Whiteboard
30
Default Servlets
SlingMainServlet
Entry point into the Sling request handling after
authentication
DefaultGetServlet
Provides default renderers for resources (HTML, TXT, JSON,
XML)
SlingPostServlet
Allows extensive content manipulation (create, delete, update)
through its REST API
DefaultErrorHandlerServlet
Default error handler servlet registered at the end of the
global search path
adaptTo() 2012
31
SlingSafeMethodServlet
Sling contains the SlingSafeMethodsServlet base class as a
helper for implementing read-only servlets
When overwriting its doXXX methods, you dont need to cast the
request and response objects to have access to the Sling-specific
methods
adaptTo() 2012
32
Path
Discouraged in Sling!
Bypasses access control
Use only for servlets which are independently of the existence of any
specific resource
adaptTo() 2012
33
Extension
Use this for alternative representations of a resource as
another file type (PDF, PNG, JSON etc.)
Method
Youll primarily use this to implement some specific data
storage by binding a servlet to the POST method also.
adaptTo() 2012
34
Filters in Sling
Used for authentication, post-processing of markup etc.
Filters in Sling are services implementing the javax.servlet.Filter
interface
Two service properties are relevant:
sling.filter.scope Indicates the filter chain the filter should
be part of. Required! Sling wont pick up your filter if it isnt
set.
service.ranking Indicates the priority of the filter in the
chain. The higher the number the earlier the filter will be
invoked.
Current filter configuration can be inspected in the Sling
Servlet Filter tab at
http://localhost:8080/system/console/config
adaptTo() 2012
35
The SlingPostServlet
Sample:
<form method="POST" action="http://host/new/content"
enctype="multipart/form-data">
<input type="text" name="title" value="" />
<input type="Submit" />
</form>
adaptTo() 2012
36
Indicates that the title property should be set to Some Value, unless the
value of the title parameter is not blank.
Indicates that the value of the checked-Property should be set on the
target Node as Boolean.
adaptTo() 2012
37
Agenda
General
Architecture
Request Handling
URL decomposition
Dispatching Requests
Servlets and Scripts
Filters
Resources
Resources
Resource Provider and Resource Resolver
Resource Resolution Mapping
Sling API
Adapters
Sling API
adaptTo() 2012
38
Resources
What is a Resource?
Extending from JCR's Everything is Content, Sling
assumes that (almost) Everthing is a Resource. Thus
Sling is maintaining a virtual tree of resources, which
is a merger of the actual contents in the JCR
Repository and resources provided by so called
resource providers.
adaptTo() 2012
39
JCR-based Resources
Since Sling is built upon JCR, these (JCR-based)
Resources are the default and youll encounter them
most often
JCR-based Resources are provided with the
default JcrResourceProvider
The JcrResourceProvider is always available and is
always asked last.
Resources provided by other Resource providers may never
be overruled by repository based Resources.
adaptTo() 2012
40
Bundle-based Resources
Resources can be provided by files (resourceType=nt:file) and
directories (resourceType=nt:folder) contained in an OSGi bundle
The BundleResourceProvider is responsible for mapping the
directory tree into the resource tree
Your bundle has to declare the resources it provides with the
header Sling-Bundle-Resources
Its very convenient to add it as instruction in the maven-bundleplugin configuration:
<configuration>
<instructions>
<Sling-BundleResources>/resource/tree;path:=/bundle/tree</Sling-Bundle-Resources>
</instructions>
</configuration>
adaptTo() 2012
41
Filesystem Resources
FilesystemResourceProvider can mount a directory
from the local file system into the resource tree
As with other similar providers files use the nt:file
resource type, directories the nt:folder resource type
FilesystemResourceProvider can be configured via the
OSGi configuration console
adaptTo() 2012
42
ResourceProvider
Provides access to resources from different locations
through a single ResourceResolver
Registered to a path in the virtual resource tree, its
able to provide resources below that location
ResourceResolver asks ResourceProviders in the order
of longest match of the root path (e.g. R1 registered
below /content/a will have higher priority than R2
registered below /content)
JCR ResourceProvider is registered at the root (/) of
the virtual resource tree
Last fallback is always the JCR repository
adaptTo() 2012
43
Resource Resolver
Gateway for resources, abstracts the path resolution
Abstracts access to the persistence layer(s)
resolve() : central method for matching a path to a resource
map() : inverse operation to resolve(), yielding an external path
for a resource path
Generated by ResourceResolverFactory based on current user
credentials
Available through
SlingHttpServletRequest.getResourceResolver()
Resource Enumeration through listChildren()
adaptTo() 2012
44
adaptTo() 2012
45
Querying Resources
The ResourceResolver provides two methods for
querying Resources:
ResourceResolver.findResources(query, language)
ResourceResolver.queryResources(query, language)
Those are convenience wrappers around the JCR
Query functionality
Only repository based resources are supported, as
currently theres no way for ResourceProviders that
are not repository based to support queries
adaptTo() 2012
46
{scheme}/{host.port}/{uri_path}
47
adaptTo() 2012
48
Mapping Example
/etc/map
+-- http
+-- www.example.com.80
+-- sling:internalRedirect = "/example"
+-- any_example.com.80
+-- sling:match = ".+\.example\.com\.80"
+-- sling:redirect = "http://www.example.com/"
+-- localhost_any
+-- sling:match = "localhost\.\d*"
+-- sling:internalRedirect = "/content"
+-- (stories)
+-- sling:internalRedirect = /anecdotes/$1"
adaptTo() 2012
49
Mapping Example
Regular Expression
Redirect
Internal Description
http/www.example.com.80
/example
yes
http/.+\.example\.com\.80
http://www.exa no
mple.com
http/localhost\.\d*
/content
yes
http/localhost\.\d*/(stories)
/anecdotes/stor yes
ies
adaptTo() 2012
50
Namespace Mangling
Paths in Sling often contain colons as theyre used for
namespacing in the underlying JCR Repository
Namespace mangling encloses the namespace prefix in
underscores and removes the colon
Only namespaces registered with JCR are processed to prevent
mangling of paths that might contain underscores
The mangling takes place in the map() methods (to take care of
paths leaving the system)
The unmangling is done in the resolve() methods (to handle
incoming paths)
Example:
/content/_a_sample/jcr:content/jcr:data.png
gets mangled to :
/content/_a_sample/_jcr_content/_jcr_data.png
adaptTo() 2012
51
Agenda
General
Architecture
Request Handling
URL decomposition
Dispatching Requests
Servlets and Scripts
Filters
Resources
Resources
Resource Provider and Resource Resolver
Resource Resolution Mapping
Sling API
Adapters
Sling API
adaptTo() 2012
52
Adapters
adaptTo() (interface Adaptable) on
Resource/ResourceResolver-Implementations
Code Sample:
ValueMap valueMap = getResource().adaptTo(ValueMap.class);
adaptTo() 2012
53
54
(Sling)Request/Response, RequestPathInfo
SlingHttpServletRequest
SlingHttpServletResponse
RequestPathInfo
adaptTo() 2012
55
Resource
Resource extends Adaptable
Example:
Resource resource = resourceResolver.getResource(path);
Resource parentResource = resource.getParent();
Iterator<Resource> resourceIterator =
parentResource.listChildren();
while (resourceIterator.hasNext()) {
Resource childResource = resourceIterator.next();
if(childResource.isResourceType("comp/book")) {
// do something
}
}
adaptTo() 2012
56
ResourceResolver
ResourceResolver extends Adaptable
defines two kinds of methods to access resources: The resolve
methods and the getResource methods
Method Kind
adaptTo() 2012
Access Algorithm
resolve
getResource
57
ValueMap
ValueMap extends Map<String, Object>
The ValueMap offers an easy way to access the properties of a
resource.
With most resources you can use the Resource.adaptTo method to
adapt the resource to a value map
Example:
ValueMap vMap = resource.adaptTo(ValueMap.class);
String str1 = vMap.get("propName" String.class);
String str2 = vMap.get("propName", "");
adaptTo() 2012
58