= Logging Event Listener =

This example code shows how to implement an [[Event Listener>>http://code.xwiki.org/xwiki/bin/view/Modules/ObservationModule]] in Groovy that logs page updates in the ##Main.Logger## page.

{{velocity}}
{{html}}
#if ($request.confirm != "1")
<form method="get">
  <input type="hidden" name="confirm" value="1"/>
  <input type="submit" class="button" value="Register Event Listener"/>
</form>
#end
{{/html}}
{{/velocity}}

{{groovy}}
import org.xwiki.observation.*
import org.xwiki.observation.event.*
import com.xpn.xwiki.web.*
import com.xpn.xwiki.*
import org.xwiki.bridge.event.DocumentCreatingEvent

class OnDocumentCreationEventListener implements EventListener
{
    def xwiki
    def context
    def currentdoc

    OnDocumentCreationEventListener(xwiki, context, currentdoc)
    {
        this.xwiki = xwiki
        this.context = context
        this.currentdoc = currentdoc
    }

    String getName()
    {
        return "OnDocumentCreationEventListener"
    }

    List<Event> getEvents()
    {
        return Arrays.asList(new DocumentCreatingEvent())
    }

    void onEvent(Event event, Object source, Object data)
    {
        currentdoc.newObject("XWiki.RevisionClass")
        // Prevent infinite recursion
        if (source.fullName != "Main.Logger") {
            def document = xwiki.getDocument("Main.Logger")
            document.setContent("${document.getContent()}\n${source.fullName} has changed") // + "nb created object = " + nb_created_obj)
            document.save("Logging event", true)
        }
    }
}

// Only register the listener if the user has passed confirm=1 in the URL. This is to prevent
// from unintentially re-registering the listener against the observation manager.
if (request.confirm == "1") {
    // Register against the Observation Manager
    def observation = Utils.getComponent(ObservationManager.class)
    observation.removeListener("OnDocumentCreationEventListener")
    observation.removeListener("logging")
    def listener = new OnDocumentCreationEventListener(xwiki, xcontext, doc)
    observation.addListener(listener)
    println "{{info}}Listener is now registered {{/info}}"
}
{{/groovy}}

{{groovy}}
import org.xwiki.rendering.block.*

// Pretty print the first Groovy macro content.
println "{{code language=\"java\"}}${doc.getDocument().getXDOM().getChildrenByType(MacroBlock.class, true).get(1).getContent()}{{/code}}"
{{/groovy}}
