Blogs

Blogs

OSGI - Force bundle refresh

When you write a custom Impl with higher Service Ranking

You've just written some custom implementation for a Liferay Service but your implementation is not picked from inside of the bundle that should use it despite the higher service ranking.

@Component(
        immediate = true,
        property = {
                "service.ranking:Integer=100"
        },
        service = AssetPublisherHelper.class
    )
public class CustomAssetPublisherHelperImpl implements AssetPublisherHelper {
    [Some code...]
}

There is a chance that the @Component that is doing @Reference on AssetPublisherHelper is applying a lazy policy.

Good news, you can ask the bundle that contains that @Component to refresh itself.
This is how you do that.

Add this piece of code to your custom @Component:

    @Activate
    @Modified
    public void activate(BundleContext bundleContext) {
        Bundle[] bundles = bundleContext.getBundles();
        
        List<Bundle> bundlesToRefresh = new ArrayList<Bundle>();
        
        for(int i = 0; i < bundles.length; i++) {
            Bundle bundle = bundles[i];
            if("com.liferay.asset.publisher.web".equals(bundle.getSymbolicName())) {
                LOG.info("Refreshing bundle {}", bundle.getSymbolicName());
                bundlesToRefresh.add(bundle);
            }
        }

        bundles[0].adapt(FrameworkWiring.class).refreshBundles(bundlesToRefresh);
    }

In my example, com.liferay.asset.publisher.web is the symbolic name of the bundle I need to refresh as soon as I provide my custom service implementation.

And voilà ! Now have a look at your logs when you deploy your component:

2021-02-10 08:19:49.715 INFO  [com.liferay.portal.kernel.deploy.auto.AutoDeployScanner][AutoDeployDir:271] Processing my.categories.filter-1.0.0.jar
2021-02-10 08:19:57.452 INFO  [fileinstall-directory-watcher][BundleStartStopLogger:49] STOPPED my.categories.filter_1.0.0 [4154]
2021-02-10 08:19:57.620 INFO  [Refresh Thread: Equinox Container: 112a69e0-cd8c-450b-9688-1fc43e9a5d06][BundleStartStopLogger:46] STARTED my.categories.filter_1.0.0 [4154]
2021-02-10 08:19:57.625 INFO  [Refresh Thread: Equinox Container: 112a69e0-cd8c-450b-9688-1fc43e9a5d06][AssetPublisherPortletFilter:197] Refreshing bundle com.liferay.asset.publisher.web
2021-02-10 08:19:57.815 INFO  [Refresh Thread: Equinox Container: 112a69e0-cd8c-450b-9688-1fc43e9a5d06][BundleStartStopLogger:49] STOPPED com.liferay.asset.publisher.web_4.0.41 [2708]
2021-02-10 08:19:58.073 INFO  [Refresh Thread: Equinox Container: 112a69e0-cd8c-450b-9688-1fc43e9a5d06][BundleStartStopLogger:46] STARTED com.liferay.asset.publisher.web_4.0.41 [2708]