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