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        } catch (OperationException cause) {
103            throw new NuxeoException(cause);
104        }
105    }
106
107    protected OperationContext open(Event event) {
108        EventContext ectx = event.getContext();
109        if (ectx instanceof DocumentEventContext) {
110            OperationContext ctx = new OperationContext(ectx.getCoreSession());
111            ctx.setInput(((DocumentEventContext) ectx).getSourceDocument());
112            return ctx;
113        }
114        return new OperationContext();
115    }
116
117    // TODO: impl remove handlers method? or should refactor runtime to be able
118    // to redeploy only using clear() method
119
120    public void handleEvent(Event event, List<EventHandler> handlers, boolean saveSession) {
121        if (handlers == null || handlers.isEmpty()) {
122            return; // ignore
123        }
124
125        EventContext ectx = event.getContext();
126        for (EventHandler handler : handlers) {
127            try (OperationContext ctx = getContext(ectx)) {
128                ctx.put("Event", event);
129                ctx.setCommit(saveSession); // avoid reentrant events
130                if (handler.isEnabled(ctx, ectx, false)) {
131                    // TODO this will save the session at each iteration!
132                    svc.run(ctx, handler.getChainId());
133                }
134            } catch (NuxeoException | OperationException e) {
135                log.error("Failed to handle event " + event.getName() + " using chain: " + handler.getChainId(), e);
136            }
137        }
138    }
139
140    protected OperationContext getContext(EventContext ectx) {
141        if (ectx instanceof DocumentEventContext) {
142            OperationContext ctx = new OperationContext(ectx.getCoreSession());
143            ctx.setInput(((DocumentEventContext) ectx).getSourceDocument());
144            return ctx;
145        }
146        // not a document event .. the chain must begin with void
147        // operation - session is not available.
148        return new OperationContext();
149    }
150
151}