001/*
002 * (C) Copyright 2011-2016 Nuxeo SA (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 *     Anahide Tchertchian
018 */
019package org.nuxeo.ecm.platform.task.providers;
020
021import java.io.Serializable;
022import java.util.ArrayList;
023import java.util.List;
024import java.util.Locale;
025import java.util.Map;
026
027import org.apache.commons.logging.Log;
028import org.apache.commons.logging.LogFactory;
029import org.nuxeo.ecm.core.api.CoreSession;
030import org.nuxeo.ecm.core.api.DocumentModel;
031import org.nuxeo.ecm.core.api.LifeCycleConstants;
032import org.nuxeo.ecm.core.api.NuxeoException;
033import org.nuxeo.ecm.core.api.NuxeoPrincipal;
034import org.nuxeo.ecm.platform.query.api.AbstractPageProvider;
035import org.nuxeo.ecm.platform.query.api.PageProvider;
036import org.nuxeo.ecm.platform.task.Task;
037import org.nuxeo.ecm.platform.task.TaskService;
038import org.nuxeo.ecm.platform.task.dashboard.DashBoardItem;
039import org.nuxeo.ecm.platform.task.dashboard.DashBoardItemImpl;
040import org.nuxeo.runtime.api.Framework;
041
042/**
043 * Page provider for {@link DashBoardItem} elements.
044 * <p>
045 * Useful for content views displaying users' tasks.
046 * <p>
047 * WARNING: this page provider does not handle sorting, and its pagination management is not efficient (done in post
048 * filter).
049 * <p>
050 * This page provider requires the property {@link #CORE_SESSION_PROPERTY} to be filled with a core session. It also
051 * accepts an optional property {@link #FILTER_DOCS_FROM_TRASH}, defaulting to true.
052 *
053 * @since 5.5
054 */
055public class UserTaskPageProvider extends AbstractPageProvider<DashBoardItem> implements PageProvider<DashBoardItem> {
056
057    private static final long serialVersionUID = 1L;
058
059    private static final Log log = LogFactory.getLog(UserTaskPageProvider.class);
060
061    public static final String CORE_SESSION_PROPERTY = "coreSession";
062
063    public static final String FILTER_DOCS_FROM_TRASH = "filterDocumentsFromTrash";
064
065    protected List<DashBoardItem> userTasks;
066
067    protected List<DashBoardItem> pageTasks;
068
069    @Override
070    public List<DashBoardItem> getCurrentPage() {
071        if (pageTasks == null) {
072            pageTasks = new ArrayList<>();
073            if (userTasks == null) {
074                getAllTasks();
075            }
076            if (!hasError()) {
077                long resultsCount = userTasks.size();
078                setResultsCount(resultsCount);
079                // post-filter the results "by hand" to handle pagination
080                long pageSize = getMinMaxPageSize();
081                if (pageSize == 0) {
082                    pageTasks.addAll(userTasks);
083                } else {
084                    // handle offset
085                    long offset = getCurrentPageOffset();
086                    if (offset <= resultsCount) {
087                        for (int i = Long.valueOf(offset).intValue(); i < resultsCount && i < offset + pageSize; i++) {
088                            pageTasks.add(userTasks.get(i));
089                        }
090                    }
091                }
092            }
093        }
094        return pageTasks;
095    }
096
097    protected Locale getLocale() {
098        String locale = (String) getProperties().get("locale");
099        if (locale != null) {
100            return new Locale(locale);
101        }
102        return null;
103    }
104
105    protected void getAllTasks() {
106        error = null;
107        errorMessage = null;
108        userTasks = new ArrayList<>();
109        CoreSession coreSession = getCoreSession();
110        boolean filterTrashDocs = getFilterDocumentsInTrash();
111        NuxeoPrincipal pal = (NuxeoPrincipal) coreSession.getPrincipal();
112        TaskService taskService = Framework.getService(TaskService.class);
113        List<Task> tasks = taskService.getAllCurrentTaskInstances(coreSession, getSortInfos());
114        if (tasks != null) {
115            for (Task task : tasks) {
116                List<String> targetDocumentsIds = task.getTargetDocumentsIds();
117                boolean hasTargetDocuments = targetDocumentsIds != null && !targetDocumentsIds.isEmpty();
118                if (task.hasEnded() || task.isCancelled() || !hasTargetDocuments) {
119                    continue;
120                }
121                DocumentModel doc = taskService.getTargetDocumentModel(task, coreSession);
122                if (doc != null) {
123                    if (filterTrashDocs && LifeCycleConstants.DELETED_STATE.equals(doc.getCurrentLifeCycleState())) {
124                        continue;
125                    } else {
126                        userTasks.add(new DashBoardItemImpl(task, doc, getLocale()));
127                    }
128                } else {
129                    log.warn(String.format("User '%s' has a task of type '%s' on a missing or deleted document",
130                            pal.getName(), task.getName()));
131                }
132            }
133        }
134    }
135
136    protected boolean getFilterDocumentsInTrash() {
137        Map<String, Serializable> props = getProperties();
138        if (props.containsKey(FILTER_DOCS_FROM_TRASH)) {
139            return Boolean.TRUE.equals(Boolean.valueOf((String) props.get(FILTER_DOCS_FROM_TRASH)));
140        }
141        return true;
142    }
143
144    protected CoreSession getCoreSession() {
145        Map<String, Serializable> props = getProperties();
146        CoreSession coreSession = (CoreSession) props.get(CORE_SESSION_PROPERTY);
147        if (coreSession == null) {
148            throw new NuxeoException("cannot find core session");
149        }
150        return coreSession;
151    }
152
153    /**
154     * This page provider does not support sort for now => override what may be contributed in the definition
155     */
156    @Override
157    public boolean isSortable() {
158        return false;
159    }
160
161    @Override
162    protected void pageChanged() {
163        pageTasks = null;
164        super.pageChanged();
165    }
166
167    @Override
168    public void refresh() {
169        userTasks = null;
170        pageTasks = null;
171        super.refresh();
172    }
173
174}