Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ResourceTree iterate all resources in a tree
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.apache.sling.api.resource.Resource;
public class ResourceTree {
private Resource root;
public static Stream<ResourceTree> stream(Resource resource) {
return new ResourceTree(resource).streamTree();
}
public static Stream<ResourceTree> stream(Resource resource, String filterType) {
return new ResourceTree(resource).streamTree(filterType);
}
private ResourceTree(Resource root) {
this.root = root;
}
public Resource getResource() {
return root;
}
private Stream<ResourceTree> streamTree() {
return Stream.concat(Stream.of(this), StreamSupport.stream(root.getChildren().spliterator(), false)
.map(ResourceTree::new).flatMap(ResourceTree::streamTree));
}
private Stream<ResourceTree> streamTree(String filterType) {
return Stream.concat(Stream.of(this),
StreamSupport.stream(root.getChildren().spliterator(), false)
.filter(c -> filterType.equals(c.getResourceType())).map(ResourceTree::new)
.flatMap(rt -> rt.streamTree(filterType)));
}
}
/*
Usage
for example to find all of the includes in a dialog:
ResourceTree.stream(dialog).map(ResourceTree::getResource)
.filter(r -> r.getResourceType().equals("granite/ui/components/coral/foundation/include"))
.map(i -> component.getResourceResolver().getResource(i.getValueMap().get("path", "")))
.forEach(r -> addDialogFields(r, fields));
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.