Search code examples
javagroovysap-commerce-cloud

Possibilities to execute a groovy script with Hybris in java code (no hAC)


I'm wondering if there is a way to execute a groovy script with Hybris. I know how groovy scripts are executed with the Hybris Administration Console (hAC), but I need a solution to execute such a script from java code. Preferably with the Patching Framework's @SystemSetup but not necessary. (https://help.sap.com/docs/SAP_COMMERCE/d0224eca81e249cb821f2cdf45a82ace/5db22427a1d541669bc4d12793a7b672.html?locale=en-US)

I'm looking for a method similar to Impex import (eg. from core extension):

@SystemSetup(extension = SampleCoreConstants.EXTENSIONNAME)
public class CoreSystemSetup extends AbstractSystemSetup {

public static final String IMPORT_ACCESS_RIGHTS = "accessRights";

@SystemSetup(type = Type.ESSENTIAL, process = Process.ALL)
public void createEssentialData(final SystemSetupContext context)
{
    importImpexFile(context, "/samplecore/import/common/file-name.impex");
}

@Override
@SystemSetupParameterMethod
public List<SystemSetupParameter> getInitializationOptions()
{
    final List<SystemSetupParameter> params = new ArrayList<>();

    params.add(createBooleanSystemSetupParameter(IMPORT_ACCESS_RIGHTS, "Import Users & Groups", true));

    return params;
}

Here the same with SQL: https://www.stackextend.com/hybris/run-native-sql-query-hybris/

So anyone who can help me out with a solution (or with a clear answer if this is possible or not) are welcome.

Thanks!


Solution

  • It's possible to run groovy in your code. Even in SystemSetup.

    You can use the hybris service (spring bean) de.hybris.platform.scripting.engine.ScriptingLanguagesService that's available in the processing extension

    In the code, this could be something like

    final ClassPathResource resource = new ClassPathResource("location.groovy");
    final ResourceScriptContent content = new ResourceScriptContent(resource);
    
    ScriptExecutable groovyScript = scriptingLanguagesService.getExecutableByContent(content);
    
    ScriptExecutionResult result = groovyScript.execute();
    

    This will execute a script on the given location in your classpath. If you don't have your groovy in a file in your classpath, there are other Content types possible. For example: SimpleScriptContent