001/*
002 * (C) Copyright 2015 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 *     <a href="mailto:grenard@nuxeo.com">Guillaume</a>
018 */
019package org.nuxeo.ecm.collections.core.listener;
020
021import org.apache.commons.logging.Log;
022import org.apache.commons.logging.LogFactory;
023import org.nuxeo.ecm.collections.api.CollectionManager;
024import org.nuxeo.ecm.core.api.DocumentModel;
025import org.nuxeo.ecm.core.api.IdRef;
026import org.nuxeo.ecm.core.api.event.DocumentEventTypes;
027import org.nuxeo.ecm.core.api.facet.VersioningDocument;
028import org.nuxeo.ecm.core.event.Event;
029import org.nuxeo.ecm.core.event.EventContext;
030import org.nuxeo.ecm.core.event.EventListener;
031import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
032import org.nuxeo.runtime.api.Framework;
033
034/**
035 * Event handler to restored the collection members of a restored version of a collection.
036 *
037 * @since 7.3
038 */
039public class RestoredCollectionListener implements EventListener {
040
041    private static final Log log = LogFactory.getLog(RestoredCollectionListener.class);
042
043    @Override
044    public void handleEvent(Event event) {
045        EventContext ctx = event.getContext();
046        if (!(ctx instanceof DocumentEventContext)) {
047            return;
048        }
049
050        final String eventId = event.getName();
051
052        final DocumentEventContext docCxt = (DocumentEventContext) event.getContext();
053        final CollectionManager collectionManager = Framework.getService(CollectionManager.class);
054
055        DocumentModel doc = null;
056        DocumentModel version = null;
057        if (eventId.equals(DocumentEventTypes.BEFORE_DOC_RESTORE)) {
058            doc = docCxt.getSourceDocument();
059            final String versionRefId = (String) docCxt.getProperties().get(
060                    VersioningDocument.RESTORED_VERSION_UUID_KEY);
061            version = docCxt.getCoreSession().getDocument(new IdRef(versionRefId));
062            if (!collectionManager.isCollection(doc)) {
063                return;
064            }
065        } else {
066            return;
067        }
068
069        log.trace(String.format("Collection %s restored", doc.getId()));
070
071        collectionManager.processRestoredCollection(doc, version);
072
073    }
074
075}