001/*
002 *  Copyright 2016 Anyware Services
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 */
016package org.ametys.plugins.workspaces.tasks.generators;
017
018import java.io.IOException;
019import java.util.Comparator;
020import java.util.List;
021import java.util.Set;
022import java.util.stream.Stream;
023
024import org.apache.avalon.framework.service.ServiceException;
025import org.apache.avalon.framework.service.ServiceManager;
026import org.apache.cocoon.ProcessingException;
027import org.apache.cocoon.generation.ServiceableGenerator;
028import org.apache.cocoon.xml.AttributesImpl;
029import org.apache.cocoon.xml.XMLUtils;
030import org.xml.sax.SAXException;
031
032import org.ametys.core.user.CurrentUserProvider;
033import org.ametys.core.user.UserIdentity;
034import org.ametys.plugins.workspaces.project.ProjectManager;
035import org.ametys.plugins.workspaces.project.ProjectsCatalogueManager;
036import org.ametys.plugins.workspaces.project.modules.WorkspaceModule;
037import org.ametys.plugins.workspaces.project.modules.WorkspaceModuleExtensionPoint;
038import org.ametys.plugins.workspaces.project.objects.Project;
039import org.ametys.plugins.workspaces.tasks.Task;
040import org.ametys.plugins.workspaces.tasks.TasksWorkspaceModule;
041import org.ametys.plugins.workspaces.tasks.WorkspaceTaskDAO;
042import org.ametys.web.repository.page.Page;
043
044/**
045 * Task list generator for the simple service.
046 */
047public class TaskListGenerator extends ServiceableGenerator
048{
049    /** The project manager */
050    protected ProjectManager _projectManager;
051    
052    /** The project calaog manager */
053    protected ProjectsCatalogueManager _projectCatalogManager;
054    
055    /** The workspace task DAO */
056    protected WorkspaceTaskDAO _workspaceTaskDAO;
057    
058    /** The current user provider */
059    protected CurrentUserProvider _currentUserProvider;
060    
061    private WorkspaceModuleExtensionPoint _moduleEP;
062    
063    @Override
064    public void service(ServiceManager serviceManager) throws ServiceException
065    {
066        _projectManager = (ProjectManager) serviceManager.lookup(ProjectManager.ROLE);
067        _moduleEP = (WorkspaceModuleExtensionPoint) serviceManager.lookup(WorkspaceModuleExtensionPoint.ROLE);
068        _projectCatalogManager = (ProjectsCatalogueManager) serviceManager.lookup(ProjectsCatalogueManager.ROLE);
069        _workspaceTaskDAO = (WorkspaceTaskDAO) serviceManager.lookup(WorkspaceTaskDAO.ROLE);
070        _currentUserProvider = (CurrentUserProvider) serviceManager.lookup(CurrentUserProvider.ROLE);
071    }
072    
073    @Override
074    public void generate() throws IOException, SAXException, ProcessingException
075    {
076        int max = parameters.getParameterAsInteger("max-results", 0);
077        
078        UserIdentity currentUser = _currentUserProvider.getUser();
079        
080        Stream<Task> streamTasks = _projectManager.getUserProjects(currentUser)
081            .keySet()
082            .stream()
083            .map(project -> _workspaceTaskDAO.getProjectTasks(project))
084            .flatMap(List::stream)
085            .filter(t -> !t.isClosed()) // sax only open task
086            .filter(t -> t.getAssignments().contains(currentUser)) // sax only task assigned to current user
087            .sorted(Comparator.comparing(t -> t.getCreationDate())); // sort by creation date
088        
089        if (max > 0)
090        {
091            streamTasks = streamTasks.limit(max);
092        }
093        
094        // SAX the tasks
095        contentHandler.startDocument();
096        XMLUtils.startElement(contentHandler, "tasks");
097
098        streamTasks.forEach(task ->
099        {
100            Project project = _projectManager.getParentProject(task);
101            this._saxTask(project, task);
102        });
103        
104        XMLUtils.endElement(contentHandler, "tasks");
105        contentHandler.endDocument();
106    }
107    
108    /**
109     * SAX necessary task properties for the simple task list service.
110     * @param project the parent roject
111     * @param task The task
112     */
113    protected void _saxTask(Project project, Task task)
114    {
115        try
116        {
117            AttributesImpl attrs = new AttributesImpl();
118            
119            attrs.addCDATAAttribute("id", task.getId());
120            
121            String pageId = _getTaskPageId(project);
122            if (pageId != null)
123            {
124                attrs.addCDATAAttribute("pageId", pageId);
125            }
126            XMLUtils.startElement(contentHandler, "task", attrs);
127            
128            // Project
129            attrs.clear();
130            attrs.addCDATAAttribute("id", project.getId());
131            String siteUrl = _projectManager.getProjectUrl(project, null);
132            if (siteUrl != null)
133            {
134                attrs.addCDATAAttribute("url", siteUrl);
135            }
136            XMLUtils.createElement(contentHandler, "project", project.getTitle());
137            
138            _projectCatalogManager.saxCategory(contentHandler, project, "projectCategory");
139            
140            task.dataToSAX(contentHandler);
141            
142            XMLUtils.endElement(contentHandler, "task");
143        }
144        catch (Exception e)
145        {
146            throw new RuntimeException("An error occurred while gathering the tasks' information.");
147        }
148    }
149    
150    private String _getTaskPageId (Project project)
151    {
152        WorkspaceModule module = _moduleEP.getModule(TasksWorkspaceModule.TASK_MODULE_ID);
153        Set<Page> taskModulePages = _projectManager.getModulePages(project, module);
154        if (!taskModulePages.isEmpty())
155        {
156            return taskModulePages.iterator().next().getId();
157        }
158        
159        return null;
160    }
161}