001/*
002 * (C) Copyright 2017 Nuxeo (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 *     Funsho David
018 *
019 */
020
021package org.nuxeo.ecm.platform.tag;
022
023import static org.nuxeo.ecm.platform.tag.TagService.Feature.TAGS_BELONG_TO_DOCUMENT;
024
025import org.nuxeo.ecm.core.api.CoreSession;
026import org.nuxeo.ecm.core.api.DocumentModel;
027import org.nuxeo.ecm.core.api.DocumentRef;
028import org.nuxeo.ecm.core.api.IdRef;
029import org.nuxeo.ecm.core.event.DeletedDocumentModel;
030import org.nuxeo.ecm.core.event.Event;
031import org.nuxeo.ecm.core.event.EventContext;
032import org.nuxeo.ecm.core.event.EventListener;
033import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
034import org.nuxeo.runtime.api.Framework;
035
036/**
037 * Listener that copy tags applied on the live document to a version synchronously after the check-in event.
038 *
039 * @since 9.3
040 */
041public class CheckedInDocumentListener implements EventListener {
042
043    @Override
044    public void handleEvent(Event event) {
045        EventContext ctx = event.getContext();
046        if (ctx instanceof DocumentEventContext) {
047            DocumentEventContext docCtx = (DocumentEventContext) ctx;
048            CoreSession session = docCtx.getCoreSession();
049            DocumentModel doc = docCtx.getSourceDocument();
050            if (doc == null) {
051                return;
052            }
053            String docId = doc.getId();
054            TagService tagService = Framework.getService(TagService.class);
055            if (doc instanceof DeletedDocumentModel) {
056                tagService.removeTags(session, docId);
057                return;
058            }
059            DocumentRef versionRef = (DocumentRef) ctx.getProperty("checkedInVersionRef");
060            if (!tagService.hasFeature(TAGS_BELONG_TO_DOCUMENT)) {
061                if (versionRef instanceof IdRef) {
062                    tagService.copyTags(session, docId, versionRef.toString());
063                }
064            }
065        }
066    }
067}