001/*
002 *  Copyright 2018 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.odf.schedulable;
017
018import java.util.List;
019import java.util.stream.Collectors;
020
021import org.apache.avalon.framework.service.ServiceException;
022import org.apache.avalon.framework.service.ServiceManager;
023import org.quartz.JobExecutionContext;
024
025import org.ametys.cms.repository.Content;
026import org.ametys.cms.repository.ContentDAO;
027import org.ametys.cms.search.content.ContentSearcherFactory;
028import org.ametys.cms.search.query.NotQuery;
029import org.ametys.cms.search.query.Query.Operator;
030import org.ametys.cms.search.query.StringQuery;
031import org.ametys.odf.coursepart.CoursePart;
032import org.ametys.odf.coursepart.CoursePartFactory;
033import org.ametys.plugins.core.impl.schedule.AbstractStaticSchedulable;
034import org.ametys.plugins.repository.RemovableAmetysObject;
035
036/**
037 * Scheduler to purge orphan course parts.
038 */
039public class CoursePartPurgeSchedulable extends AbstractStaticSchedulable
040{
041    private ContentSearcherFactory _contentSearcherFactory;
042    private ContentDAO _contentDAO;
043
044    @Override
045    public void service(ServiceManager manager) throws ServiceException
046    {
047        super.service(manager);
048        _contentSearcherFactory = (ContentSearcherFactory) manager.lookup(ContentSearcherFactory.ROLE);
049        _contentDAO = (ContentDAO) manager.lookup(ContentDAO.ROLE);
050    }
051    
052    @Override
053    public void execute(JobExecutionContext context) throws Exception
054    {
055        // Getting all orphan course parts (linked to any course)
056        List<String> contentIdsToDelete = _contentSearcherFactory
057            .create(CoursePartFactory.COURSE_PART_CONTENT_TYPE)
058            .search(new NotQuery(new StringQuery(CoursePart.PARENT_COURSES, Operator.EXISTS, null, null)))
059            .stream()
060            .filter(RemovableAmetysObject.class::isInstance)
061            .map(Content::getId)
062            .collect(Collectors.toList());
063        
064        _contentDAO.deleteContents(contentIdsToDelete, true);
065    }
066}