SlideShare uma empresa Scribd logo
1 de 17
Baixar para ler offline
CIRCUIT
AN ADOBE DEVELOPER EVENT
PRESENTED BY CITYTECH, INC.
Use SlingQuery and
walk the tree with ease
Tomek Rękawek, Cognifide
@TomaszRekawek
Sling API
Resource parent = myResource.getParent();
for (Resource child : parent.getChildren()) {
if (child.adaptTo(ValueMap.class).containsKey("myProperty")) {
//...
}
}
efficient, especially for denormalized and well-
structured content[1]
easy to use
but:
a lot of while()s, iterators and nullchecks
code complexity is growing fast
[1] Efficient content structures and queries in CRX
Sling example
Find the first ancestor with a given template.
String path = "/content/geometrixx/en/products/triangle/jcr:content/par";
String homeTemplate = "/apps/geometrixx/templates/homepage";
Resource resource = resourceResolver.getResource(path);
while ((resource = resource.getParent()) != null) {
if (!resource.isResourceType("cq:Page")) {
continue;
}
ValueMap map = resource.adaptTo(ValueMap.class);
String cqTemplate = map.get("jcr:content/cq:template");
if (homeTemplate.equals(cqTemplate)) {
break;
}
}
resource.getPath();
SlingQuery example
import static com.cognifide.sling.query.api.SlingQuery.$;
Resource resource = getResource("/content/geometrixx/en/products/triangle/jcr:content/par");
$(resource)
.closest("cq:Page[jcr:content/cq:template=/apps/geometrixx/templates/homepage]")
$()is a valid method name in Java,
it wraps resource(s) into an iterable SlingQuery
collection
each method transforms the existing collection
into a new one
API inspired by jQuery
Get all text components
from the parsys
r = getResource("/content/geometrixx/en/jcr:content/rightpar/teaser")
SlingQuery collection = $(r)
.closest("cq:PageContent")
.find("foundation/components/parsys#par")
.children("foundation/components/text")
for (Resource c : collection) {
println c.path
}
each method returns new collection
SlingQueryobject implements Iterable
Breadcrumbs
r = getResource("/content/geometrixx/en/products/mandelbrot/overview/jcr:content/par")
Iterable<Page> breadcrumbs = $(r)
.parents("cq:Page")
.not("[jcr:content/hideInNav=true]")
.map(Page.class)
for (Page p : breadcrumbs) {
println p.title
}
map()method creates a new Iterable<>
adapting each resource to a given class
resource.adaptTo(Page.class)
approach compatible with Sling Models
Selector string
r = getResource("/content/geometrixx/en/products/mandelbrot")
$(r)
.children("cq:PageContent")
.children("foundation/components/parsys")
.children("#title[jcr:title=Best in class][type=large]:first")
selector format
resource type or node type
#resource-name
attributes in []
modifiers, each prepended by :
all elements are optional
Advanced selectors
r = getResource("/content/geometrixx")
$(r)
.find("[text*=square]:not(cq:PageContent):first")
.closest("cq:Page")
.find("#title, #image, #par:parent")
:not()accepts any valid selector
:not(:not(:not(:first)))
:parent- only resources having children
there is a number of operators for square brackets
alternatives can be separated with a comma
Random image
rnd = new java.util.Random()
r = getResource("/content/dam/geometrixx/travel")
$(r)
.children("dam:Asset")
.filter({ rnd.nextFloat() > 0.9 } as Predicate)
.first()
in Java it'd look like this:
// ...
.filter(new Predicate<Resource>() {
@Override
public boolean accepts(Resource resource) {
return rnd.nextFloat() > 0.9;
}
});
Siblings but not me
r = getResource("/content/geometrixx/en/products/mandelbrot/jcr:content/par/image")
myPage = $(r).closest("cq:Page")
result = myPage
.siblings("cq:Page")
.not(myPage)
the SlingQuery collection is immutable
each method returns a new collection
any Iterable<Resource>may be used as a filter
Find all pages with
given template
$(resourceResolver)
.find("cq:PageContent[cq:template=/apps/geometrixx/templates/homepage]")
.parent()
$(resourceResolver)creates a collection
containing /
find()iterates over the whole subtree
Search strategy
r = getResource("/content/geometrixx/en")
result = $(r)
.searchStrategy(DFS)
.find("cq:Page")
for (Resource c : result) {
println c.path
}
strategies: DFS, BFS, QUERY
QUERYtries to rewrite find()selector into JCR-
SQL2
the result is filtered once more
Find method vs JCR
find()is powerful but may be dangerous
it should be used only for small subtrees
if you want to query a large space, use JCR-SQL[2]
or XPath
if your SlingQuery processes more than 100
resources, you'll get a warning in the logs:
28.05.2014 13:35:49.942 *WARN* [0:0:0:0:0:0:0:1 [1401276949857] POST /bin/groovy
console/post.json HTTP/1.1] SlingQuery Number of processed resources exceeded 10
0. Consider using a JCR query instead of SlingQuery. More info here: http://git.
io/h2HeUQ
Laziness
result = $(resourceResolver)
.searchStrategy(DFS)
.find()
.slice(10, 20)
result.toString()
we don't query resources unless we need them
invoking the SlingQuery method adds a new
function to the chain
functions are executed by the final iterator (like
the one created by the for()loop)
all functions are lazy
expect the last()function
Resources
code & docs
global Maven repository
https://github.com/Cognifide/Sling-Query
<dependency>
<groupId>com.cognifide.cq</groupId>
<artifactId>sling-query</artifactId>
<version>1.4.4</version>
</dependency>
Questions?
Thank you!

