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 *     Nuxeo - initial API and implementation
011 *
012 * $Id$
013 */
014
015package org.nuxeo.ecm.platform.audit.api.job;
016
017import java.util.ArrayList;
018import java.util.Date;
019import java.util.List;
020
021import org.nuxeo.ecm.core.api.security.SecurityConstants;
022import org.nuxeo.ecm.platform.audit.api.AuditLogger;
023import org.nuxeo.ecm.platform.audit.api.AuditReader;
024import org.nuxeo.ecm.platform.audit.api.LogEntry;
025import org.nuxeo.runtime.api.Framework;
026
027/**
028 * Simple helper class to trace job execution using the Audit Service.
029 *
030 * @author Thierry Delprat
031 */
032public class JobHistoryHelper {
033
034    public static final String JOB_STARTED_SUFFIX = "Started";
035
036    public static final String JOB_ENDED_SUFFIX = "Ended";
037
038    public static final String JOB_FAILED_SUFFIX = "Failed";
039
040    protected AuditLogger logger;
041
042    protected String jobName;
043
044    protected final String jobStartedEventId;
045
046    protected final String jobEndedEventId;
047
048    protected final String jobFailedEventId;
049
050    public JobHistoryHelper(String jobName) {
051        this.jobName = jobName;
052
053        jobStartedEventId = jobName + JOB_STARTED_SUFFIX;
054        jobEndedEventId = jobName + JOB_ENDED_SUFFIX;
055        jobFailedEventId = jobName + JOB_FAILED_SUFFIX;
056    }
057
058    protected LogEntry getNewLogEntry() {
059        LogEntry entry = getLogger().newLogEntry();
060        entry.setCategory(jobName);
061        entry.setPrincipalName(SecurityConstants.SYSTEM_USERNAME);
062        entry.setEventDate(new Date());
063        return entry;
064    }
065
066    protected AuditLogger getLogger() {
067        if (logger == null) {
068            logger = Framework.getService(AuditLogger.class);
069        }
070        return logger;
071    }
072
073    /**
074     * Logs an event for Job startup.
075     */
076    public void logJobStarted() {
077        LogEntry entry = getNewLogEntry();
078        entry.setEventId(jobStartedEventId);
079        List<LogEntry> entries = new ArrayList<LogEntry>();
080        entries.add(entry);
081        getLogger().addLogEntries(entries);
082    }
083
084    /**
085     * Logs an event for a successful Job completion.
086     */
087    public void logJobEnded() {
088        LogEntry entry = getNewLogEntry();
089        entry.setEventId(jobEndedEventId);
090        List<LogEntry> entries = new ArrayList<LogEntry>();
091        entries.add(entry);
092        getLogger().addLogEntries(entries);
093    }
094
095    /**
096     * Logs an event for a failed Job execution.
097     */
098    public void logJobFailed(String errMessage) {
099        LogEntry entry = getNewLogEntry();
100        entry.setEventId(jobFailedEventId);
101        entry.setComment(errMessage);
102        List<LogEntry> entries = new ArrayList<LogEntry>();
103        entries.add(entry);
104        getLogger().addLogEntries(entries);
105    }
106
107    protected Date getLastRunWithStatus(String status) {
108        AuditReader reader = Framework.getService(AuditReader.class);
109
110        StringBuilder query = new StringBuilder("from LogEntry log where log.eventId=");
111        query.append("'");
112        query.append(status);
113        query.append("' AND log.category='");
114        query.append(jobName);
115        query.append("'  ORDER BY log.eventDate DESC");
116
117        List<?> result = reader.nativeQuery(query.toString(), 1, 1);
118
119        if (!result.isEmpty()) {
120            LogEntry entry = (LogEntry) result.get(0);
121            return entry.getEventDate();
122        }
123
124        return null;
125    }
126
127    /**
128     * Gets the last date the Job was successfully run.
129     */
130    public Date getLastSuccessfulRun() {
131        return getLastRunWithStatus(jobEndedEventId);
132    }
133
134    /**
135     * Gets the last date the Job was failed.
136     */
137    public Date getLastFailedRun() {
138        return getLastRunWithStatus(jobFailedEventId);
139    }
140
141    /**
142     * Gets the last date the Job was started.
143     */
144    public Date getLastStarted() {
145        return getLastRunWithStatus(jobStartedEventId);
146    }
147
148}