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(Msg.code(2200) + "No Cache Service Providers found. Choose between hapi-fhir-caching-caffeine (Default) and hapi-fhir-caching-guava (Android)");
041        }
042
043        public static <K, V> Cache<K, V> build(long theTimeoutMillis) {
044                CacheProvider<Object, Object> cacheProvider = getCacheProvider();
045                return cacheProvider.create(theTimeoutMillis);
046        }
047
048        public static  <K, V> LoadingCache<K, V> build(long theTimeoutMillis, CacheLoader<K, V> theCacheLoader) {
049                CacheProvider<K, V> cacheProvider = getCacheProvider();
050                return cacheProvider.create(theTimeoutMillis, theCacheLoader);
051        }
052
053        public static  <K, V> Cache<K, V> build(long theTimeoutMillis, long theMaximumSize) {
054                CacheProvider<Object, Object> cacheProvider = getCacheProvider();
055                return cacheProvider.create(theTimeoutMillis, theMaximumSize);
056        }
057
058        public static  <K, V> LoadingCache<K, V> build(long theTimeoutMillis, long theMaximumSize, CacheLoader<K, V> cacheLoader) {
059                CacheProvider<K, V> cacheProvider = getCacheProvider();
060                return cacheProvider.create(theTimeoutMillis, theMaximumSize, cacheLoader);
061        }
062}