Mais conteúdo relacionado

Mais procurados

jQuery Datatables With MongDb
jQuery Datatables With MongDbjQuery Datatables With MongDb
jQuery Datatables With MongDbsliimohara
 
Google apps script database abstraction exposed version
Google apps script database abstraction   exposed versionGoogle apps script database abstraction   exposed version
Google apps script database abstraction exposed versionBruce McPherson
 
Lift 2 0
Lift 2 0Lift 2 0
Lift 2 0SO
 
JavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerJavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerBruce McPherson
 
Enonic Content Repository built on elasticsearch
Enonic Content Repository built on elasticsearchEnonic Content Repository built on elasticsearch
Enonic Content Repository built on elasticsearchenonic
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js FundamentalsMark
 
MongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineMongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineJason Terpko
 
Анатолий Кулаков «Windows PowerShell во имя добра»
Анатолий Кулаков «Windows PowerShell во имя добра»Анатолий Кулаков «Windows PowerShell во имя добра»
Анатолий Кулаков «Windows PowerShell во имя добра»SpbDotNet Community
 
Using Arbor/ RGraph JS libaries for Data Visualisation
Using Arbor/ RGraph JS libaries for Data VisualisationUsing Arbor/ RGraph JS libaries for Data Visualisation
Using Arbor/ RGraph JS libaries for Data VisualisationAlex Hardman
 
MongoDB Aggregation
MongoDB Aggregation MongoDB Aggregation
MongoDB Aggregation Amit Ghosh
 
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...MongoDB
 

Mais procurados (20)

jQuery Datatables With MongDb
jQuery Datatables With MongDbjQuery Datatables With MongDb
jQuery Datatables With MongDb
 
Google apps script database abstraction exposed version
Google apps script database abstraction   exposed versionGoogle apps script database abstraction   exposed version
Google apps script database abstraction exposed version
 
wtf is in Java/JDK/wtf7?
wtf is in Java/JDK/wtf7?wtf is in Java/JDK/wtf7?
wtf is in Java/JDK/wtf7?
 
XQuery Rocks
XQuery RocksXQuery Rocks
XQuery Rocks
 
JQuery Flot
JQuery FlotJQuery Flot
JQuery Flot
 
LibreCat::Catmandu
LibreCat::CatmanduLibreCat::Catmandu
LibreCat::Catmandu
 
Lift 2 0
Lift 2 0Lift 2 0
Lift 2 0
 
Dbabstraction
DbabstractionDbabstraction
Dbabstraction
 
JavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerJavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primer
 
Polyglot Persistence
Polyglot PersistencePolyglot Persistence
Polyglot Persistence
 
Enonic Content Repository built on elasticsearch
Enonic Content Repository built on elasticsearchEnonic Content Repository built on elasticsearch
Enonic Content Repository built on elasticsearch
 
Not your Grandma's XQuery
Not your Grandma's XQueryNot your Grandma's XQuery
Not your Grandma's XQuery
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js Fundamentals
 
MongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineMongoDB - Aggregation Pipeline
MongoDB - Aggregation Pipeline
 
Grails UI Primer
Grails UI PrimerGrails UI Primer
Grails UI Primer
 
Анатолий Кулаков «Windows PowerShell во имя добра»
Анатолий Кулаков «Windows PowerShell во имя добра»Анатолий Кулаков «Windows PowerShell во имя добра»
Анатолий Кулаков «Windows PowerShell во имя добра»
 
