Created

Aug 05, 2013

Observation in JCR

Posted by Ugo Cei

Observation is a JCR mechanism that allows code to listen for events generated during repository operations and react to them in various ways. Two types of observation may be supported by a JCR repository: Asynchronous Observation and Journaled Observation. The former allows an application to react to events as they occur in real time, the latter to query the repository for a log of past events. Not all implementations of JCR are required to support one or both types of observation, but an application can query whether a repository supports using code like the following:

if (repository.getDescriptor(Repository.OPTION_OBSERVATION_SUPPORTED).equals("true"))

or

if (repository.getDescriptor(Repository.OPTION_JOURNALED_OBSERVATION_SUPPORTED).equals("true"))

The six type of events that can be detected are as follows:

  • Node added
  • Node moved
  • Node removed
  • Property added
  • Property removed
  • Property changed

A seventh event type, called "Persist", may also appear in certain circumstances related to Journaled Observation.

Notice that, even if observation is supported, your application code is not guaranteed to be able to be notified of all events and, even if it could, reacting to a large number of events might be impractical from a performance standpoint. As the JCR 2.0 specification says:

The scope of event reporting is implementation-dependent. An implementation should make a best-effort attempt to report all events, but may exclude events if reporting them would be impractical given implementation or resource limitations. For example, on an import, move or remove of a subgraph containing a large number of items, an implementation may choose to report only events associated with the root node of the affected graph and not those for every subitem in the structure.


Registering an event listener

An event listener is a class that implements the javax.jcr.observation.EvenListener interface. This interface declares one method that must be implemented by derived classes:

void onEvent(EventIterator it);

Notice that the argument to the onEvent method is an EventIterator (a subclass of RangeIterator that adds an extra Event nextEvent() method for convenience). This is because events are dispatched in bundles of related events, rather than as single events. A bundle corresponds to a single atomic change to a persistent workspace and contains only events caused by that change.

Listeners apply per workspace, not repository-wide; they only receive events for the workspace in which they are registered.

The implementation must then be registered with the ObservationManager by calling its addEventListener method, whose signature is as follows:

void addEventListener(EventListener listener,
                      int eventTypes,
                      java.lang.String absPath,
                      boolean isDeep,
                      java.lang.String[] uuid,
                      java.lang.String[] nodeTypeName,
                      boolean noLocal)


Let's have a look at the arguments for this method.

EventListener listener

This is an instance of a class implementing the EventListener interface, as explained above.

int eventTypes

This represents the set of events our listener is interested in, as a bitwise OR of the integer values of the constants defined in the Event interface for the various event types, which are:

Event.NODE_ADDED
Event.NODE_MOVED
Event.NODE_REMOVED
Event.PERSIST
Event.PROPERTY_ADDED
Event.PROPERTY_CHANGED
Event.PROPERTY_REMOVED


java.lang.String absPath

Only events associated with the node whose path is absPath (or its subgraph if isDeep is true) will trigger a notification.

boolean isDeep

If true, include descendants of the node pointed to by absPath in those being listened for events.

java.lang.String[] uuid

If not null, only listen for events relative to the nodes identified by the UUIDs contained in the array. You can pass null if you don't want to filter by node id, but be careful that passing an empty array will filter out all events.

java.lang.String[] nodeTypeName

If not null, only listen for events relative to the nodes whose type names are contained in the array. You can pass null if you don't want to filter by node type, but be careful that passing an empty array will filter out all events.

boolean noLocal

If true, ignore events generated by the session through which the listener was registered. Useful for avoiding infinite loops of event listeners triggering events themselves.

Typically, an event listener will be implemented as an OSGi component that registers itself when activated:

protected void activate(ComponentContext context) throws Exception {
    session = repository.loginAdministrative(null);
    observationManager = session.getWorkspace().getObservationManager();
    
    observationManager.addEventListener(this, Event.PROPERTY_ADDED | Event.PROPERTY_CHANGED, "/", true, null,
            null, true);
    LOGGER.info("********added JCR event listener");
}


Unregistering the event listener

The component should take care of unregistering itself when deactivated, in order to avoid memory leaks:

protected void deactivate(ComponentContext componentContext) {
    try {
        if (observationManager != null) {
            observationManager.removeEventListener(this);
            LOGGER.info("********removed JCR event listener");
        }
    }
    catch (RepositoryException re) {
        LOGGER.error("********error removing the JCR event listener", re);
    }
    finally {
        if (session != null) {
            session.logout();
            session = null;
        }
    }
}


Handling the event

The following sample illustrates an event handler that reacts to events of type PROPERTY_ADDED and PROPERTY_CHANGED on all nodes, as per the addEventListener call above and appends an exclamation mark to the end of the value of "jcr:title" properties. In this case, it is imperative that the value of the noLocal parameter to addEventListener be false, otherwise we would be triggering another property change event and would keep adding "!" to the title forever.

