001/* 002 * (C) Copyright 2020 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 * Nour AL KOTOB 018 */ 019package org.nuxeo.ecm.platform.routing.core.listener; 020 021import static org.nuxeo.ecm.core.query.sql.NXQL.ECM_UUID; 022import static org.nuxeo.ecm.platform.routing.api.DocumentRoutingConstants.DOCUMENT_ROUTE_DOCUMENT_TYPE; 023import static org.nuxeo.ecm.platform.task.TaskConstants.TASK_PROCESS_ID_PROPERTY_NAME; 024import static org.nuxeo.ecm.platform.task.TaskConstants.TASK_TYPE_NAME; 025 026import org.nuxeo.ecm.core.api.CoreSession; 027import org.nuxeo.ecm.core.api.DocumentModel; 028import org.nuxeo.ecm.core.api.IdRef; 029import org.nuxeo.ecm.core.event.Event; 030import org.nuxeo.ecm.core.event.EventBundle; 031import org.nuxeo.ecm.core.event.PostCommitEventListener; 032import org.nuxeo.ecm.core.event.impl.DocumentEventContext; 033 034/** 035 * Listener that deletes orphan Tasks. 036 * 037 * @since 11.1 038 */ 039public class DocumentRouteDeletedListener implements PostCommitEventListener { 040 041 protected static final String QUERY_GET_TASKS_RELATED_TO_DOCUMENT_ROUTE = "SELECT * FROM " + TASK_TYPE_NAME 042 + " WHERE " + TASK_PROCESS_ID_PROPERTY_NAME + " = '%s'"; 043 044 @Override 045 public void handleEvent(EventBundle events) { 046 for (Event event : events) { 047 DocumentEventContext context = (DocumentEventContext) event.getContext(); 048 DocumentModel docModel = context.getSourceDocument(); 049 if (DOCUMENT_ROUTE_DOCUMENT_TYPE.equals(docModel.getType())) { 050 deleteOrphanTasks(context.getCoreSession(), docModel.getId()); 051 } 052 } 053 } 054 055 /** 056 * Deletes all tasks whose process id matches the given DocumentRoute id. 057 * 058 * @since 11.1 059 */ 060 protected void deleteOrphanTasks(CoreSession session, String id) { 061 String query = String.format(QUERY_GET_TASKS_RELATED_TO_DOCUMENT_ROUTE, id); 062 session.queryProjection(query, 0, 0) 063 .stream() 064 .map(m -> m.get(ECM_UUID)) 065 .map(taskId -> new IdRef((String) taskId)) 066 .forEach(session::removeDocument); 067 } 068 069}