rules Developer Jahia 7.3 Jahia 8 Legacy

Create my own rule consequence service class

Question

The Jahia pre-built rule consequence to execute an action on a node does not work with Publication but only with AddNode or deleteNode.
Example:

when
    A node is published
    - the node has the type nt:myNodeType
then
    Execute the action "actionName" now on the node

Cause

The current code returns the parent node instead of the actual node.

Solution

Create a service class to handle your own consequence:

package my.action.rule;

import org.drools.core.spi.KnowledgeHelper;
import org.jahia.registries.ServicesRegistry;
import org.jahia.services.content.rules.BackgroundAction;
import org.jahia.services.content.rules.NodeFact;
import org.jahia.services.content.rules.PublishedNodeFact;
import org.quartz.SchedulerException;

import javax.jcr.RepositoryException;

public class MyRuleService {

    private MyRuleService myRuleService;

    public void setMyRuleService(MyRuleService myRuleService) {
        this.myRuleService = myRuleService;
    }

    public void executeActionNow(NodeFact node, final String actionToExecute, KnowledgeHelper drools)
            throws SchedulerException, RepositoryException {
        final BackgroundAction action = ServicesRegistry.getInstance().getJahiaTemplateManagerService().getBackgroundActions().get(
                actionToExecute);
        if (action != null) {
            if (node instanceof PublishedNodeFact) {
                if (((PublishedNodeFact) node).getNode().getProperty("j:published").getBoolean()) {
                    action.executeBackgroundAction(((PublishedNodeFact) node).getNode());
                }
            }
        }
    }
}

Add this 2 beans in your spring configuration:

<bean id="myRuleService" class="my.action.rule.MyRuleService">
</bean>

<bean class="org.jahia.services.content.rules.ModuleGlobalObject">
<property name="globalRulesObject">
    <map>
        <entry key="myRuleService">
            <bean class="my.action.rule.MyRuleService">
                <property name="myRuleService" ref="myRuleService"/>
            </bean>
        </entry>
    </map>
</property>
</bean>

Under META-INF add a rule.dsl file for your consequence:
 

[consequence][]Execute this action {actionName} now on the {node}=myRuleService.executeActionNow(node,{actionName}, drools);