001/*
002 * (C) Copyright 2006-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 *     bstefanescu
018 */
019package org.nuxeo.ecm.automation.core.events;
020
021import java.util.List;
022import java.util.Set;
023
024import org.apache.commons.logging.Log;
025import org.apache.commons.logging.LogFactory;
026import org.nuxeo.ecm.automation.AutomationService;
027import org.nuxeo.ecm.automation.OperationContext;
028import org.nuxeo.ecm.automation.OperationException;
029import org.nuxeo.ecm.core.api.NuxeoException;
030import org.nuxeo.ecm.core.event.Event;
031import org.nuxeo.ecm.core.event.EventContext;
032import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
033
034/**
035 * TODO: This service should be moved in another project, and renamed since it's a service, not a simple registry...
036 *
037 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
038 */
039public class EventHandlerRegistry {
040
041    private static final Log log = LogFactory.getLog(OperationEventListener.class);
042
043    protected final AutomationService svc;
044
045    protected EventRegistry handlers;
046
047    protected EventRegistry pchandlers;
048
049    public EventHandlerRegistry(AutomationService svc) {
050        this.svc = svc;
051        handlers = new EventRegistry();
052        pchandlers = new EventRegistry();
053    }
054
055    public List<EventHandler> getEventHandlers(String eventId) {
056        return handlers.lookup().get(eventId);
057    }
058
059    public List<EventHandler> getPostCommitEventHandlers(String eventId) {
060        return pchandlers.lookup().get(eventId);
061    }
062
063    public void putEventHandler(EventHandler handler) {
064        handlers.addContribution(handler);
065    }
066
067    public synchronized void putPostCommitEventHandler(EventHandler handler) {
068        pchandlers.addContribution(handler);
069    }
070
071    public synchronized void removePostCommitEventHandler(EventHandler handler) {
072        pchandlers.removeContribution(handler);
073    }
074
075    public synchronized void removeEventHandler(EventHandler handler) {
076        handlers.removeContribution(handler);
077    }
078
079    public synchronized void clear() {
080        handlers = new EventRegistry();
081        pchandlers = new EventRegistry();
082    }
083
084    public Set<String> getPostCommitEventNames() {
085        return pchandlers.lookup().keySet();
086    }
087
088    public boolean acceptEvent(Event event, List<EventHandler> handlers) {
089        if (handlers == null || handlers.isEmpty()) {
090            return false;
091        }
092
093        try (OperationContext ctx = open(event)) {
094            EventContext ectx = event.getContext();
095            ctx.put("Event", event);
096            for (EventHandler handler : handlers) {
097                if (handler.isEnabled(ctx, ectx, true)) {
098                    return true;
099                }
100            }
101            return false;
102        }
103    }
104
105    protected OperationContext open(Event event) {
106        EventContext ectx = event.getContext();
107        if (ectx instanceof DocumentEventContext) {
108            OperationContext ctx = new OperationContext(ectx.getCoreSession());
109            ctx.setInput(((DocumentEventContext) ectx).getSourceDocument());
110            return ctx;
111        }
112        return new OperationContext();
113    }
114
115    // TODO: impl remove handlers method? or should refactor runtime to be able
116    // to redeploy only using clear() method
117
118    public void handleEvent(Event event, List<EventHandler> handlers, boolean saveSession) {
119        if (handlers == null || handlers.isEmpty()) {
120            return; // ignore
121        }
122
123        EventContext ectx = event.getContext();
124        for (EventHandler handler : handlers) {
125            try (OperationContext ctx = getContext(ectx)) {
126                ctx.put("Event", event);
127                ctx.setCommit(saveSession); // avoid reentrant events
128                if (handler.isEnabled(ctx, ectx, false)) {
129                    // TODO this will save the session at each iteration!
130                    svc.run(ctx, handler.getChainId());
131                }
132            } catch (OperationException e) {
133                log.error("Failed to handle event " + event.getName() + " using chain: " + handler.getChainId(), e);
134                throw new NuxeoException(e);
135            } catch (NuxeoException e) {
136                log.error("Failed to handle event " + event.getName() + " using chain: " + handler.getChainId(), e);
137                throw e;
138            }
139        }
140    }
141
142    protected OperationContext getContext(EventContext ectx) {
143        if (ectx instanceof DocumentEventContext) {
144            OperationContext ctx = new OperationContext(ectx.getCoreSession());
145            ctx.setInput(((DocumentEventContext) ectx).getSourceDocument());
146            return ctx;
147        }
148        // not a document event .. the chain must begin with void
149        // operation - session is not available.
150        return new OperationContext();
151    }
152
153}