Search code examples
workflowaemauthor

AEM - Custom workflow with Author content validation ?


How to write AEM - Custom workflow with Author content validation ?

eg: I want to validate Author HTML content while doing page activation. I want to check all Hyperlinks in Author content, based on specific link fail the workflow or pass the workflow for activation.


Solution

  • The AEM Workflow documentation is very helpful on this subject. You will need to create service that implements the WorkflowProcess interface. Once that is done, you can create a new workflow at http://localhost:4502/workflow or you can update the default activation workflow at http://localhost:4502/cf#/etc/workflow/models/request_for_activation.html. Drop in a new Process Step, set the Advance Handler to true and the Process to your service. Don't forget to hit the Save button.

    In your service, you have access to the Session and thus the Resource Resolver as well as the path to the activated resource. That's all you need to get the resource and run your custom code against its properties. If your custom validation comes back false, you can terminate the workflow by using wfsession.terminateWorkflow(item.getWorkflow()), otherwise the workflow will continue because you set it to auto advance.

    This is a rough outline for your workflow process step:

    @Component
    @Service
    @Properties({
        @Property(name = Constants.SERVICE_DESCRIPTION, value = "Workflow step description"),
        @Property(name = Constants.SERVICE_VENDOR, value = "Company Name"),
        @Property(name = "process.label", value = "Process Label will show in the workflow dropdown") })
    public class MyCustomStep implements WorkflowProcess {
    
        public void execute(WorkItem item, WorkflowSession wfsession, MetaDataMap args) throws WorkflowException {
            ResourceResolver resolver = wfsession.adaptTo(ResourceResolver.class);
    
            if (resolver != null) {
                // Get the payload: the activated resource
                String path = item.getWorkflowData().getPayload().toString();
    
                Resource resource = resolver.getResource(path);
    
                if (resource != null) {
                    ValueMap properties = resource.adaptTo(ValueMap.class);
                    String propertyToCheck = properties.get("myPropertyName", String.class);
    
                    if (!customValidationMethod(propertyToCheck)) {
                        // Terminate workflow
                        wfsession.terminateWorkflow(item.getWorkflow());
                    }
                }
            }
        }
    }