<commit_before>/*
 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 */
package org.nuxeo.ecm.platform.task.core.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.nuxeo.ecm.core.api.IdRef;
import org.nuxeo.ecm.core.api.NuxeoPrincipal;
import org.nuxeo.ecm.core.api.UnrestrictedSessionRunner;
import org.nuxeo.ecm.platform.ec.notification.NotificationConstants;
import org.nuxeo.ecm.platform.task.Task;
import org.nuxeo.ecm.platform.task.TaskEventNames;
import org.nuxeo.ecm.platform.task.TaskProvider;
import org.nuxeo.ecm.platform.task.TaskQueryConstant;
import org.nuxeo.ecm.platform.task.TaskService;
import org.nuxeo.ecm.platform.task.core.helpers.TaskActorsHelper;

/**
 * @author <NAME>uin
 * @author <NAME>
 * @since 5.5
 */
public class DocumentTaskProvider implements TaskProvider {

    private static final long serialVersionUID = 1L;

    private final static Log log = LogFactory.getLog(DocumentTaskProvider.class);

    @Override
    public List<Task> getCurrentTaskInstances(CoreSession coreSession)
            throws ClientException {

        // Get tasks for current user
        // We need to build the task actors list: prefixed and unprefixed names
        // of the principal and all its groups
        NuxeoPrincipal principal = (NuxeoPrincipal) coreSession.getPrincipal();
        List<String> actors = TaskActorsHelper.getTaskActors(principal);

        return getCurrentTaskInstances(actors, coreSession);
    }

    /**
     * Returns a list of task instances assigned to one of the actors in the
     * list or to its pool.
     *
     * @param actors a list used as actorId to retrieve the tasks.
     * @param filter
     * @return
     * @throws ClientException
     */
    @Override
    public List<Task> getCurrentTaskInstances(List<String> actors,
            CoreSession coreSession) throws ClientException {
        if (actors == null || actors.isEmpty()) {
            return new ArrayList<Task>();
        }
        String userNames = TaskQueryConstant.formatStringList(actors);
        String query = String.format(
                TaskQueryConstant.GET_TASKS_FOR_ACTORS_QUERY, userNames);
        DocumentModelList taskDocuments = coreSession.query(query);
        return wrapDocModelInTask(taskDocuments);
    }

    @Override
    public List<Task> getTaskInstances(DocumentModel dm, NuxeoPrincipal user,
            CoreSession coreSession) throws ClientException {
        String query;
        if (user == null) {
            query = String.format(
                    TaskQueryConstant.GET_TASKS_FOR_TARGET_DOCUMENT_QUERY,
                    dm.getId());
        } else {
            List<String> actors = TaskActorsHelper.getTaskActors(user);
            String userNames = TaskQueryConstant.formatStringList(actors);
            query = String.format(
                    TaskQueryConstant.GET_TASKS_FOR_TARGET_DOCUMENT_AND_ACTORS_QUERY,
                    dm.getId(), userNames);
        }
        DocumentModelList taskDocuments = coreSession.query(query);
        return wrapDocModelInTask(taskDocuments);
    }

    @Override
    public List<Task> getTaskInstances(DocumentModel dm, List<String> actors,
            CoreSession coreSession) throws ClientException {
        if (actors == null || actors.isEmpty()) {
            return new ArrayList<Task>();
        }
        String userNames = TaskQueryConstant.formatStringList(actors);
        String query = String.format(
                TaskQueryConstant.GET_TASKS_FOR_TARGET_DOCUMENT_AND_ACTORS_QUERY,
                dm.getId(), userNames);
        DocumentModelList taskDocuments = coreSession.query(query);
        return wrapDocModelInTask(taskDocuments);
    }

    @Override
    public List<Task> getAllTaskInstances(final String processId,
            CoreSession session) throws ClientException {
        final List<Task> tasks = new ArrayList<Task>();
        new UnrestrictedSessionRunner(session) {
            @Override
            public void run() throws ClientException {
                String query = String.format(
                        TaskQueryConstant.GET_TASKS_FOR_PROCESS_ID_QUERY,
                        processId);
                DocumentModelList taskDocuments = session.query(query);
                tasks.addAll(wrapDocModelInTask(taskDocuments, true));
            }
        }.runUnrestricted();
        return tasks;
    }

