
001/*- 002 * #%L 003 * HAPI FHIR Subscription Server 004 * %% 005 * Copyright (C) 2014 - 2025 Smile CDR, Inc. 006 * %% 007 * Licensed under the Apache License, Version 2.0 (the "License"); 008 * you may not use this file except in compliance with the License. 009 * You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, software 014 * distributed under the License is distributed on an "AS IS" BASIS, 015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 016 * See the License for the specific language governing permissions and 017 * limitations under the License. 018 * #L% 019 */ 020package ca.uhn.fhir.jpa.topic; 021 022import org.hl7.fhir.r5.model.SubscriptionTopic; 023 024import java.util.Collection; 025import java.util.HashSet; 026import java.util.Map; 027import java.util.Optional; 028import java.util.Set; 029import java.util.concurrent.ConcurrentHashMap; 030 031public class ActiveSubscriptionTopicCache { 032 // We canonicalize on R5 SubscriptionTopic and convert back to R4B when necessary 033 private final Map<String, SubscriptionTopic> myCache = new ConcurrentHashMap<>(); 034 035 public int size() { 036 return myCache.size(); 037 } 038 039 /** 040 * @return true if the subscription topic was added, false if it was already present 041 */ 042 public boolean add(SubscriptionTopic theSubscriptionTopic) { 043 String key = theSubscriptionTopic.getIdElement().getIdPart(); 044 SubscriptionTopic previousValue = myCache.put(key, theSubscriptionTopic); 045 return previousValue == null; 046 } 047 048 /** 049 * @return the number of entries removed 050 */ 051 public int removeIdsNotInCollection(Set<String> theIdsToRetain) { 052 int retval = 0; 053 HashSet<String> safeCopy = new HashSet<>(myCache.keySet()); 054 055 for (String next : safeCopy) { 056 if (!theIdsToRetain.contains(next)) { 057 myCache.remove(next); 058 ++retval; 059 } 060 } 061 return retval; 062 } 063 064 public Collection<SubscriptionTopic> getAll() { 065 return myCache.values(); 066 } 067 068 public void remove(String theSubscriptionTopicId) { 069 myCache.remove(theSubscriptionTopicId); 070 } 071 072 public Optional<SubscriptionTopic> findSubscriptionTopicByUrl(String theTopicUrl) { 073 return myCache.values().stream() 074 .filter(t -> t.getUrl().equals(theTopicUrl)) 075 .findFirst(); 076 } 077}