2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.russound.internal.rio;
15 import java.util.concurrent.CopyOnWriteArrayList;
17 import org.openhab.core.types.State;
20 * Abstract implementation of {@link RioHandlerCallback} that will provide listener services (adding/removing and firing
23 * @author Tim Roberts - Initial contribution
25 public abstract class AbstractRioHandlerCallback implements RioHandlerCallback {
27 private final CopyOnWriteArrayList<ListenerState> listeners = new CopyOnWriteArrayList<>();
30 * Adds a listener to {@link #listeners} wrapping the listener in a {@link ListenerState}
33 public void addListener(String channelId, RioHandlerCallbackListener listener) {
34 listeners.add(new ListenerState(channelId, listener));
38 * Remove a listener from {@link #listeners} if the channelID matches
41 public void removeListener(String channelId, RioHandlerCallbackListener listener) {
42 for (ListenerState listenerState : listeners) {
43 if (listenerState.channelId.equals(channelId) && listenerState.listener == listener) {
44 listeners.remove(listenerState);
50 * Fires a stateUpdate message to all listeners for the channelId and state
52 * @param channelId a non-null, non-empty channelId
53 * @param state a non-null state
54 * @throws IllegalArgumentException if channelId is null or empty.
55 * @throws IllegalArgumentException if state is null
57 protected void fireStateUpdated(String channelId, State state) {
58 if (channelId == null || channelId.isEmpty()) {
59 throw new IllegalArgumentException("channelId cannot be null or empty)");
62 throw new IllegalArgumentException("state cannot be null");
64 for (ListenerState listenerState : listeners) {
65 if (listenerState.channelId.equals(channelId)) {
66 listenerState.listener.stateUpdate(channelId, state);
72 * Internal class used to associate a listener with a channel id
76 private class ListenerState {
78 private final String channelId;
79 /** The listener associated with it */
80 private final RioHandlerCallbackListener listener;
83 * Create the listener state from the channelID and listener
85 * @param channelId the channelID
86 * @param listener the listener
88 ListenerState(String channelId, RioHandlerCallbackListener listener) {
89 this.channelId = channelId;
90 this.listener = listener;