Respond to a Page Copy Event
Introduction
Goal
Extend the page copy process with additional custom behavior.
Summary
CMS users can copy pages within the channel manager. Before processing a page copy the delivery tier sends an event to its internal event bus, enabling developers to extend the process with additional custom behavior.
Extend the Page Copy Process
When the delivery tier (HST) processes a page copy instruction, it copies a set of configuration nodes below /hst:myproject in the repository. Before persisting these changes, a PageCopyEvent is sent to the synchronous HST internal event bus. Developers can create a Listener for this PageCopyEvent and add custom behavior to the page copy (like invoking some workflow on some content, sending an event to a message bus, removing an experiment that was running on the source page, etc). The PageCopyEvent is extra useful when a page is copied to a different channel and you also want the content for the page to be copied over to the other channel (see below). Through the PageCopyEvent a developer can also abort the entire copy page action.
Because the code in the HST that posts the event also handles the persistence of the session changes at the end, a developer should never save the JCR session that can be accessed via
pageCopyEvent.getPageCopyContext().getRequestContext().getSession();
or
event.getPageCopyContext().getNewSiteMapItemNode().getSession()
Create a Custom Listener for a PageCopyEvent
The boilerplate code for a custom listener for PageCopyEvent looks like this:
package com.example.pagecopy; import org.hippoecm.hst.pagecomposer.jaxrs.api.ChannelEventListenerRegistry; import org.hippoecm.hst.pagecomposer.jaxrs.api.PageCopyEvent; import org.onehippo.cms7.services.eventbus.Subscribe; public class PageCopyEventListener { @SuppressWarnings("UnusedDeclaration") public void init() { ChannelEventListenerRegistry.get().register(this); } @SuppressWarnings("UnusedDeclaration") public void destroy() { ChannelEventListenerRegistry.get().unregister(this); } @Subscribe public void onPageCopyEvent(PageCopyEvent event) { if (event.getException() != null) { return; } // DO YOUR STUFF BUT MAKE SURE TO NEVER // SAVE THE JCR SESSION FOR THAT IS ACCESSIBLE VIA // THE PageCopyEvent#getPageCopyContext#getRequestContext } }
The last step is to make sure your PageCopyEventListener is initialized as a Spring bean: Add a spring xml configuration bean as follows:
<bean class="com.example.pagecopy.PageCopyEventListener" init-method="init" destroy-method="destroy"/>
Now, whenever a webmaster copies a page via the Page Settings, the above PageCopyEventListener#onPageCopyEvent is invoked before any changes are persisted into the repository.
Abort Page Copy with the PageCopyEvent
A listener for page copy events can abort a page copy action by setting an exception on the event object. This can be useful in case some requirement is not met or the post-processing fails. See Abort a Channel Manager Action for details.