001/*
002 * (C) Copyright 2015-2018 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 *     <a href="mailto:grenard@nuxeo.com">Guillaume Renard</a>
018 *
019 */
020
021package org.nuxeo.ecm.platform.routing.core.listener;
022
023import org.apache.commons.lang3.StringUtils;
024import org.nuxeo.ecm.core.api.CoreSession;
025import org.nuxeo.ecm.core.api.DocumentModel;
026import org.nuxeo.ecm.core.api.IdRef;
027import org.nuxeo.ecm.core.api.event.DocumentEventTypes;
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.ecm.platform.routing.api.DocumentRoutingConstants;
032import org.nuxeo.ecm.platform.routing.core.impl.GraphNode;
033import org.nuxeo.ecm.platform.routing.core.impl.GraphRoute;
034import org.nuxeo.ecm.platform.task.Task;
035
036/**
037 * @since 7.4
038 */
039public class RoutingTaskDeletedListener implements EventListener {
040
041    @Override
042    public void handleEvent(Event event) {
043        if (!DocumentEventTypes.ABOUT_TO_REMOVE.equals(event.getName())) {
044            return;
045        }
046        DocumentEventContext docCtx;
047        if (event.getContext() instanceof DocumentEventContext) {
048            docCtx = (DocumentEventContext) event.getContext();
049        } else {
050            return;
051        }
052        DocumentModel doc = docCtx.getSourceDocument();
053        CoreSession session = docCtx.getCoreSession();
054        if (doc.hasFacet(DocumentRoutingConstants.ROUTING_TASK_FACET_NAME)) {
055            Task task = doc.getAdapter(Task.class);
056            String routeId = task.getProcessId();
057            IdRef routeIdRef = new IdRef(routeId);
058            if (StringUtils.isNotBlank(routeId) && session.exists(routeIdRef)) {
059                GraphRoute graphRoute = session.getDocument(routeIdRef).getAdapter(GraphRoute.class);
060                String nodeId = task.getVariable(DocumentRoutingConstants.TASK_NODE_ID_KEY);
061                if (StringUtils.isNotBlank(nodeId)) {
062                    GraphNode graphNode = graphRoute.getNode(nodeId);
063                    graphNode.removeTaskInfo(task.getId());
064                }
065            }
066
067        }
068    }
069
070}