Skip to content

Method: CacheFactory()

1: /*
2: * JOPA
3: * Copyright (C) 2024 Czech Technical University in Prague
4: *
5: * This library is free software; you can redistribute it and/or
6: * modify it under the terms of the GNU Lesser General Public
7: * License as published by the Free Software Foundation; either
8: * version 3.0 of the License, or (at your option) any later version.
9: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library.
17: */
18: package cz.cvut.kbss.jopa.sessions.cache;
19:
20: import cz.cvut.kbss.jopa.model.JOPAPersistenceProperties;
21: import org.slf4j.Logger;
22: import org.slf4j.LoggerFactory;
23:
24: import java.util.Map;
25: import java.util.Objects;
26:
27: /**
28: * Creates second level cache based on the specified properties.
29: */
30: public abstract class CacheFactory {
31:
32: private static final Logger LOG = LoggerFactory.getLogger(CacheFactory.class);
33:
34: private static final String LRU_CACHE = "lru";
35: private static final String TTL_CACHE = "ttl";
36:
37: private CacheFactory() {
38: throw new AssertionError();
39: }
40:
41: /**
42: * Creates new cache based on the specified properties.
43: *
44: * @param properties Configuration of cache
45: * @return Cache implementation
46: */
47: public static CacheManager createCache(Map<String, String> properties) {
48: Objects.requireNonNull(properties);
49: final String enabledStr = properties.get(JOPAPersistenceProperties.CACHE_ENABLED);
50: if (enabledStr != null && !Boolean.parseBoolean(enabledStr)) {
51: LOG.debug("Second level cache is disabled.");
52: return new DisabledCacheManager();
53: }
54: return createEnabledCache(properties);
55: }
56:
57: private static CacheManager createEnabledCache(Map<String, String> properties) {
58: final String cacheType = properties.getOrDefault(JOPAPersistenceProperties.CACHE_TYPE, LRU_CACHE).toLowerCase();
59: switch (cacheType) {
60: case LRU_CACHE:
61: LOG.debug("Using LRU cache.");
62: return new LruCacheManager(properties);
63: case TTL_CACHE:
64: LOG.debug("Using TTL cache.");
65: return new TtlCacheManager(properties);
66: default:
67: throw new IllegalArgumentException("Invalid second level cache type " + cacheType);
68: }
69: }
70: }