001package ca.uhn.fhir.sl.cache;
002
003/*-
004 * #%L
005 * HAPI FHIR - ServiceLoaders - Caching API
006 * %%
007 * Copyright (C) 2014 - 2023 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.i18n.Msg;
024
025import java.util.Iterator;
026import java.util.ServiceLoader;
027
028@SuppressWarnings("unchecked")
029public class CacheFactory {
030
031        @SuppressWarnings("rawtypes")
032        static ServiceLoader<CacheProvider> loader = ServiceLoader.load(CacheProvider.class);
033
034        @SuppressWarnings("rawtypes")
035        private static synchronized <K, V> CacheProvider<K, V> getCacheProvider() {
036                Iterator<CacheProvider> iterator = loader.iterator();
037                if (iterator.hasNext()) {
038                        return iterator.next();
039                }
040                throw new RuntimeException(
041                                Msg.code(2200)
042                                                + "No Cache Service Providers found. Choose between hapi-fhir-caching-caffeine (Default) and hapi-fhir-caching-guava (Android)");
043        }
044
045        public static <K, V> Cache<K, V> build(long theTimeoutMillis) {
046                CacheProvider<Object, Object> cacheProvider = getCacheProvider();
047                return cacheProvider.create(theTimeoutMillis);
048        }
049
050        public static <K, V> LoadingCache<K, V> build(long theTimeoutMillis, CacheLoader<K, V> theCacheLoader) {
051                CacheProvider<K, V> cacheProvider = getCacheProvider();
052                return cacheProvider.create(theTimeoutMillis, theCacheLoader);
053        }
054
055        public static <K, V> Cache<K, V> build(long theTimeoutMillis, long theMaximumSize) {
056                CacheProvider<Object, Object> cacheProvider = getCacheProvider();
057                return cacheProvider.create(theTimeoutMillis, theMaximumSize);
058        }
059
060        public static <K, V> LoadingCache<K, V> build(
061                        long theTimeoutMillis, long theMaximumSize, CacheLoader<K, V> cacheLoader) {
062                CacheProvider<K, V> cacheProvider = getCacheProvider();
063                return cacheProvider.create(theTimeoutMillis, theMaximumSize, cacheLoader);
064        }
065}