"Correct" way to lookup Cloud Service Configurations from Java in AEM 6
Asked Answered
S

0

6

AEM's Cloud Services API isn't terribly well documented, and provides a number of somewhat awkward to use methods that can be used to find a given Configuration from a resource. Below are a few examples I've found "in the wild" that do this.

Method 1: Getting all Configurations and iterating them until a named config is found:

public static Configuration findConfiguration(ConfigurationManager configurationManager, Resource resource, String serviceName) {
    Iterator configurations = configurationManager.getConfigurations(resource);
    while (configurations.hasNext()) {
        Configuration configuration = (Configuration) configurations.next();
        if (serviceName.equals(configuration.get("cq:cloudservicename", ""))) {
            return configuration;
        }
    }
    return null;
}

Method 2: Lookup all the cq:cloudserviceconfigs that apply to the resource and ask for the one you want:

public static Configuration findConfiguration(ConfigurationManager configurationManager, Resource resource, String serviceName) {
    HierarchyNodeInheritanceValueMap pageProperties = 
        new HierarchyNodeInheritanceValueMap(resource);

    String[] allServices = 
        pageProperties.getInherited("cq:cloudserviceconfigs", new String[0]);

    return configurationManager.getConfiguration(serviceName, allServices);
}

Method 3: Similar to method 2, but looks like it'll only work if the requested config is also defined on the first parent that has a cq:cloudserviceconfigs property?

public static Configuration findConfiguration(ConfigurationManager configurationManager, Resource resource, String serviceName) {

    Resource configurationResource = 
        configurationManager.getConfigurationResource(resource);

    if (configurationResource != null) {
        String[] cloudServiceConfigs = configurationResource.adaptTo(Page.class)
            .getProperties().get("cq:cloudserviceconfigs", String[].class);

        if (cloudServiceConfigs != null && cloudServiceConfigs.length > 0) {
            return configurationManager.getConfiguration(serviceName, cloudServiceConfigs);
        }
    }
    return null;
}

I find it odd that whoever designed this interface didn't simply add a method like Configuration ConfigurationManager#getService(Resource resource, String serviceName) - the hoops you have to jump through to achieve what seems like a common use case are frustrating, but that's how it is apparently.

So my question is this:

  1. Is there a better API or library to use than ConfigurationManager for looking up a specific cloud service config for a page or resource?

  2. If not, what is good, robust, performant way of using ConfigurationManager to do this?

Thanks.

Santosantonica answered 9/4, 2016 at 11:19 Comment(1)
from adobe's own code, method2 seems to be standard way of doing it.Apotheosize

© 2022 - 2024 — McMap. All rights reserved.