001/*
002 * (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     matic
016 */
017package org.nuxeo.ecm.platform.annotations.repository.service;
018
019import java.net.URI;
020import java.util.List;
021
022import org.nuxeo.ecm.core.api.CoreSession;
023import org.nuxeo.ecm.core.api.DocumentModel;
024import org.nuxeo.ecm.core.api.NuxeoPrincipal;
025import org.nuxeo.ecm.core.api.event.DocumentEventTypes;
026import org.nuxeo.ecm.core.event.Event;
027import org.nuxeo.ecm.core.event.EventContext;
028import org.nuxeo.ecm.platform.annotations.api.Annotation;
029import org.nuxeo.ecm.platform.annotations.api.AnnotationsService;
030import org.nuxeo.ecm.platform.annotations.repository.URNDocumentViewTranslator;
031import org.nuxeo.runtime.api.Framework;
032
033/**
034 * @author matic
035 */
036public class ResetCheckedoutGraphListener implements GraphManagerEventListener {
037
038    protected final URNDocumentViewTranslator translator = new URNDocumentViewTranslator();
039
040    protected final GraphManagerEventListener copyManager = new DocumentVersionnedGraphManager();
041
042    public void manage(Event event) {
043
044        copyManager.manage(event);
045
046        if (!DocumentEventTypes.DOCUMENT_CHECKEDIN.equals(event.getName())) {
047            return;
048        }
049
050        // reset checked-out graph
051
052        final EventContext context = event.getContext();
053        final CoreSession session = context.getCoreSession();
054
055        final DocumentModel doc = (DocumentModel) context.getArguments()[0];
056        final String repo = doc.getRepositoryName();
057
058        removeGraphFor(session, repo, doc, (NuxeoPrincipal) context.getPrincipal());
059    }
060
061    protected void removeGraphFor(CoreSession session, String repositoryName, DocumentModel doc, NuxeoPrincipal user)
062            {
063        URI uri = translator.getNuxeoUrn(repositoryName, doc.getId());
064        AnnotationsService service = Framework.getLocalService(AnnotationsService.class);
065
066        List<Annotation> annotations = service.queryAnnotations(uri, user);
067        for (Annotation annotation : annotations) {
068            AnnotationsRepositoryComponent.instance.injector.removeAnnotationText(doc, annotation.getId());
069            session.saveDocument(doc);
070            service.deleteAnnotationFor(uri, annotation, user);
071        }
072    }
073
074}