001/*
002 * (C) Copyright 2012 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 *     Arnaud Kervern
018 */
019package org.nuxeo.ecm.rating.listener;
020
021import static org.nuxeo.ecm.activity.ActivityHelper.createDocumentActivityObject;
022import static org.nuxeo.ecm.core.api.LifeCycleConstants.DELETED_STATE;
023import static org.nuxeo.ecm.core.api.LifeCycleConstants.TRANSITION_EVENT;
024import static org.nuxeo.ecm.core.api.LifeCycleConstants.TRANSTION_EVENT_OPTION_TO;
025import static org.nuxeo.ecm.core.api.event.DocumentEventTypes.DOCUMENT_REMOVED;
026
027import org.nuxeo.ecm.core.api.DocumentModel;
028import org.nuxeo.ecm.core.event.Event;
029import org.nuxeo.ecm.core.event.EventListener;
030import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
031import org.nuxeo.ecm.rating.api.RatingService;
032import org.nuxeo.runtime.api.Framework;
033
034/**
035 * Remove rates made when a document is removed or his lifecycle state is changing to DELETED_STATE
036 *
037 * @author <a href="mailto:akervern@nuxeo.com">Arnaud Kervern</a>
038 */
039public class RatingListener implements EventListener {
040    @Override
041    public void handleEvent(Event event) {
042        if (event.getContext() instanceof DocumentEventContext) {
043            DocumentEventContext ctx = (DocumentEventContext) event.getContext();
044            DocumentModel document = ctx.getSourceDocument();
045
046            if (DOCUMENT_REMOVED.equals(event.getName())) {
047                cancelRates(document);
048            } else if (TRANSITION_EVENT.equals(event.getName())) {
049                String destinationState = (String) ctx.getProperty(TRANSTION_EVENT_OPTION_TO);
050                if (DELETED_STATE.equals(destinationState)) {
051                    cancelRates(document);
052                }
053            }
054        }
055    }
056
057    protected void cancelRates(DocumentModel document) {
058        RatingService ratingService = Framework.getLocalService(RatingService.class);
059        ratingService.cancelRates(createDocumentActivityObject(document), null);
060    }
061}