Wednesday, March 25, 2020

AEM6 | Enable component programmatically

Problem:

An OSGi component is disabled by default, need to enable it programmatically in AEM6.x.

Solution:

Use SCR API to enable it. Sample code here:
for (Bundle bundle : bundleContext.getBundles()) {
    ComponentDescriptionDTO dto = scr.getComponentDescriptionDTO(bundle, componentName);
    if (dto != null && !scr.isComponentEnabled(dto)) {
        LOGGER.info("Component {} disabled by configuration.", dto.implementationClass);
        scr.enableComponent(dto);
    }
}
Complete code can be found here:
package com.vivek.sample.components;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.runtime.ServiceComponentRuntime;
import org.osgi.service.component.runtime.dto.ComponentDescriptionDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Sample code to enable component programmatically
*
* @author Vivek
*/
@Component(immediate = true, service = EnableComponent.class)
public class EnableComponent {
/**
* Logger
*/
private static final Logger LOGGER = LoggerFactory.getLogger(EnableComponent.class);
/**
* SCR
*/
@Reference
private ServiceComponentRuntime scr;
/**
* Bundle context
*/
private BundleContext bundleContext;
/**
* Enable component
*
* @param componentName name
*/
private void enableComponent(final String componentName) {
for (Bundle bundle : bundleContext.getBundles()) {
ComponentDescriptionDTO dto = scr.getComponentDescriptionDTO(bundle, componentName);
if (dto != null && !scr.isComponentEnabled(dto)) {
LOGGER.info("Component {} disabled by configuration.", dto.implementationClass);
scr.enableComponent(dto);
}
}
}
/**
* Activate method
*
* @param context context
*/
@Activate
public final void activate(final BundleContext context) {
this.bundleContext = context;
enableComponent("com.day.cq.dam.core.impl.MissingMetadataNotificationJob");
}
}

Use Case:

Sample use case is to enable "com.day.cq.dam.core.impl.MissingMetadataNotificationJob" component in https://helpx.adobe.com/experience-manager/6-3/assets/using/metadata-schemas.html#Definemandatorymetadata

No comments:

Post a Comment

CDN | Clearing Cloudflare cache

In order to clear Cloudflare cache automatically via code, follow below steps: 1. Develop Custom TransportHandler Develop a custom Trans...