001package ca.uhn.fhir.jpa.subscription.channel.subscription; 002 003/*- 004 * #%L 005 * HAPI FHIR Storage api 006 * %% 007 * Copyright (C) 2014 - 2022 Smile CDR, Inc. 008 * %% 009 * Licensed under the Apache License, Version 2.0 (the "License"); 010 * you may not use this file except in compliance with the License. 011 * You may obtain a copy of the License at 012 * 013 * http://www.apache.org/licenses/LICENSE-2.0 014 * 015 * Unless required by applicable law or agreed to in writing, software 016 * distributed under the License is distributed on an "AS IS" BASIS, 017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 018 * See the License for the specific language governing permissions and 019 * limitations under the License. 020 * #L% 021 */ 022 023import ca.uhn.fhir.jpa.subscription.channel.api.IChannelReceiver; 024import org.apache.commons.lang3.Validate; 025import org.springframework.messaging.Message; 026import org.springframework.messaging.MessageHandler; 027import org.springframework.messaging.SubscribableChannel; 028import org.springframework.messaging.support.AbstractSubscribableChannel; 029import org.springframework.messaging.support.ChannelInterceptor; 030 031import java.util.Set; 032 033public class BroadcastingSubscribableChannelWrapper extends AbstractSubscribableChannel implements IChannelReceiver { 034 035 private final IChannelReceiver myWrappedChannel; 036 private final MessageHandler myHandler; 037 038 public BroadcastingSubscribableChannelWrapper(IChannelReceiver theChannel) { 039 myHandler = message -> send(message); 040 theChannel.subscribe(myHandler); 041 myWrappedChannel = theChannel; 042 } 043 044 public SubscribableChannel getWrappedChannel() { 045 return myWrappedChannel; 046 } 047 048 @Override 049 protected boolean sendInternal(Message<?> theMessage, long timeout) { 050 Set<MessageHandler> subscribers = getSubscribers(); 051 Validate.isTrue(subscribers.size() > 0, "Channel has zero subscribers"); 052 for (MessageHandler next : subscribers) { 053 next.handleMessage(theMessage); 054 } 055 return true; 056 } 057 058 @Override 059 public void destroy() throws Exception { 060 myWrappedChannel.destroy(); 061 myWrappedChannel.unsubscribe(myHandler); 062 } 063 064 @Override 065 public void addInterceptor(ChannelInterceptor interceptor) { 066 super.addInterceptor(interceptor); 067 myWrappedChannel.addInterceptor(interceptor); 068 } 069 070 @Override 071 public String getName() { 072 return myWrappedChannel.getName(); 073 } 074}