001/*
002 * (C) Copyright 2007-2010 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Florent Guillaume
016 */
017package org.nuxeo.ecm.core.scheduler;
018
019import java.io.Serializable;
020import java.util.HashMap;
021import java.util.Map;
022
023import javax.security.auth.login.LoginContext;
024import javax.security.auth.login.LoginException;
025
026import org.apache.commons.logging.Log;
027import org.apache.commons.logging.LogFactory;
028import org.nuxeo.ecm.core.api.impl.UserPrincipal;
029import org.nuxeo.ecm.core.event.Event;
030import org.nuxeo.ecm.core.event.EventContext;
031import org.nuxeo.ecm.core.event.EventService;
032import org.nuxeo.ecm.core.event.impl.EventContextImpl;
033import org.nuxeo.ecm.core.event.impl.EventImpl;
034import org.nuxeo.runtime.api.Framework;
035import org.nuxeo.runtime.api.login.LoginAs;
036import org.nuxeo.runtime.transaction.TransactionHelper;
037import org.quartz.Job;
038import org.quartz.JobDataMap;
039import org.quartz.JobExecutionContext;
040import org.quartz.JobExecutionException;
041
042/**
043 * A Quartz job whose execution sends a configured event.
044 */
045public class EventJob implements Job {
046
047    private static final Log log = LogFactory.getLog(EventJob.class);
048
049    /**
050     * Job execution to send the configured event.
051     */
052    @Override
053    public void execute(JobExecutionContext context) throws JobExecutionException {
054        JobDataMap dataMap = context.getJobDetail().getJobDataMap();
055
056        // switch to the Nuxeo classloader so that the event listeners
057        // work as usual
058
059        ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
060        ClassLoader nuxeoCL = getClass().getClassLoader();
061        Thread.currentThread().setContextClassLoader(nuxeoCL);
062        try {
063            execute(dataMap);
064        } catch (LoginException e) {
065            String eventId = dataMap.getString("eventId");
066            log.error("Error while processing scheduled event id: " + eventId, e);
067        } finally {
068            Thread.currentThread().setContextClassLoader(oldCL);
069        }
070    }
071
072    protected void execute(JobDataMap dataMap) throws LoginException {
073        String eventId = dataMap.getString("eventId");
074        String eventCategory = dataMap.getString("eventCategory");
075        String username = dataMap.getString("username");
076
077        SchedulerService scheduler = Framework.getLocalService(SchedulerService.class);
078        if (scheduler == null || !scheduler.hasApplicationStarted()) {
079            // too early
080            return;
081        }
082
083        EventService eventService = Framework.getService(EventService.class);
084        if (eventService == null) {
085            log.error("Cannot find EventService");
086            return;
087        }
088
089        LoginContext loginContext = null;
090        try {
091            // login
092            if (username == null) {
093                loginContext = Framework.login();
094            } else {
095                if (Framework.getLocalService(LoginAs.class) != null) {
096                    loginContext = Framework.loginAsUser(username);
097                } else if (!Framework.isTestModeSet()) {
098                    log.error("LoginAs service not available");
099                }
100            }
101
102            // set up event context
103            UserPrincipal principal = new UserPrincipal(username, null, false, false);
104            EventContext eventContext = new EventContextImpl(null, principal);
105            eventContext.setProperty("category", eventCategory);
106            eventContext.setProperties(getWrappedMap(dataMap));
107            Event event = new EventImpl(eventId, eventContext);
108
109            // start transaction
110            boolean tx = TransactionHelper.startTransaction();
111
112            // send event
113            log.debug("Sending scheduled event id=" + eventId + ", category=" + eventCategory + ", username="
114                    + username);
115            boolean ok = false;
116            try {
117                eventService.fireEvent(event);
118                ok = true;
119            } finally {
120                if (tx) {
121                    if (!ok) {
122                        TransactionHelper.setTransactionRollbackOnly();
123                    }
124                    TransactionHelper.commitOrRollbackTransaction();
125                }
126            }
127        } finally {
128            // logout
129            if (loginContext != null) {
130                loginContext.logout();
131            }
132        }
133    }
134
135    /**
136     * @return a plain map from a JobDataMap object
137     * @since 7.10
138     */
139    private Map<String, Serializable> getWrappedMap(JobDataMap jobMap) {
140        Map<String, Serializable> map = new HashMap<String, Serializable>();
141        for (String key : jobMap.getKeys()) {
142            map.put(key, (Serializable) jobMap.get(key));
143        }
144        return map;
145    }
146
147}