001package ca.uhn.fhir.rest.server.provider;
002
003/*-
004 * #%L
005 * HAPI FHIR - Server Framework
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 javax.annotation.Nonnull;
024import java.util.ArrayList;
025import java.util.Collections;
026import java.util.HashSet;
027import java.util.List;
028import java.util.Set;
029import java.util.function.Supplier;
030
031public class ResourceProviderFactory {
032        private Set<IResourceProviderFactoryObserver> myObservers = Collections.synchronizedSet(new HashSet<>());
033        private List<Supplier<Object>> mySuppliers = new ArrayList<>();
034
035        public void addSupplier(@Nonnull Supplier<Object> theSupplier) {
036                mySuppliers.add(theSupplier);
037                myObservers.forEach(observer -> observer.update(theSupplier));
038        }
039
040        public void removeSupplier(@Nonnull Supplier<Object> theSupplier) {
041                mySuppliers.remove(theSupplier);
042                myObservers.forEach(observer -> observer.remove(theSupplier));
043        }
044
045        public List<Object> createProviders() {
046                List<Object> retVal = new ArrayList<>();
047                for (Supplier<Object> next : mySuppliers) {
048                        Object nextRp = next.get();
049                        if (nextRp != null) {
050                                retVal.add(nextRp);
051                        }
052                }
053                return retVal;
054        }
055
056        public void attach(IResourceProviderFactoryObserver theObserver) {
057                myObservers.add(theObserver);
058        }
059
060        public void detach(IResourceProviderFactoryObserver theObserver) {
061                myObservers.remove(theObserver);
062        }
063}