001/* 002 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Thomas Roger 018 */ 019package org.nuxeo.snapshot.listeners; 020 021import static org.nuxeo.ecm.core.api.event.DocumentEventTypes.DOCUMENT_UPDATED; 022 023import org.apache.commons.logging.Log; 024import org.apache.commons.logging.LogFactory; 025import org.nuxeo.ecm.core.api.DocumentModel; 026import org.nuxeo.ecm.core.api.NuxeoException; 027import org.nuxeo.ecm.core.api.VersioningOption; 028import org.nuxeo.ecm.core.event.Event; 029import org.nuxeo.ecm.core.event.EventListener; 030import org.nuxeo.ecm.core.event.impl.DocumentEventContext; 031import org.nuxeo.snapshot.Snapshotable; 032 033/** 034 * Listener snapshoting documents with the {@link Snapshotable#FACET} facet if the property 035 * {@code snapshotVersioningOption} is set. 036 * 037 * @author <a href="mailto:troger@nuxeo.com">Thomas Roger</a> 038 * @since 5.7 039 */ 040public class SnapshotableListener implements EventListener { 041 042 private static final Log log = LogFactory.getLog(SnapshotableListener.class); 043 044 public static final String SNAPSHOT_VERSIONING_OPTION_KEY = "snapshotVersioningOption"; 045 046 @Override 047 public void handleEvent(Event event) { 048 String eventName = event.getName(); 049 if (!DOCUMENT_UPDATED.equals(eventName)) { 050 return; 051 } 052 053 if (!(event.getContext() instanceof DocumentEventContext)) { 054 return; 055 } 056 DocumentEventContext ctx = (DocumentEventContext) event.getContext(); 057 DocumentModel doc = ctx.getSourceDocument(); 058 if (doc.isProxy() || doc.isVersion() || !doc.hasFacet(Snapshotable.FACET)) { 059 return; 060 } 061 062 String versioningOption = (String) ctx.getProperty(SNAPSHOT_VERSIONING_OPTION_KEY); 063 if (versioningOption == null) { 064 return; 065 } 066 067 VersioningOption option; 068 try { 069 option = VersioningOption.valueOf(versioningOption); 070 } catch (IllegalArgumentException e) { 071 log.error(String.format("Unknown versioning option value '%s': %s", versioningOption, e.getMessage())); 072 log.debug(e, e); 073 return; 074 } 075 if (option == VersioningOption.NONE) { 076 return; 077 } 078 079 try { 080 Snapshotable snapshotable = doc.getAdapter(Snapshotable.class); 081 snapshotable.createSnapshot(option); 082 } catch (NuxeoException e) { 083 event.markRollBack(e.getMessage(), e); 084 throw e; 085 } 086 087 } 088}