Using Arbor/ RGraph JS libaries for Data Visualisation
Using Arbor/ RGraph JS libaries for Data VisualisationUsing Arbor/ RGraph JS libaries for Data Visualisation
Using Arbor/ RGraph JS libaries for Data Visualisation
 
Bulk copy
Bulk copyBulk copy
Bulk copy
 
MongoDB Aggregation
MongoDB Aggregation MongoDB Aggregation
MongoDB Aggregation
 
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
 

Semelhante a SlingQuery

Remote code-with-expression-language-injection
Remote code-with-expression-language-injectionRemote code-with-expression-language-injection
Remote code-with-expression-language-injectionMickey Jack
 
Sling models by Justin Edelson
Sling models by Justin Edelson Sling models by Justin Edelson
Sling models by Justin Edelson AEM HUB
 
Elasticsearch & "PeopleSearch"
Elasticsearch & "PeopleSearch"Elasticsearch & "PeopleSearch"
Elasticsearch & "PeopleSearch"George Stathis
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011Nick Sieger
 
Declarative & workflow based infrastructure with Terraform
Declarative & workflow based infrastructure with TerraformDeclarative & workflow based infrastructure with Terraform
Declarative & workflow based infrastructure with TerraformRadek Simko
 
Android basic 4 Navigation Drawer
Android basic 4 Navigation DrawerAndroid basic 4 Navigation Drawer
Android basic 4 Navigation DrawerEakapong Kattiya
 
Designing a JavaFX Mobile application
Designing a JavaFX Mobile applicationDesigning a JavaFX Mobile application
Designing a JavaFX Mobile applicationFabrizio Giudici
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stackTomáš Kypta
 
Intro to Spark and Spark SQL
Intro to Spark and Spark SQLIntro to Spark and Spark SQL
Intro to Spark and Spark SQLjeykottalam
 
CoffeeScript Design Patterns
CoffeeScript Design PatternsCoffeeScript Design Patterns
CoffeeScript Design PatternsTrevorBurnham
 
Scala Programming for Semantic Web Developers ESWC Semdev2015
Scala Programming for Semantic Web Developers ESWC Semdev2015Scala Programming for Semantic Web Developers ESWC Semdev2015
Scala Programming for Semantic Web Developers ESWC Semdev2015Jean-Paul Calbimonte
 
Integration patterns in AEM 6
Integration patterns in AEM 6Integration patterns in AEM 6
Integration patterns in AEM 6Yuval Ararat
 
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
 
NEMROD : Symfony2 components to work with native RDF
NEMROD : Symfony2 components to work with native RDFNEMROD : Symfony2 components to work with native RDF
NEMROD : Symfony2 components to work with native RDFConjecto
 
Experience Manager 6 Developer Features - Highlights
Experience Manager 6 Developer Features - HighlightsExperience Manager 6 Developer Features - Highlights
Experience Manager 6 Developer Features - HighlightsCédric Hüsler
 
Serverless archtiectures
Serverless archtiecturesServerless archtiectures
Serverless archtiecturesIegor Fadieiev
 

Semelhante a SlingQuery (20)

Remote code-with-expression-language-injection
Remote code-with-expression-language-injectionRemote code-with-expression-language-injection
Remote code-with-expression-language-injection
 
Sling models by Justin Edelson
Sling models by Justin Edelson Sling models by Justin Edelson
Sling models by Justin Edelson
 
Elasticsearch & "PeopleSearch"
Elasticsearch & "PeopleSearch"Elasticsearch & "PeopleSearch"
Elasticsearch & "PeopleSearch"
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
Declarative & workflow based infrastructure with Terraform
Declarative & workflow based infrastructure with TerraformDeclarative & workflow based infrastructure with Terraform
Declarative & workflow based infrastructure with Terraform
 
Android basic 4 Navigation Drawer
Android basic 4 Navigation DrawerAndroid basic 4 Navigation Drawer
Android basic 4 Navigation Drawer
 
Designing a JavaFX Mobile application
Designing a JavaFX Mobile applicationDesigning a JavaFX Mobile application
Designing a JavaFX Mobile application
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
Intro to Spark and Spark SQL
Intro to Spark and Spark SQLIntro to Spark and Spark SQL
Intro to Spark and Spark SQL
 
CoffeeScript Design Patterns
CoffeeScript Design PatternsCoffeeScript Design Patterns
CoffeeScript Design Patterns
 
SWT Lecture Session 4 - Sesame
SWT Lecture Session 4 - SesameSWT Lecture Session 4 - Sesame
SWT Lecture Session 4 - Sesame
 
