001/*
002 * (C) Copyright 2015-2018 Nuxeo (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 *     Antoine Taillefer <ataillefer@nuxeo.com>
018 */
019
020package org.nuxeo.drive.listener;
021
022import java.util.ArrayList;
023import java.util.List;
024
025import org.apache.commons.lang3.ArrayUtils;
026import org.apache.commons.logging.Log;
027import org.apache.commons.logging.LogFactory;
028import org.nuxeo.drive.service.NuxeoDriveEvents;
029import org.nuxeo.ecm.core.event.Event;
030import org.nuxeo.ecm.core.event.EventBundle;
031import org.nuxeo.ecm.core.event.EventContext;
032import org.nuxeo.ecm.core.event.PostCommitFilteringEventListener;
033import org.nuxeo.ecm.platform.audit.api.AuditLogger;
034import org.nuxeo.ecm.platform.audit.api.LogEntry;
035import org.nuxeo.runtime.api.Framework;
036
037/**
038 * Post-commit asynchronous listener that pushes the virtual events generated by
039 * {@link NuxeoDriveFileSystemDeletionListener} to the Audit log.
040 *
041 * @since 7.4
042 */
043public class NuxeoDriveVirtualEventLogger implements PostCommitFilteringEventListener {
044
045    private static final Log log = LogFactory.getLog(NuxeoDriveVirtualEventLogger.class);
046
047    @Override
048    public boolean acceptEvent(Event event) {
049        return NuxeoDriveEvents.VIRTUAL_EVENT_CREATED.equals(event.getName());
050    }
051
052    @Override
053    public void handleEvent(EventBundle events) {
054        AuditLogger logger = Framework.getService(AuditLogger.class);
055        if (logger != null) {
056            for (Event event : events) {
057                EventContext ctx = event.getContext();
058                Object[] args = ctx.getArguments();
059                if (ArrayUtils.isEmpty(args)) {
060                    return;
061                }
062                List<LogEntry> logEntries = new ArrayList<>();
063                for (int i = 0; i < args.length; i++) {
064                    Object arg = args[i];
065                    if (arg instanceof LogEntry) {
066                        logEntries.add((LogEntry) arg);
067                    }
068                }
069                if (!logEntries.isEmpty()) {
070                    logger.addLogEntries(logEntries);
071                }
072            }
073        } else {
074            log.error("Can not reach AuditLogger");
075        }
076    }
077
078}