    @Override
    public List<Task> getAllTaskInstances(String processId,
            NuxeoPrincipal user, CoreSession session) throws ClientException {
        List<String> actors = TaskActorsHelper.getTaskActors(user);
        return getAllTaskInstances(processId, actors, session);
    }

    @Override
    public List<Task> getAllTaskInstances(final String processId,
            final List<String> actors, CoreSession session)
            throws ClientException {
        final List<Task> tasks = new ArrayList<Task>();
        new UnrestrictedSessionRunner(session) {
            @Override
            public void run() throws ClientException {
                String query = String.format(
                        TaskQueryConstant.GET_TASKS_FOR_PROCESS_ID_AND_ACTORS_QUERY,
                        processId, actors);
                DocumentModelList taskDocuments = session.query(query);
                tasks.addAll(wrapDocModelInTask(taskDocuments, true));
            }
        }.runUnrestricted();
        return tasks;
    }

    public static List<Task> wrapDocModelInTask(DocumentModelList taskDocuments) {
        List<Task> tasks = new ArrayList<Task>();
        for (DocumentModel doc : taskDocuments) {
            tasks.add(doc.getAdapter(Task.class));
        }
        return tasks;
    }

    /**
     * Converts a {@link DocumentModelList} to a list of {@link Task}s.
     *
     * @param detach if {@code true}, detach each document before converting it
     *            to a {@code Task}.
     */
    public static List<Task> wrapDocModelInTask(
            DocumentModelList taskDocuments, boolean detach)<commit_msg>NXP-9666: correctly compute usernames list for the query<commit_after>/*
 * (C) Copyright 2012 <NAME> (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 */
package org.nuxeo.ecm.platform.task.core.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.nuxeo.ecm.core.api.IdRef;
import org.nuxeo.ecm.core.api.NuxeoPrincipal;
import org.nuxeo.ecm.core.api.UnrestrictedSessionRunner;
import org.nuxeo.ecm.platform.ec.notification.NotificationConstants;
import org.nuxeo.ecm.platform.task.Task;
import org.nuxeo.ecm.platform.task.TaskEventNames;
import org.nuxeo.ecm.platform.task.TaskProvider;
import org.nuxeo.ecm.platform.task.TaskQueryConstant;
import org.nuxeo.ecm.platform.task.TaskService;
import org.nuxeo.ecm.platform.task.core.helpers.TaskActorsHelper;

/**
 * @author <NAME>
 * @author <NAME>
 * @since 5.5
 */
public class DocumentTaskProvider implements TaskProvider {

    private static final long serialVersionUID = 1L;

    private final static Log log = LogFactory.getLog(DocumentTaskProvider.class);

    @Override
    public List<Task> getCurrentTaskInstances(CoreSession coreSession)
            throws ClientException {

        // Get tasks for current user
        // We need to build the task actors list: prefixed and unprefixed names
        // of the principal and all its groups
        NuxeoPrincipal principal = (NuxeoPrincipal) coreSession.getPrincipal();
        List<String> actors = TaskActorsHelper.getTaskActors(principal);

        return getCurrentTaskInstances(actors, coreSession);
    }

    /**
     * Returns a list of task instances assigned to one of the actors in the
     * list or to its pool.
     *
     * @param actors a list used as actorId to retrieve the tasks.
     * @param filter
     * @return
     * @throws ClientException
     */
    @Override
    public List<Task> getCurrentTaskInstances(List<String> actors,
            CoreSession coreSession) throws ClientException {
        if (actors == null || actors.isEmpty()) {
            return new ArrayList<Task>();
        }
        String userNames = TaskQueryConstant.formatStringList(actors);
        String query = String.format(
                TaskQueryConstant.GET_TASKS_FOR_ACTORS_QUERY, userNames);
        DocumentModelList taskDocuments = coreSession.query(query);
        return wrapDocModelInTask(taskDocuments);
    }

