AemConfigurationInjectResourceDetectionStrategy.java

  1. /*
  2.  * #%L
  3.  * wcm.io
  4.  * %%
  5.  * Copyright (C) 2021 wcm.io
  6.  * %%
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  * you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at
  10.  *
  11.  *      http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  * Unless required by applicable law or agreed to in writing, software
  14.  * distributed under the License is distributed on an "AS IS" BASIS,
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  * See the License for the specific language governing permissions and
  17.  * limitations under the License.
  18.  * #L%
  19.  */
  20. package io.wcm.caconfig.extensions.bindings.impl;

  21. import org.apache.sling.api.SlingHttpServletRequest;
  22. import org.apache.sling.api.resource.Resource;
  23. import org.apache.sling.caconfig.spi.ConfigurationInjectResourceDetectionStrategy;
  24. import org.jetbrains.annotations.NotNull;
  25. import org.jetbrains.annotations.Nullable;
  26. import org.osgi.service.component.annotations.Component;
  27. import org.osgi.service.component.propertytypes.ServiceRanking;

  28. import com.day.cq.wcm.api.Page;
  29. import com.day.cq.wcm.api.components.ComponentContext;
  30. import com.day.cq.wcm.commons.WCMUtils;

  31. /**
  32.  * AEM-specific implementation of {@link ConfigurationInjectResourceDetectionStrategy}.
  33.  * It detects if the current request is attached to an AEM page, and uses the resource of that page
  34.  * for resolving the context-aware configurations.
  35.  * With this, it works also for structure components in editable templates, which are technically located below /conf.
  36.  */
  37. @Component(service = ConfigurationInjectResourceDetectionStrategy.class)
  38. @ServiceRanking(1000)
  39. public class AemConfigurationInjectResourceDetectionStrategy implements ConfigurationInjectResourceDetectionStrategy {

  40.   @Override
  41.   public @Nullable Resource detectResource(@NotNull SlingHttpServletRequest request) {
  42.     Page currentPage = getCurrentPage(request);
  43.     if (currentPage != null) {
  44.       return currentPage.adaptTo(Resource.class);
  45.     }
  46.     return null;
  47.   }

  48.   private @Nullable Page getCurrentPage(@NotNull SlingHttpServletRequest request) {
  49.     ComponentContext componentContext = WCMUtils.getComponentContext(request);
  50.     if (componentContext != null) {
  51.       return componentContext.getPage();
  52.     }
  53.     return null;
  54.   }

  55. }