1 package org.apache.archiva.repository.events;
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 {
30 private static final Logger log = LoggerFactory.getLogger(EventManager.class);
32 private final ConcurrentHashMap<EventType<? extends Event>, Set<EventHandler>> handlerMap = new ConcurrentHashMap<>();
34 private final Object source;
36 public EventManager(Object source) {
38 throw new IllegalArgumentException("The source may not be null");
44 public <T extends Event> void registerEventHandler(EventType<T> type, EventHandler<? super T> eventHandler) {
45 Set<EventHandler> handlers = handlerMap.computeIfAbsent(type, t -> new LinkedHashSet<>());
46 if (!handlers.contains(eventHandler)) {
47 handlers.add(eventHandler);
52 public <T extends Event> void unregisterEventHandler(EventType<T> type, EventHandler<? super T> eventHandler) {
53 if (handlerMap.containsKey(type)) {
54 handlerMap.get(type).remove(eventHandler);
58 public void fireEvent(Event fireEvent) {
59 final EventType<? extends Event> type = fireEvent.getType();
61 if (fireEvent.getSource()!=source) {
62 event = fireEvent.copyFor(source);
66 for (EventType<? extends Event> handlerType : handlerMap.keySet()) {
67 if (EventType.isInstanceOf(type, handlerType)) {
68 for (EventHandler handler : handlerMap.get(handlerType)) {
70 handler.handle(event);
71 } catch (Exception e) {
72 // We catch all errors from handlers
73 log.error("An error occured during event handling: {}", e.getMessage(), e);