Using Sling adapters using-sling-adapters

Sling offers an Adapter pattern to translate objects conveniently that implement the Adaptable interface. This interface provides a generic adaptTo() method that translates the object to the class type being passed as the argument.

For example, to translate a Resource object to the corresponding Node object, you can simply do:

Node node = resource.adaptTo(Node.class);

Use cases use-cases

There are the following use cases:

  • Get implementation-specific objects.

    For example, a JCR-based implementation of the generic Resource interface provides access to the underlying JCR Node.

  • Shortcut creation of objects that require internal context objects to be passed.

    For example, the JCR-based ResourceResolver holds a reference to the request’s JCR Session, which in turn is needed for many objects that can work based on that request session, such as the PageManager or UserManager.

  • Shortcut to services.

    A rare case - sling.getService() is simple as well.

Null return value null-return-value

The adaptTo() returns null.

The reasons vary, including the following:

  • The implementation does not support the target type.
  • An adapter factory handling this case is not active (for example, due to missing service references)
  • An internal condition failed.
  • The service is not available.

It is important that you handle the null case gracefully. For jsp renderings, it might be acceptable to have the jsp fail if it results in an empty piece of content.

Caching caching

To improve performance, implementations are free to cache the object returned from a obj.adaptTo() call. If the obj is the same, the returned object is the same.

This caching is performed for all AdapterFactory based cases.

However, there is no general rule - the object could be either a new instance or an existing one. This means that you cannot rely on either behavior. Hence, it is important, especially inside AdapterFactory, that objects are reusable in this scenario.

How it works how-it-works

There are various ways that Adaptable.adaptTo() can be implemented:

  • By the object itself; implementing the method itself and mapping to certain objects.

  • By an AdapterFactory, which can map arbitrary objects.

    The objects must still implement the Adaptable interface and must extend SlingAdaptable (which passes the adaptTo call to a central adapter manager).

    Hooks into the adaptTo mechanism for existing classes, such as Resource.

  • A combination of both.

For the first case, the Java™ docs can state what adaptTo-targets are possible. However, for specific subclasses such as the JCR-based resource, it is often not possible. In the latter case, implementations of AdapterFactory are typically part of the private classes of a bundle and thus not exposed in a client API, or listed in Java™ docs. Theoretically, it would be possible to access all AdapterFactory implementations from the OSGi service runtime and look at their “adaptables” (sources and targets) configurations, but not to map them to each other. In the end, it depends on the internal logic, which must be documented. Hence, the reference.

Reference reference

Sling sling

Resource adapts to:

Node
If it is a JCR-node-based resource or a JCR property referencing a node
Property
If it is a JCR-property-based resource
Item
If it is a JCR-based resource (node or property)
Map
It returns a map of the properties, if it is a JCR-node-based resource (or other resource supporting value maps).
ValueMap
It returns a convenient-to-use map of the properties, if it is a JCR-node-based resource or other resource supporting value maps. It can also be achieved (more simply) by using
ResourceUtil.getValueMap(Resource) (handles null case, and so on).
InheritanceValueMap
Extension of ValueMap which allows the hierarchy of resources to be taken into account when looking for properties.
ModifiableValueMap
An extension of the ValueMap, which lets you modify properties on that node.
InputStream
It returns the binary content of a file resource when it's JCR node-based (nt:file or nt:resource), a bundle resource, or a file system resource. It returns the data of a binary JCR property resource.
URL
It returns a URL for the resource. It returns the repository URL for a JCR node-based resource, the JAR bundle URL for a bundle resource, or the file URL for a file system resource.
File
If it is a file system resource
SlingScript
If this resource is a script (for example, jsp file) for which a script engine is registered with sling.
Servlet
If this resource is a script (for example, jsp file) for which a script engine is registered with sling or if it is a servlet resource.
String
Boolean
Long
Double
Calendar
Value
String[]
Boolean[]
Long[]
Calendar[]
Value[]
Returns the values if it is a JCR-property-based resource (and the value fits).
LabeledResource
If it is a JCR-node-based resource
Page
If it is a JCR-node-based resource and the node is a cq:Page (or cq:PseudoPage).
Component
If it is a cq:Component node resource
Design
If it is a design node (cq:Page)
Template
If it is a cq:Template node resource
Blueprint
If it is a cq:Template node resource
Asset
If it is a dam:Asset node resource
Rendition
If it is a dam:Asset rendition (nt:file under the rendition folder of a dam:Asset)
Tag
If it is a cq:Tag node resource
UserManager
Based on the JCR session if it is a JCR-based resource and the user has permissions to access the UserManager.
Authorizable
The Authorizable is the common base interface for User and Group.
User
The user is a special Authorizable that can be authenticated and impersonated.
SimpleSearch
Searches below the resource (or use setSearchIn()) if it is a JCR-based resource.
WorkflowStatus
Workflow status for the given page / workflow payload node.
ReplicationStatus
Replication status for the given resource or its jcr:content subnode (checked first).
ConnectorResource
It returns an adapted connector resource for certain types, if it is a JCR-node-based resource.
Config
If it is a cq:ContentSyncConfig node resource
ConfigEntry
If it is below a cq:ContentSyncConfig node resource

ResourceResolver adapts to:

Session
The request's JCR session, if it is a JCR-based resource resolver (default).
PageManager
ComponentManager
Designer
AssetManager
Based on the JCR session, if it is a JCR-based resource resolver.
TagManager
Based on the JCR session, if it is a JCR-based resource resolver.
UserManager
The UserManager provides access to and means to maintain authorizable objects that are users and groups. The UserManager is bound to a particular Session.
Authorizable
The current user.
User
The current user.
QueryBuilder
Externalizer
For externalizing absolute URLs, even without the request object.

SlingHttpServletRequest adapts to:

No targets yet, but implements Adaptable and could be used as source in a custom AdapterFactory.

SlingHttpServletResponse adapts to:

ContentHandler
(XML)
If it is a sling rewriter response

WCM wcm

The page adapts to:

Resource
Resource of the page.
LabeledResource
Labeled resource is the current resource. That is, the same object you are looking at.
Node
Node of the page.
...
Everything that the page's resource can be adapted to.

The component adapts to:

Resource
Resource of the component.
LabeledResource
Labeled resource is the current resource. That is, the same object you are looking at.
Node
Node of the component.
Everything that the component’s resource can be adapted to.

The template adapts to:

Resource
Resource of the template.
LabeledResource
Labeled resource is the current resource. That is, the same object you are looking at.
Node
Node of this template.
...
Everything that the template's resource can be adapted to.

Security security

Authorizable, **User, and Group adapt to:

Node
Returns the user / group home node.
ReplicationStatus
It returns the replication status for the user / group home node.

DAM dam

Asset adapts to:

Resource
Resource of the asset.
Node
Node of the asset.
Everything that the asset’s resource can be adapted to.

Tag tagging

Tag adapts to:

Resource
Resource of the tag.
Node
Node of the tag.
Everything that the tag’s resource can be adapted to.

Other other

Furthermore, Sling / JCR / OCM also provides an [AdapterFactory](https://sling.apache.org/site/adapters.html#Adapters-AdapterFactory) for custom OCM (Object Content Mapping) objects.

recommendation-more-help
experience-manager-65-lts-help-main-toc