4 sesame
4 sesame4 sesame
4 sesame
 
Scala Programming for Semantic Web Developers ESWC Semdev2015
Scala Programming for Semantic Web Developers ESWC Semdev2015Scala Programming for Semantic Web Developers ESWC Semdev2015
Scala Programming for Semantic Web Developers ESWC Semdev2015
 
Integration patterns in AEM 6
Integration patterns in AEM 6Integration patterns in AEM 6
Integration patterns in AEM 6
 
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
 
Android query
Android queryAndroid query
Android query
 
NEMROD : Symfony2 components to work with native RDF
NEMROD : Symfony2 components to work with native RDFNEMROD : Symfony2 components to work with native RDF
NEMROD : Symfony2 components to work with native RDF
 
Experience Manager 6 Developer Features - Highlights
Experience Manager 6 Developer Features - HighlightsExperience Manager 6 Developer Features - Highlights
Experience Manager 6 Developer Features - Highlights
 
Serverless archtiectures
Serverless archtiecturesServerless archtiectures
Serverless archtiectures
 

Mais de Tomasz Rękawek

Deep-dive into cloud-native AEM deployments based on Kubernetes
Deep-dive into cloud-native AEM deployments based on KubernetesDeep-dive into cloud-native AEM deployments based on Kubernetes
Deep-dive into cloud-native AEM deployments based on KubernetesTomasz Rękawek
 
Emulating Game Boy in Java
Emulating Game Boy in JavaEmulating Game Boy in Java
Emulating Game Boy in JavaTomasz Rękawek
 
Zero downtime deployments for the Sling-based apps using Docker
Zero downtime deployments for the Sling-based apps using DockerZero downtime deployments for the Sling-based apps using Docker
Zero downtime deployments for the Sling-based apps using DockerTomasz Rękawek
 
CRX2Oak - all the secrets of repository migration
CRX2Oak - all the secrets of repository migrationCRX2Oak - all the secrets of repository migration
CRX2Oak - all the secrets of repository migrationTomasz Rękawek
 
Inter-Sling communication with message queue
Inter-Sling communication with message queueInter-Sling communication with message queue
Inter-Sling communication with message queueTomasz Rękawek
 
Shooting rabbits with sling
Shooting rabbits with slingShooting rabbits with sling
Shooting rabbits with slingTomasz Rękawek
 

Mais de Tomasz Rękawek (9)

Radio ad blocker
Radio ad blockerRadio ad blocker
Radio ad blocker
 
Deep-dive into cloud-native AEM deployments based on Kubernetes
Deep-dive into cloud-native AEM deployments based on KubernetesDeep-dive into cloud-native AEM deployments based on Kubernetes
Deep-dive into cloud-native AEM deployments based on Kubernetes
 
Emulating Game Boy in Java
Emulating Game Boy in JavaEmulating Game Boy in Java
Emulating Game Boy in Java
 
Zero downtime deployments for the Sling-based apps using Docker
Zero downtime deployments for the Sling-based apps using DockerZero downtime deployments for the Sling-based apps using Docker
Zero downtime deployments for the Sling-based apps using Docker
 
CRX2Oak - all the secrets of repository migration
CRX2Oak - all the secrets of repository migrationCRX2Oak - all the secrets of repository migration
CRX2Oak - all the secrets of repository migration
 
Code metrics
Code metricsCode metrics
Code metrics
 
Inter-Sling communication with message queue
Inter-Sling communication with message queueInter-Sling communication with message queue
Inter-Sling communication with message queue
 
Sling Dynamic Include
Sling Dynamic IncludeSling Dynamic Include
Sling Dynamic Include
 
Shooting rabbits with sling
Shooting rabbits with slingShooting rabbits with sling
Shooting rabbits with sling
 

Último

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 

Último (20)

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 

