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