Search code examples
javaaemquery-builder

How to get all the assets in a Collection in AEM?


I am trying to get all the assets inside a collection in AEM given the path of the collection.

Let's say the path of the collection is /content/dam/collections/public/-/-XZMzZlhkJKIa7-Mg15h/testing

I need to get all the assets inside this collection.

I checked under content/dam/collections the assets are not stored under this location

I even tried by writing a query in query builder in AEM giving type:dam:asset and path:"location of the collection"

I couldn't get any results.

I just need to get all the assets under the collection in Java or QueryBuilder


Solution

  • Resource Collection API will be used to retrieve the assets in a Collection.

    Below code should work for you.

    Resource resource = resourceResolver
                .getResource("/content/dam/collections/k/kXjI0j44sW4pq2mWc9fE/public collections");
        if (null != resource) {
            log.debug("resource path is {}", resource.getPath());
            ResourceCollection resourceCollection = resource.adaptTo(ResourceCollection.class);
            if (null != resourceCollection) {
                Iterator<Resource> resourceIterator = resourceCollection.getResources();
                while (resourceIterator.hasNext()) {
                    Resource damResource = resourceIterator.next();
                    log.debug("damResource path is {}", damResource.getPath());
                    imagePaths.add(damResource.getPath());
                }
            }
        }
    

    Refer below links for the model class and a sample Component

    https://github.com/sudheerdvn/aem-flash/blob/develop/core/src/main/java/com/flash/aem/core/models/ReadCollectionAssets.java

    https://github.com/sudheerdvn/aem-flash/tree/develop/ui.apps/src/main/content/jcr_root/apps/aem-flash/components/content/read-collection-assets