001/*
002 * (C) Copyright 2014 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.event.Event;
026import org.nuxeo.ecm.core.event.EventContext;
027import org.nuxeo.ecm.core.event.EventListener;
028import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
029import org.nuxeo.runtime.api.Framework;
030
031/**
032 * Synchronous event handler to update Collection of a removed CollectiomMember and CollectionMember of a Collection by
033 * scheduling an asynchronous work.
034 *
035 * @since 5.9.3
036 */
037public class RemovedCollectionListener implements EventListener {
038
039    private static final Log log = LogFactory.getLog(RemovedCollectionListener.class);
040
041    @Override
042    public void handleEvent(Event event) {
043
044        final EventContext ctx = event.getContext();
045        if (!(ctx instanceof DocumentEventContext)) {
046            return;
047        }
048
049        final DocumentModel doc = ((DocumentEventContext) ctx).getSourceDocument();
050
051        final CollectionManager collectionManager = Framework.getService(CollectionManager.class);
052
053        final boolean isCollectionRemoved = collectionManager.isCollection(doc);
054        final boolean isCollectionMemberRemoved = collectionManager.isCollected(doc);
055
056        if (isCollectionRemoved) {
057            log.trace(String.format("Collection %s removed", doc.getId()));
058            collectionManager.processRemovedCollection(doc);
059        } else if (isCollectionMemberRemoved) {
060            log.trace(String.format("CollectionMember %s removed", doc.getId()));
061            collectionManager.processRemovedCollectionMember(doc);
062        }
063    }
064
065}