    @Override
    public List<Task> getTaskInstances(DocumentModel dm, NuxeoPrincipal user,
            CoreSession coreSession) throws ClientException {
        String query;
        if (user == null) {
            query = String.format(
                    TaskQueryConstant.GET_TASKS_FOR_TARGET_DOCUMENT_QUERY,
                    dm.getId());
        } else {
            List<String> actors = TaskActorsHelper.getTaskActors(user);
            String userNames = TaskQueryConstant.formatStringList(actors);
            query = String.format(
                    TaskQueryConstant.GET_TASKS_FOR_TARGET_DOCUMENT_AND_ACTORS_QUERY,
                    dm.getId(), userNames);
        }
        DocumentModelList taskDocuments = coreSession.query(query);
        return wrapDocModelInTask(taskDocuments);
    }

    @Override
    public List<Task> getTaskInstances(DocumentModel dm, List<String> actors,
            CoreSession coreSession) throws ClientException {
        if (actors == null || actors.isEmpty()) {
            return new ArrayList<Task>();
        }
        String userNames = TaskQueryConstant.formatStringList(actors);
        String query = String.format(
                TaskQueryConstant.GET_TASKS_FOR_TARGET_DOCUMENT_AND_ACTORS_QUERY,
                dm.getId(), userNames);
        DocumentModelList taskDocuments = coreSession.query(query);
        return wrapDocModelInTask(taskDocuments);
    }

    @Override
    public List<Task> getAllTaskInstances(final String processId,
            CoreSession session) throws ClientException {
        final List<Task> tasks = new ArrayList<Task>();
        new UnrestrictedSessionRunner(session) {
            @Override
            public void run() throws ClientException {
                String query = String.format(
                        TaskQueryConstant.GET_TASKS_FOR_PROCESS_ID_QUERY,
                        processId);
                DocumentModelList taskDocuments = session.query(query);
                tasks.addAll(wrapDocModelInTask(taskDocuments, true));
            }
        }.runUnrestricted();
        return tasks;
    }

    @Override
    public List<Task> getAllTaskInstances(String processId,
            NuxeoPrincipal user, CoreSession session) throws ClientException {
        List<String> actors = TaskActorsHelper.getTaskActors(user);
        return getAllTaskInstances(processId, actors, session);
    }

    @Override
    public List<Task> getAllTaskInstances(final String processId,
            final List<String> actors, CoreSession session)
            throws ClientException {
        final List<Task> tasks = new ArrayList<Task>();
        new UnrestrictedSessionRunner(session) {
            @Override
            public void run() throws ClientException {
                String userNames = TaskQueryConstant.formatStringList(actors);
                String query = String.format(
                        TaskQueryConstant.GET_TASKS_FOR_PROCESS_ID_AND_ACTORS_QUERY,
                        processId, userNames);
                DocumentModelList taskDocuments = session.query(query);
                tasks.addAll(wrapDocModelInTask(taskDocuments, true));
            }
        }.runUnrestricted();
        return tasks;
    }

    public static List<Task> wrapDocModelInTask(DocumentModelList taskDocuments) {
        List<Task> tasks = new ArrayList<Task>();
        for (DocumentModel doc : taskDocuments) {
            tasks.add(doc.getAdapter(Task.class));
        }
        return tasks;
    }

    /**
     * Converts a {@link DocumentModelList} to a list of {@link Task}s.
     *
     * @param detach if {@code true}, detach each document before converting it
     *            to a {@code Task}.
     */
    public static List<Task> wrapDocModelInTask(
            DocumentModelList taskDocuments, boolean detach)
{'fraction_non_alphanumeric': 0.08343967106195944, 'fraction_numerical': 0.0015596200198497094, 'mean_word_length': 2.781023854194586, 'pattern_counts': {'":': 0, '<': 54, '<?xml version=': 0, '>': 54, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6967363', 'n_tokens_mistral': 3934, 'n_tokens_neox': 3720, 'n_words': 946}