001/**
002 * Copyright 2015 DuraSpace, Inc.
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.fcrepo.kernel.impl.observer.eventmappings;
017
018import static com.google.common.collect.Multimaps.index;
019import static org.slf4j.LoggerFactory.getLogger;
020import static java.util.Arrays.asList;
021import static javax.jcr.observation.Event.PROPERTY_ADDED;
022import static javax.jcr.observation.Event.PROPERTY_CHANGED;
023import static javax.jcr.observation.Event.PROPERTY_REMOVED;
024
025import java.util.Iterator;
026import java.util.List;
027
028import javax.jcr.RepositoryException;
029import javax.jcr.observation.Event;
030
031import org.fcrepo.kernel.exception.RepositoryRuntimeException;
032import org.fcrepo.kernel.observer.FedoraEvent;
033import org.fcrepo.kernel.observer.eventmappings.InternalExternalEventMapper;
034
035import org.slf4j.Logger;
036
037import com.google.common.base.Function;
038import com.google.common.collect.Multimap;
039
040/**
041 * Maps all JCR {@link Event}s concerning one JCR node to one
042 * {@link FedoraEvent}. Adds the types of those JCR events together to calculate
043 * the final type of the emitted FedoraEvent. TODO stop aggregating events in
044 * the heap and make this a purely iterative algorithm, if possible
045 *
046 * @author ajs6f
047 * @since Feb 27, 2014
048 */
049public class AllNodeEventsOneEvent implements InternalExternalEventMapper {
050
051    private static final List<Integer> PROPERTY_EVENT_TYPES = asList(PROPERTY_ADDED, PROPERTY_CHANGED,
052            PROPERTY_REMOVED);
053
054    /**
055     * Extracts the node identifier from a JCR {@link Event}.
056     */
057    private static final Function<Event, String> EXTRACT_NODE_ID = new Function<Event, String>() {
058
059        @Override
060        public String apply(final Event ev) {
061            try {
062                final String id = ev.getIdentifier();
063                LOGGER.debug("Sorting an event by identifier: {}", id);
064                return id;
065            } catch (final RepositoryException e) {
066                throw new RepositoryRuntimeException(e);
067            }
068        }
069    };
070
071    @Override
072    public Iterator<FedoraEvent> apply(final Iterator<Event> events) {
073        return new FedoraEventIterator(events);
074    }
075
076    private static class FedoraEventIterator implements Iterator {
077
078        private final Iterator<Event> events;
079
080        // sort JCR events into a Multimap keyed by the node ID involved
081        private final Multimap<String, Event> sortedEvents;
082
083        private final Iterator<String> nodeIds;
084
085        public FedoraEventIterator(final Iterator<Event> events) {
086            this.events = events;
087            sortedEvents = index(events, EXTRACT_NODE_ID);
088            nodeIds = sortedEvents.keySet().iterator();
089        }
090
091        @Override
092        public boolean hasNext() {
093            return nodeIds.hasNext();
094        }
095
096        @Override
097        public FedoraEvent next() {
098            final Iterator<Event> nodeSpecificEvents = sortedEvents.get(nodeIds.next()).iterator();
099            // we can safely call next() immediately on nodeSpecificEvents
100            // because if
101            // there was no event at all, there would appear no entry in our
102            // Multimap under this key
103            final Event firstEvent = nodeSpecificEvents.next();
104            final FedoraEvent fedoraEvent = new FedoraEvent(firstEvent);
105
106            addProperty(fedoraEvent, firstEvent);
107            while (nodeSpecificEvents.hasNext()) {
108                // add the event type and property name to the event we are building up to emit
109                // we could aggregate other information here if that seems useful
110                final Event otherEvent = nodeSpecificEvents.next();
111                fedoraEvent.addType(otherEvent.getType());
112                addProperty(fedoraEvent, otherEvent);
113            }
114            return fedoraEvent;
115        }
116
117        @Override
118        public void remove() {
119            // the underlying Multimap is immutable anyway
120            throw new UnsupportedOperationException();
121        }
122
123        private void addProperty( final FedoraEvent fedoraEvent, final Event ev ) {
124            try {
125                if (PROPERTY_EVENT_TYPES.contains(ev.getType())) {
126                    final String eventPath = ev.getPath();
127                    fedoraEvent.addProperty(eventPath.substring(eventPath.lastIndexOf('/') + 1));
128                } else {
129                    LOGGER.trace("Not adding non-event property: {}, {}", fedoraEvent, ev);
130                }
131            } catch (final RepositoryException e) {
132                throw new RepositoryRuntimeException(e);
133            }
134        }
135    }
136
137    private final static Logger LOGGER = getLogger(AllNodeEventsOneEvent.class);
138}