1 package org.apache.archiva.event;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
26 import java.util.concurrent.ConcurrentHashMap;
28 public class EventManager implements EventSource
31 private static final Logger LOG = LoggerFactory.getLogger(EventManager.class);
33 private final ConcurrentHashMap<EventType<? extends Event>, Set<EventHandler>> handlerMap = new ConcurrentHashMap<>();
35 private final Object source;
37 public EventManager(Object source) {
39 throw new IllegalArgumentException("The source may not be null");
45 public <T extends Event> void registerEventHandler(EventType<T> type, EventHandler<? super T> eventHandler) {
46 Set<EventHandler> handlers = handlerMap.computeIfAbsent(type, t -> new LinkedHashSet<>());
47 if (!handlers.contains(eventHandler)) {
48 handlers.add(eventHandler);
53 public <T extends Event> void unregisterEventHandler(EventType<T> type, EventHandler<? super T> eventHandler) {
54 if (handlerMap.containsKey(type)) {
55 handlerMap.get(type).remove(eventHandler);
59 public void fireEvent(Event fireEvent) {
60 final EventType<? extends Event> type = fireEvent.getType();
62 if (fireEvent.getSource()!=source) {
63 event = fireEvent.copyFor(source);
67 for (EventType<? extends Event> handlerType : handlerMap.keySet()) {
68 if (EventType.isInstanceOf(type, handlerType)) {
69 for (EventHandler handler : handlerMap.get(handlerType)) {
71 handler.handle(event);
72 } catch (Exception e) {
73 // We catch all errors from handlers
74 LOG.error("An error occured during event handling: {}", e.getMessage(), e);