001/*
002 * (C) Copyright 2009 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 *     arussel
016 */
017package org.nuxeo.ecm.platform.task.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.api.NuxeoPrincipal;
024import org.nuxeo.ecm.core.api.event.DocumentEventTypes;
025import org.nuxeo.ecm.core.event.Event;
026import org.nuxeo.ecm.core.event.EventListener;
027import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
028import org.nuxeo.ecm.platform.task.Task;
029import org.nuxeo.ecm.platform.task.TaskService;
030import org.nuxeo.runtime.api.Framework;
031
032/**
033 * Listener that deletes deletes related tasks of the document.
034 *
035 * @author arussel
036 * @since 5.5
037 */
038public class DeleteTaskForDeletedDocumentListener implements EventListener {
039
040    private TaskService taskService;
041
042    public TaskService getTaskService() {
043        if (taskService == null) {
044            taskService = Framework.getService(TaskService.class);
045        }
046        return taskService;
047    }
048
049    @Override
050    public void handleEvent(Event event) {
051        if (DocumentEventTypes.ABOUT_TO_REMOVE.equals(event.getName())) {
052            DocumentEventContext context = (DocumentEventContext) event.getContext();
053            DocumentModel dm = context.getSourceDocument();
054            CoreSession coreSession = context.getCoreSession();
055            List<Task> tasks = getTaskService().getTaskInstances(dm, (NuxeoPrincipal) null, coreSession);
056            if (!tasks.isEmpty()) {
057                for (Task task : tasks) {
058                    getTaskService().deleteTask(coreSession, task.getId());
059                }
060            }
061        }
062    }
063
064}