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