public void onEvent(EventIterator it) {
    while (it.hasNext()) {
        Event event = it.nextEvent();
        try {
            LOGGER.info("********new property event: {}", event.getPath());
            Property changedProperty = session.getProperty(event.getPath());
            if (changedProperty.getName().equalsIgnoreCase("jcr:title")
                    && !changedProperty.getString().endsWith("!")) {
                changedProperty.setValue(changedProperty.getString() + "!");
                session.save();
            }
        }
        catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }        
}


References

 

COMMENTS

  • By Cuci Sofa - 2:12 PM on Apr 04, 2014   Reply
    Thanks.
    • By Anonymous - 4:33 PM on Apr 04, 2014   Reply
      Nice information for<US>Today
      • By Paket Pernikahan - 4:26 AM on Apr 06, 2014   Reply
        i really to say nice tools from adobe. i like it.
        • By Paket Pernikahan - 4:34 AM on Apr 06, 2014   Reply
          i really to say nice tools from adobe. i like it.
          • By Paket Pernikahan - 4:36 AM on Apr 06, 2014   Reply
            i really to say nice tools from adobe. i like it.
            • By surf wallpaper - 9:57 AM on Apr 09, 2014   Reply
              Nice information. Thank you for sharing it with us!
              • By Short Layered Hairstyles - 4:43 PM on Apr 10, 2014   Reply
                Really great post, Thank you for sharing This knowledge.Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Please keep it up!
                • By pengertian kebugaran jasmani - 6:13 AM on Apr 15, 2014   Reply
                  i love this content
                  • By limo service nyc - 6:44 PM on Apr 18, 2014   Reply
                    JCR is something that I have been looking into for quite some time. It is something that a webinar could be useful for.
                  • By Jasa SEO - 3:50 AM on Apr 05, 2014   Reply
                    Many Thanks.
                    • By Cap Kaki Tiga Setia Manfaat - 3:08 PM on Apr 06, 2014   Reply
                      Thanks.
                      • By model mayhem - 4:37 PM on Apr 06, 2014   Reply
                        I surmise I have chosen an intelligent and mind blowing website with interesting material.
                        • By Harga Android - 5:13 PM on Apr 07, 2014   Reply
                          Many Thanks.
                          • Just saying thanks will not just be sufficient, for the fantasti c lucidity in your writing. I will instantly grab your rss feed to stay informed of any updates.
                            • By gclub casino - 5:11 PM on Apr 09, 2014   Reply
                              Events associated with the root node of the affected graph and not those for every subitem in the structure.
                              • By Low Rise Forming - 6:33 AM on Apr 10, 2014   Reply
                                he latter to query the repository for a log of past events. Not all implementations of JCR are required to support one or both types of observation, but an application can query whether a repository supports using code like the following:
                                • By Aymeric Roux - 7:59 AM on Apr 10, 2014   Reply
                                  thank's a lot verry nice !!!
                                  • By olivier Lefevre - 8:00 AM on Apr 10, 2014   Reply
                                    verry good job thank's to you !!!
                                    • By Pulau Seribu - 10:01 AM on Apr 10, 2014   Reply
                                      Many Thanks.
                                      • By Pakar SEO - 11:29 AM on Apr 10, 2014   Reply
                                        Thanks.
                                        • By Kajakk kurs - 6:40 AM on Apr 11, 2014   Reply
                                          verry good job thank's to you !!!
                                          • By Peluang Usaha Waralaba Loundry Kiloan - 9:29 AM on Apr 11, 2014   Reply
                                            Thanks.
                                                      • By adobe photoshop free download - 2:19 PM on Apr 11, 2014   Reply
                                                        I agree with your blog and i will be back to check it more in the future so please keep up your work. michael kors outleti love your content & the way that you write
                                                        • By skuldfri - 10:32 PM on Apr 11, 2014   Reply
                                                          Two types of observation may be supported by a JCR repository: Asynchronous Observation and Journaled Observation.
                                                          • By Strategi Pemasaran - 4:53 AM on Apr 12, 2014   Reply
                                                            Thanks.
                                                            • By Airul - 5:47 AM on Apr 12, 2014   Reply
                                                              Thanks.
                                                              • By Tidung - 6:25 AM on Apr 12, 2014   Reply
                                                                Thanks.
                                                                • By harga samsung galaxy tab - 2:32 PM on Apr 12, 2014   Reply
                                                                  Existing without the answers to the difficulties you’ve sorted out through this guide is a critical case, as well as the kind which could have badly affected my entire career if I had not discovered your web site.
                                                                  • By pregnancy miracle ebook - 5:35 AM on Apr 13, 2014   Reply
                                                                    that allows code to listen for events generated during repository operations and react to them in various ways.
                                                                    • By taruhan sbobet - 1:58 PM on Apr 13, 2014   Reply
                                                                      You can pass null if you don't want to filter by node id, but be careful that passing an empty array will filter out all events.
                                                                      • By cheap flowers delivered - 3:28 PM on Apr 13, 2014   Reply
                                                                        I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
                                                                        • By cheap flowers delivered - 3:29 PM on Apr 13, 2014   Reply
                                                                          I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
                                                                          • By honda lease offers - 11:16 PM on Apr 13, 2014   Reply
                                                                            Two types of observation may be supported by a JCR repository: Asynchronous Observation and Journaled Observation.
                                                                              • By flowers by post - 8:24 AM on Apr 14, 2014   Reply
                                                                                reporting is implementation-dependent. An implementation should make a best-effort attempt to report all events, but may
                                                                                • By sulfate free shampoo - 5:40 PM on Apr 14, 2014   Reply

                                                                                  Two types of observation may be supported by a JCR repository: Asynchronous Observation and Journaled Observation.
                                                                                  • By pusat grosir baju gamis - 8:28 AM on Apr 15, 2014   Reply
                                                                                    I wish to show thanks to you just for bailing me out of this particular trouble.As a result of checking through the the net and meeting techniques that were not productive, I was thinking my life was done.
                                                                                    • By sarkari naukri in mp - 1:21 PM on Apr 15, 2014   Reply
                                                                                      If true, ignore events generated by the session through which the listener was registered. Useful for avoiding infinite loops of event listeners triggering events themselves.
                                                                                      • By free online games for kids - 11:38 AM on Apr 16, 2014   Reply
                                                                                        The quondam acknowledges an petition to answer to facts as they betide in intrinsic era, the final to ask the warehouse for a record of former occasions.
                                                                                        • By easy Vegan Recipes - 7:24 PM on Apr 16, 2014   Reply
                                                                                          Thanks.
                                                                                          • By boost your bust - 8:32 AM on Apr 17, 2014   Reply
                                                                                            ignore events generated by the session through which the listener was registered. Useful for avoiding infinite loops of event listeners triggering events themselves.
                                                                                            • By pakistan flights - 10:16 AM on Apr 17, 2014   Reply
                                                                                              ignore events generated by the session through which the listener was registered. Useful for avoiding infinite loops of event listeners triggering events themselves.
                                                                                              • Fast Paleo Top 100 Of 2013: James Gregory And Ute Mitchell Reveal The Top 100 Paleo And Primal Recipes Of The Year Submitted By Caveman Diet Enthusiasts From Around The Globe... Written for consumers by a consumer, this fan site includes a fun and informative Fast Paleo Top 100 review, ebook FAQ, and PDF download guide that provides an insider's look at the program and answers frequently asked questions about James Gregory and Ute Mitchell's unique and highly popular paleo diet and recipe guide. Please visit site: https://www.rebelmouse.com/fastpaleotop100of2013reviews/ ...
                                                                                                • By custom home builders in savannah ga - 4:59 AM on Apr 18, 2014   Reply
                                                                                                  When you work with a custom home builder, owners will certainly also be able to keep track of the development of the new custom house. These luxury home builders allow as much or as little involvement as possible with Custom home builders in savannah GA. Please visit site: http://www.yelp.com/biz/custom-home-builder-savannah-savannah-2 ...
                                                                                                  • By 90 second fat loss review - 3:14 PM on Apr 19, 2014   Reply
                                                                                                    90 Second Fat Loss: Greg Palumbo And Dr. Frank Lawlis Reveal A Cutting-Edge "90 Second Fat Burning Trick" That Drops Pounds And Inches From All Your Stubborn Trouble Spots Quickly, Easily, And Permanently... Written for consumers by a consumer, this fan site includes a fun and informative 90 Second Fat Loss review, ebook FAQ, and PDF download guide that provides an insider's look at the program and answers frequently asked questions about Greg Palumbo and Dr. Frank Lawlis' unique and highly popular fat loss guide. Please visit site: https://www.rebelmouse.com/90secondfatlossreview/ ...
                                                                                                    • Perfect Vision Today: Dr. Sen And Samantha Pearson Reveal A Breakthrough, Step-By-Step System To Achieve 20/20 Vision And Help Cure Myopia, Hyperopia, Presbyopia, And Most Other Visual Problems In As Little As 2 Weeks... Written for consumers by a consumer, this fan site includes a fun and informative Perfect Vision Today review, ebook FAQ, and PDF download guide that provides an insider's look at the program and answers frequently asked questions about Dr. Sen and Samantha Pearson's unique and highly popular guide to better vision. Please visit site: https://www.rebelmouse.com/perfectvisiontodayreviews/ ...
                                                                                                      • By Injustice Gods Among Us Hack - 5:18 PM on Apr 19, 2014   Reply
                                                                                                        A wad coincides to a bachelor minute revision to a pertinacious workspace furthermore accommodates just tournaments caused by that diversify.
                                                                                                        • By cheap blog comment service - 9:32 PM on Apr 19, 2014   Reply
                                                                                                          EvenListener interface. This interface maintains person rule that requirement be implemented by derived classes:

                                                                                                          ADD A COMMENT