SlingQuery

  • 1. CIRCUIT AN ADOBE DEVELOPER EVENT PRESENTED BY CITYTECH, INC. Use SlingQuery and walk the tree with ease Tomek Rękawek, Cognifide @TomaszRekawek
  • 2. Sling API Resource parent = myResource.getParent(); for (Resource child : parent.getChildren()) { if (child.adaptTo(ValueMap.class).containsKey("myProperty")) { //... } } efficient, especially for denormalized and well- structured content[1] easy to use but: a lot of while()s, iterators and nullchecks code complexity is growing fast [1] Efficient content structures and queries in CRX
  • 3. Sling example Find the first ancestor with a given template. String path = "/content/geometrixx/en/products/triangle/jcr:content/par"; String homeTemplate = "/apps/geometrixx/templates/homepage"; Resource resource = resourceResolver.getResource(path); while ((resource = resource.getParent()) != null) { if (!resource.isResourceType("cq:Page")) { continue; } ValueMap map = resource.adaptTo(ValueMap.class); String cqTemplate = map.get("jcr:content/cq:template"); if (homeTemplate.equals(cqTemplate)) { break; } } resource.getPath();
  • 4. SlingQuery example import static com.cognifide.sling.query.api.SlingQuery.$; Resource resource = getResource("/content/geometrixx/en/products/triangle/jcr:content/par"); $(resource) .closest("cq:Page[jcr:content/cq:template=/apps/geometrixx/templates/homepage]") $()is a valid method name in Java, it wraps resource(s) into an iterable SlingQuery collection each method transforms the existing collection into a new one API inspired by jQuery
  • 5. Get all text components from the parsys r = getResource("/content/geometrixx/en/jcr:content/rightpar/teaser") SlingQuery collection = $(r) .closest("cq:PageContent") .find("foundation/components/parsys#par") .children("foundation/components/text") for (Resource c : collection) { println c.path } each method returns new collection SlingQueryobject implements Iterable
  • 6. Breadcrumbs r = getResource("/content/geometrixx/en/products/mandelbrot/overview/jcr:content/par") Iterable<Page> breadcrumbs = $(r) .parents("cq:Page") .not("[jcr:content/hideInNav=true]") .map(Page.class) for (Page p : breadcrumbs) { println p.title } map()method creates a new Iterable<> adapting each resource to a given class resource.adaptTo(Page.class) approach compatible with Sling Models
  • 7. Selector string r = getResource("/content/geometrixx/en/products/mandelbrot") $(r) .children("cq:PageContent") .children("foundation/components/parsys") .children("#title[jcr:title=Best in class][type=large]:first") selector format resource type or node type #resource-name attributes in [] modifiers, each prepended by : all elements are optional
  • 8. Advanced selectors r = getResource("/content/geometrixx") $(r) .find("[text*=square]:not(cq:PageContent):first") .closest("cq:Page") .find("#title, #image, #par:parent") :not()accepts any valid selector :not(:not(:not(:first))) :parent- only resources having children there is a number of operators for square brackets alternatives can be separated with a comma
  • 9. Random image rnd = new java.util.Random() r = getResource("/content/dam/geometrixx/travel") $(r) .children("dam:Asset") .filter({ rnd.nextFloat() > 0.9 } as Predicate) .first() in Java it'd look like this: // ... .filter(new Predicate<Resource>() { @Override public boolean accepts(Resource resource) { return rnd.nextFloat() > 0.9; } });
  • 10. Siblings but not me r = getResource("/content/geometrixx/en/products/mandelbrot/jcr:content/par/image") myPage = $(r).closest("cq:Page") result = myPage .siblings("cq:Page") .not(myPage) the SlingQuery collection is immutable each method returns a new collection any Iterable<Resource>may be used as a filter
  • 11. Find all pages with given template $(resourceResolver) .find("cq:PageContent[cq:template=/apps/geometrixx/templates/homepage]") .parent() $(resourceResolver)creates a collection containing / find()iterates over the whole subtree
  • 12. Search strategy r = getResource("/content/geometrixx/en") result = $(r) .searchStrategy(DFS) .find("cq:Page") for (Resource c : result) { println c.path } strategies: DFS, BFS, QUERY QUERYtries to rewrite find()selector into JCR- SQL2 the result is filtered once more
  • 13. Find method vs JCR find()is powerful but may be dangerous it should be used only for small subtrees if you want to query a large space, use JCR-SQL[2] or XPath if your SlingQuery processes more than 100 resources, you'll get a warning in the logs: 28.05.2014 13:35:49.942 *WARN* [0:0:0:0:0:0:0:1 [1401276949857] POST /bin/groovy console/post.json HTTP/1.1] SlingQuery Number of processed resources exceeded 10 0. Consider using a JCR query instead of SlingQuery. More info here: http://git. io/h2HeUQ
  • 14. Laziness result = $(resourceResolver) .searchStrategy(DFS) .find() .slice(10, 20) result.toString() we don't query resources unless we need them invoking the SlingQuery method adds a new function to the chain functions are executed by the final iterator (like the one created by the for()loop) all functions are lazy expect the last()function
  • 15. Resources code & docs global Maven repository https://github.com/Cognifide/Sling-Query <dependency> <groupId>com.cognifide.cq</groupId> <artifactId>sling-query</artifactId> <version>1.4.4</version> </dependency>