com.tera.common.event.DefaultEventContainer.java Source code

Java tutorial

Introduction

Here is the source code for com.tera.common.event.DefaultEventContainer.java

Source

/**
 * This file is part of tera-api.
 *
 * tera-api is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
    
 * tera-api is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
    
 * You should have received a copy of the GNU General Public License
 * along with tera-api.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.tera.common.event;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;

/**
 * @author ATracer
 */
public class DefaultEventContainer implements EventContainer {

    private Multimap<String, EventCallback> callbackMap = Multimaps
            .synchronizedSetMultimap(HashMultimap.<String, EventCallback>create());

    @Override
    public void fireEvent(String eventType, Event event) {
        fireEvent(eventType, event, ArrayUtils.EMPTY_OBJECT_ARRAY);
    }

    @Override
    public void fireEvent(String eventType, Event event, Object... args) {
        Collection<EventCallback> callbacks = callbackMap.get(eventType);
        List<EventCallback> finishedCallbacks = new ArrayList<EventCallback>();
        for (EventCallback cb : callbacks) {
            cb.handle(event, args);
            if (cb.isOneRun()) {
                finishedCallbacks.add(cb);
            }
        }
        for (EventCallback finished : finishedCallbacks) {
            callbacks.remove(finished);
        }
    }

    @Override
    public void registerCallback(String eventType, EventCallback callback) {
        callbackMap.put(eventType, callback);
    }

    @Override
    public void removeCallback(String eventType, EventCallback callback) {
        callbackMap.get(eventType).remove(callback);
    }

    @Override
    public Collection<EventCallback> getCallbacks(String eventType) {
        return callbackMap.get(eventType);
    }
}