001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 */
012package org.nuxeo.ecm.core.event.script;
013
014import javax.script.Bindings;
015import javax.script.ScriptException;
016import javax.script.SimpleBindings;
017
018import org.nuxeo.ecm.core.api.NuxeoException;
019import org.nuxeo.ecm.core.event.Event;
020import org.nuxeo.ecm.core.event.EventListener;
021
022/**
023 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
024 */
025public class ScriptingEventListener implements EventListener {
026
027    protected final Script script;
028
029    public ScriptingEventListener(Script script) {
030        this.script = script;
031    }
032
033    @Override
034    public void handleEvent(Event event) {
035        Bindings bindings = new SimpleBindings();
036        bindings.put("event", event);
037        bindings.put("context", event.getContext());
038        try {
039            script.run(bindings);
040        } catch (ScriptException e) {
041            throw new NuxeoException("Failed to run script: " + script.getLocation(), e);
042        }
043    }
044
045}