001/*
002 * (C) Copyright 2013 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.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 *     Mariana Cedica
016 */
017package org.nuxeo.ecm.platform.routing.core.listener;
018
019import java.util.List;
020
021import org.nuxeo.ecm.core.api.CoreSession;
022import org.nuxeo.ecm.core.api.DocumentModel;
023import org.nuxeo.ecm.core.event.Event;
024import org.nuxeo.ecm.core.event.EventListener;
025import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
026import org.nuxeo.ecm.platform.routing.api.DocumentRoutingConstants;
027import org.nuxeo.ecm.platform.routing.api.DocumentRoutingService;
028import org.nuxeo.ecm.platform.task.Task;
029import org.nuxeo.ecm.platform.task.TaskService;
030import org.nuxeo.runtime.api.Framework;
031
032/**
033 * Cancels any remaining open tasks created by this workflow when this workflow is done
034 *
035 * @since 5.7.3
036 */
037public class DocumentRoutingWorkflowDoneListener implements EventListener {
038
039    private DocumentRoutingService routingService;
040
041    @Override
042    public void handleEvent(Event event) {
043        if (!DocumentRoutingConstants.Events.afterRouteFinish.name().equals(event.getName())) {
044            return;
045        }
046        DocumentEventContext docCtx = (DocumentEventContext) event.getContext();
047        CoreSession session = docCtx.getCoreSession();
048        DocumentModel routeInstanceDoc = docCtx.getSourceDocument();
049
050        List<Task> openTasks = Framework.getLocalService(TaskService.class).getAllTaskInstances(
051                routeInstanceDoc.getId(), session);
052        for (Task task : openTasks) {
053            getDocumentRoutingService().cancelTask(session, task.getId());
054        }
055    }
056
057    protected DocumentRoutingService getDocumentRoutingService() {
058        if (routingService == null) {
059            routingService = Framework.getLocalService(DocumentRoutingService.class);
060        }
061        return routingService;
062    }
063}