Determine runmode in Adobe CQ

22.1k Views Asked by At

How do I programmatically know which run-mode the instance is running? I created a custom tag that provides the config depending on the instance run-mode, but I can not determine the current run-mode.
I found a method that returns a list of run-mods instance:

SlingSettings settings = ...get from BundleContext...
Set<String> currentRunModes = settings.getRunModes();

But I can not get the objects SlingSettings or BundleContext. How can I get these objects or perhaps there is another way to get the current run-mode?

7

There are 7 best solutions below

0
On BEST ANSWER

SlingSetttings is the right way - If it's from Java the simplest way to get it is with an SCR @Reference annotation in a class that's an SCR @Component, saves you from having to go through BundleContext.

If it's from a Sling script, you can use sling.getService(....) to get the SlingSettings.

Note that the cases where you need to read the run modes are rare, usually you'd rather setup your OSGi configurations to depend on the run modes and have the OSGi components modify their behavior based on that.

2
On

You can also try this:

RunModeService runModeService = getSlingScriptHelper().getService(RunModeService.class);
author = runModeService.isActive("author");
0
On

Finally I decided to use global.jsp, write run-modes in the page context and get it in my class:

<%
pageContext.setAttribute("runModes", sling.getService(SlingSettingsService.class).getRunModes().toString());
%>
0
On
import java.util.Set;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import org.apache.sling.settings.SlingSettingsService;

public class myClass {
    public static Set<String> getRunModes() {
        BundleContext bundleContext = FrameworkUtil.getBundle(myClass.class).getBundleContext();
        ServiceReference serviceReference = bundleContext.getServiceReference(SlingSettingsService.class.getName( ));
        SlingSettingsService slingSettingsService = (SlingSettingsService)bundleContext.getService(serviceReference);
        return slingSettingsService.getRunModes();
    }
}
2
On

As Bertrand Delacretaz said it is the right way to check whether instance is Author or Publish. In jsp or java you could check like

import  org.apache.sling.settings.SlingSettingsService
Set<String> runModes = sling.getService(SlingSettingsService.class).getRunModes();

if (runModes.contains("author")) {
} 

Another way is using

if (mode == WCMMode.EDIT) 
{
}

But this approach will fail in case of Preview mode and wouldn't work.

0
On
@Reference
RunMode runmode;

or

sling.getService( RunMode.class )

and call

getCurrentRunModes(); //returns String[]
1
On

If you're using Sightly and working with a class that extends WCMUsePojo

slingSettings =this.getSlingScriptHelper().getService(SlingSettingsService.class);
    Set<String> runmodes = slingSettings.getRunModes();