001package org.nuxeo.snapshot.listeners;
002
003import static org.nuxeo.ecm.core.api.event.DocumentEventTypes.DOCUMENT_UPDATED;
004
005import org.apache.commons.logging.Log;
006import org.apache.commons.logging.LogFactory;
007import org.nuxeo.ecm.core.api.DocumentModel;
008import org.nuxeo.ecm.core.api.NuxeoException;
009import org.nuxeo.ecm.core.api.VersioningOption;
010import org.nuxeo.ecm.core.event.Event;
011import org.nuxeo.ecm.core.event.EventListener;
012import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
013import org.nuxeo.snapshot.Snapshotable;
014
015/**
016 * Listener snapshoting documents with the {@link Snapshotable#FACET} facet if the property
017 * {@code snapshotVersioningOption} is set.
018 *
019 * @author <a href="mailto:troger@nuxeo.com">Thomas Roger</a>
020 * @since 5.7
021 */
022public class SnapshotableListener implements EventListener {
023
024    private static final Log log = LogFactory.getLog(SnapshotableListener.class);
025
026    public static final String SNAPSHOT_VERSIONING_OPTION_KEY = "snapshotVersioningOption";
027
028    @Override
029    public void handleEvent(Event event) {
030        String eventName = event.getName();
031        if (!DOCUMENT_UPDATED.equals(eventName)) {
032            return;
033        }
034
035        if (!(event.getContext() instanceof DocumentEventContext)) {
036            return;
037        }
038        DocumentEventContext ctx = (DocumentEventContext) event.getContext();
039        DocumentModel doc = ctx.getSourceDocument();
040        if (doc.isProxy() || doc.isVersion() || !doc.hasFacet(Snapshotable.FACET)) {
041            return;
042        }
043
044        String versioningOption = (String) ctx.getProperty(SNAPSHOT_VERSIONING_OPTION_KEY);
045        if (versioningOption == null) {
046            return;
047        }
048
049        VersioningOption option;
050        try {
051            option = VersioningOption.valueOf(versioningOption);
052        } catch (IllegalArgumentException e) {
053            log.error(String.format("Unknown versioning option value '%s': %s", versioningOption, e.getMessage()));
054            log.debug(e, e);
055            return;
056        }
057        if (option == VersioningOption.NONE) {
058            return;
059        }
060
061        try {
062            Snapshotable snapshotable = doc.getAdapter(Snapshotable.class);
063            snapshotable.createSnapshot(option);
064        } catch (NuxeoException e) {
065            event.markRollBack(e.getMessage(), e);
066            throw e;
067        }
068
069    }
070}