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