SlideShare una empresa de Scribd logo
1 de 17
Descargar para leer sin conexión
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!

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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...
 

Similar 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
 

Similar 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
 

Más 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
 

Más 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

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
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
 
%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
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile EnvironmentVictorSzoltysek
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park 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
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
%+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
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
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
 
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
 

Último (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
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
 
%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
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%+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...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%+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...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
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...
 
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...
 

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>