001/*
002 * Copyright 2002-2014 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.messaging.support;
018
019import java.util.Collections;
020import java.util.Set;
021import java.util.concurrent.CopyOnWriteArraySet;
022
023import org.springframework.messaging.MessageHandler;
024import org.springframework.messaging.SubscribableChannel;
025
026/**
027 * Abstract base class for {@link SubscribableChannel} implementations.
028 *
029 * @author Rossen Stoyanchev
030 * @since 4.0
031 */
032public abstract class AbstractSubscribableChannel extends AbstractMessageChannel implements SubscribableChannel {
033
034        private final Set<MessageHandler> handlers = new CopyOnWriteArraySet<MessageHandler>();
035
036
037        public Set<MessageHandler> getSubscribers() {
038                return Collections.<MessageHandler>unmodifiableSet(this.handlers);
039        }
040
041        public boolean hasSubscription(MessageHandler handler) {
042                return this.handlers.contains(handler);
043        }
044
045        @Override
046        public boolean subscribe(MessageHandler handler) {
047                boolean result = this.handlers.add(handler);
048                if (result) {
049                        if (logger.isDebugEnabled()) {
050                                logger.debug(getBeanName() + " added " + handler);
051                        }
052                }
053                return result;
054        }
055
056        @Override
057        public boolean unsubscribe(MessageHandler handler) {
058                boolean result = this.handlers.remove(handler);
059                if (result) {
060                        if (logger.isDebugEnabled()) {
061                                logger.debug(getBeanName() + " removed " + handler);
062                        }
063                }
064                return result;
065        }
066
067}