001/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     <a href="mailto:grenard@nuxeo.com">Guillaume Renard</a>
016 *
017 */
018
019package org.nuxeo.ecm.platform.routing.core.listener;
020
021import org.apache.commons.lang.StringUtils;
022import org.nuxeo.ecm.core.api.CoreSession;
023import org.nuxeo.ecm.core.api.DocumentModel;
024import org.nuxeo.ecm.core.api.IdRef;
025import org.nuxeo.ecm.core.api.event.DocumentEventTypes;
026import org.nuxeo.ecm.core.event.Event;
027import org.nuxeo.ecm.core.event.EventListener;
028import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
029import org.nuxeo.ecm.platform.routing.api.DocumentRoutingConstants;
030import org.nuxeo.ecm.platform.routing.core.impl.GraphNode;
031import org.nuxeo.ecm.platform.routing.core.impl.GraphRoute;
032import org.nuxeo.ecm.platform.task.Task;
033
034/**
035 * @since 7.4
036 */
037public class RoutingTaskDeletedListener implements EventListener {
038
039    @Override
040    public void handleEvent(Event event) {
041        if (!DocumentEventTypes.ABOUT_TO_REMOVE.equals(event.getName())) {
042            return;
043        }
044        DocumentEventContext docCtx;
045        if (event.getContext() instanceof DocumentEventContext) {
046            docCtx = (DocumentEventContext) event.getContext();
047        } else {
048            return;
049        }
050        DocumentModel doc = docCtx.getSourceDocument();
051        CoreSession session = docCtx.getCoreSession();
052        if (doc.hasFacet(DocumentRoutingConstants.ROUTING_TASK_FACET_NAME)) {
053            Task task = doc.getAdapter(Task.class);
054            String routeId = task.getProcessId();
055            IdRef routeIdRef = new IdRef(routeId);
056            if (StringUtils.isNotBlank(routeId) && session.exists(routeIdRef)) {
057                GraphRoute graphRoute = session.getDocument(routeIdRef).getAdapter(GraphRoute.class);
058                String nodeId = task.getVariable(DocumentRoutingConstants.TASK_NODE_ID_KEY);
059                if (StringUtils.isNotBlank(nodeId)) {
060                    GraphNode graphNode = graphRoute.getNode(nodeId);
061                    graphNode.removeTaskInfo(task.getId());
062                }
063            }
064
065        }
066    }
067
068}