1package org.apache.archiva.event;
23/*4 * Licensed to the Apache Software Foundation (ASF) under one5 * or more contributor license agreements. See the NOTICE file6 * distributed with this work for additional information7 * regarding copyright ownership. The ASF licenses this file8 * to you under the Apache License, Version 2.0 (the9 * "License"); you may not use this file except in compliance10 * with the License. You may obtain a copy of the License at11 *12 * http://www.apache.org/licenses/LICENSE-2.013 *14 * Unless required by applicable law or agreed to in writing,15 * software distributed under the License is distributed on an16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY17 * KIND, either express or implied. See the License for the18 * specific language governing permissions and limitations19 * under the License.20 */2122import org.slf4j.Logger;
23import org.slf4j.LoggerFactory;
2425import java.util.*;
26import java.util.concurrent.ConcurrentHashMap;
2728publicclassEventManagerimplementsEventSource29 {
3031privatestaticfinal Logger log = LoggerFactory.getLogger(EventManager.class);
3233privatefinal ConcurrentHashMap<EventType<? extends Event>, Set<EventHandler>> handlerMap = new ConcurrentHashMap<>();
3435privatefinal Object source;
3637publicEventManager(Object source) {
38if (source==null) {
39thrownew IllegalArgumentException("The source may not be null");
40 }
41this.source = source;
42 }
4344 @Override
45public <T extends Event> void registerEventHandler(EventType<T> type, EventHandler<? super T> eventHandler) {
46 Set<EventHandler> handlers = handlerMap.computeIfAbsent(type, t -> new LinkedHashSet<>());
47if (!handlers.contains(eventHandler)) {
48 handlers.add(eventHandler);
49 }
50 }
5152 @Override
53public <T extends Event> void unregisterEventHandler(EventType<T> type, EventHandler<? super T> eventHandler) {
54if (handlerMap.containsKey(type)) {
55 handlerMap.get(type).remove(eventHandler);
56 }
57 }
5859publicvoid fireEvent(Event fireEvent) {
60final EventType<? extends Event> type = fireEvent.getType();
61Event event;
62if (fireEvent.getSource()!=source) {
63 event = fireEvent.copyFor(source);
64 } else {
65 event = fireEvent;
66 }
67for (EventType<? extends Event> handlerType : handlerMap.keySet()) {
68if (EventType.isInstanceOf(type, handlerType)) {
69for (EventHandler handler : handlerMap.get(handlerType)) {
70try {
71 handler.handle(event);
72 } catch (Exception e) {
73// We catch all errors from handlers74 log.error("An error occured during event handling: {}", e.getMessage(), e);
75 }
76 }
77 }
78 }
79 }
80 }