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 *     Nuxeo - initial API and implementation
016 */
017package org.nuxeo.ecm.platform.routing.core.listener;
018
019import org.nuxeo.ecm.core.api.DocumentModel;
020import org.nuxeo.ecm.core.event.Event;
021import org.nuxeo.ecm.core.event.EventListener;
022import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
023import org.nuxeo.ecm.platform.comment.api.CommentEvents;
024import org.nuxeo.ecm.platform.routing.api.DocumentRouteStep;
025import org.nuxeo.ecm.platform.routing.api.DocumentRoutingConstants;
026
027/***
028 * Updates the number of comments stored on the {@link DocumentRouteStep}. This is used to avoid unnecessary jena calls
029 * when displaying the number of comments on each step.
030 *
031 * @author mcedica
032 */
033public class DocumentRoutingUpdateCommentsInfoListener implements EventListener {
034
035    @Override
036    public void handleEvent(Event event) {
037        String eventId = event.getName();
038
039        if (!eventId.equals(CommentEvents.COMMENT_ADDED) && !eventId.equals(CommentEvents.COMMENT_REMOVED)) {
040            return;
041        }
042        DocumentEventContext docCtx;
043        if (event.getContext() instanceof DocumentEventContext) {
044            docCtx = (DocumentEventContext) event.getContext();
045        } else {
046            return;
047        }
048        DocumentModel doc = docCtx.getSourceDocument();
049        if (!doc.hasFacet(DocumentRoutingConstants.COMMENTS_INFO_HOLDER_FACET)) {
050            return;
051        }
052        Long comments = (Long) doc.getPropertyValue(DocumentRoutingConstants.COMMENTS_NO_PROPERTY_NAME);
053        // else increase or decrease the number of comments on the doc
054        if (eventId.equals(CommentEvents.COMMENT_ADDED)) {
055            doc.setPropertyValue(DocumentRoutingConstants.COMMENTS_NO_PROPERTY_NAME, ++comments);
056        }
057        if (eventId.equals(CommentEvents.COMMENT_REMOVED)) {
058            doc.setPropertyValue(DocumentRoutingConstants.COMMENTS_NO_PROPERTY_NAME, --comments);
059        }
060        event.getContext().getCoreSession().saveDocument(doc);
061    }
062}