2 * Copyright (c) 2010-2020 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.apache.commons.lang.StringUtils;
18 import org.openhab.core.types.State;
21 * Abstract implementation of {@link RioHandlerCallback} that will provide listener services (adding/removing and firing
24 * @author Tim Roberts - Initial contribution
26 public abstract class AbstractRioHandlerCallback implements RioHandlerCallback {
28 private final CopyOnWriteArrayList<ListenerState> listeners = new CopyOnWriteArrayList<>();
31 * Adds a listener to {@link #listeners} wrapping the listener in a {@link ListenerState}
34 public void addListener(String channelId, RioHandlerCallbackListener listener) {
35 listeners.add(new ListenerState(channelId, listener));
39 * Remove a listener from {@link #listeners} if the channelID matches
42 public void removeListener(String channelId, RioHandlerCallbackListener listener) {
43 for (ListenerState listenerState : listeners) {
44 if (listenerState.channelId.equals(channelId) && listenerState.listener == listener) {
45 listeners.remove(listenerState);
51 * Fires a stateUpdate message to all listeners for the channelId and state
53 * @param channelId a non-null, non-empty channelId
54 * @param state a non-null state
55 * @throws IllegalArgumentException if channelId is null or empty.
56 * @throws IllegalArgumentException if state is null
58 protected void fireStateUpdated(String channelId, State state) {
59 if (StringUtils.isEmpty(channelId)) {
60 throw new IllegalArgumentException("channelId cannot be null or empty)");
63 throw new IllegalArgumentException("state cannot be null");
65 for (ListenerState listenerState : listeners) {
66 if (listenerState.channelId.equals(channelId)) {
67 listenerState.listener.stateUpdate(channelId, state);
73 * Internal class used to associate a listener with a channel id
77 private class ListenerState {
79 private final String channelId;
80 /** The listener associated with it */
81 private final RioHandlerCallbackListener listener;
84 * Create the listener state from the channelID and listener
86 * @param channelId the channelID
87 * @param listener the listener
89 ListenerState(String channelId, RioHandlerCallbackListener listener) {
90 this.channelId = channelId;
91 this.listener = listener;