001/*******************************************************************************
002 * Copyright (c) 2006-2014 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 ******************************************************************************/
009package org.nuxeo.runtime.trackers.files;
010
011import java.io.File;
012
013import org.nuxeo.runtime.api.Framework;
014import org.nuxeo.runtime.services.event.Event;
015import org.nuxeo.runtime.services.event.EventService;
016
017/**
018 * Runtime events about transient files which should be deleted once the runtime leave the thread (
019 * {@link FileEventTracker}. Producers should use the static {@link FileEvent#onEnter(Object, boolean)} and
020 * {@link FileEvent#onLeave(Object)} factory methods and fire events by invoking the event's {@link FileEvent#send()}
021 * method. Consumers should implements the {@link FileEventHandler} interface and register it in the
022 * {@link EventService} using the {@link FileEventListener} wrapper.
023 *
024 * @author Stephane Lacoin at Nuxeo (aka matic)
025 * @since 6.0
026 */
027public class FileEvent extends Event {
028
029    protected FileEvent(Object source, File aFile, Object aMarker) {
030        super(FileEvent.class.getName(), FileEvent.class.getName(), source, new Object[] { aFile, aMarker });
031    }
032
033    public static void listen(FileEventListener aListener) {
034        Framework.getService(EventService.class).addListener(FileEvent.class.getName(), aListener);
035    }
036
037    public static void ignore(FileEventListener aListener) {
038        Framework.getService(EventService.class).removeListener(FileEvent.class.getName(), aListener);
039    }
040
041    public void send() {
042        Framework.getService(EventService.class).sendEvent(this);
043    }
044
045    public void handle(FileEventHandler handler) {
046        handler.onFile(getFile(), getMarker());
047    }
048
049    protected File getFile() {
050        return (File) ((Object[]) getData())[0];
051    }
052
053    protected Object getMarker() {
054        return ((Object[]) getData())[1];
055    }
056
057    public static FileEvent onFile(Object source, File aFile, Object aMarker) {
058        return new FileEvent(source, aFile, aMarker);
059    }
060}