|
| 1 | +// Copyright (c) 2024-2025 Broadcom. All Rights Reserved. |
| 2 | +// The term "Broadcom" refers to Broadcom Inc. and/or its subsidiaries. |
| 3 | +// |
| 4 | +// This software, the RabbitMQ Stream Java client library, is dual-licensed under the |
| 5 | +// Mozilla Public License 2.0 ("MPL"), and the Apache License version 2 ("ASL"). |
| 6 | +// For the MPL, please see LICENSE-MPL-RabbitMQ. For the ASL, |
| 7 | +// please see LICENSE-APACHE2. |
| 8 | +// |
| 9 | +// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, |
| 10 | +// either express or implied. See the LICENSE file for specific language governing |
| 11 | +// rights and limitations of this software. |
| 12 | +// |
| 13 | +// If you have any questions regarding licensing, please contact us at |
| 14 | + |
| 15 | +package com.rabbitmq.stream.impl; |
| 16 | + |
| 17 | +import com.rabbitmq.stream.Resource; |
| 18 | +import java.util.List; |
| 19 | +import org.slf4j.Logger; |
| 20 | +import org.slf4j.LoggerFactory; |
| 21 | + |
| 22 | +final class StateEventSupport { |
| 23 | + |
| 24 | + private static final Logger LOGGER = LoggerFactory.getLogger(StateEventSupport.class); |
| 25 | + |
| 26 | + private final List<Resource.StateListener> listeners; |
| 27 | + |
| 28 | + StateEventSupport(List<Resource.StateListener> listeners) { |
| 29 | + this.listeners = List.copyOf(listeners); |
| 30 | + } |
| 31 | + |
| 32 | + void dispatch(Resource resource, Resource.State previousState, Resource.State currentState) { |
| 33 | + if (!this.listeners.isEmpty()) { |
| 34 | + Resource.Context context = new DefaultContext(resource, previousState, currentState); |
| 35 | + this.listeners.forEach( |
| 36 | + l -> { |
| 37 | + try { |
| 38 | + l.handle(context); |
| 39 | + } catch (Exception e) { |
| 40 | + LOGGER.warn("Error in resource listener", e); |
| 41 | + } |
| 42 | + }); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + private static class DefaultContext implements Resource.Context { |
| 47 | + |
| 48 | + private final Resource resource; |
| 49 | + private final Resource.State previousState; |
| 50 | + private final Resource.State currentState; |
| 51 | + |
| 52 | + private DefaultContext( |
| 53 | + Resource resource, Resource.State previousState, Resource.State currentState) { |
| 54 | + this.resource = resource; |
| 55 | + this.previousState = previousState; |
| 56 | + this.currentState = currentState; |
| 57 | + } |
| 58 | + |
| 59 | + @Override |
| 60 | + public Resource resource() { |
| 61 | + return this.resource; |
| 62 | + } |
| 63 | + |
| 64 | + @Override |
| 65 | + public Resource.State previousState() { |
| 66 | + return this.previousState; |
| 67 | + } |
| 68 | + |
| 69 | + @Override |
| 70 | + public Resource.State currentState() { |
| 71 | + return this.currentState; |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments