001// --------------------------------------------------------------------------------
002// Copyright 2002-2024 Echo Three, LLC
003//
004// Licensed under the Apache License, Version 2.0 (the "License");
005// you may not use this file except in compliance with the License.
006// You may obtain a copy of the License at
007//
008//     http://www.apache.org/licenses/LICENSE-2.0
009//
010// Unless required by applicable law or agreed to in writing, software
011// distributed under the License is distributed on an "AS IS" BASIS,
012// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013// See the License for the specific language governing permissions and
014// limitations under the License.
015// --------------------------------------------------------------------------------
016
017package com.echothree.util.server.persistence;
018
019import javax.enterprise.inject.spi.Unmanaged;
020import org.infinispan.Cache;
021
022public class Caches {
023
024    private static Unmanaged<SecurityCacheBean> unmanagedSecurityCacheBean = new Unmanaged<>(SecurityCacheBean.class);
025    private static Unmanaged<DataCacheBean> unmanagedDataCacheBean = new Unmanaged<>(DataCacheBean.class);
026
027    private Unmanaged.UnmanagedInstance<SecurityCacheBean> securityCacheBeanInstance = null;
028    private Cache<String, Object> securityCache = null;
029    private Unmanaged.UnmanagedInstance<DataCacheBean> dataCacheBeanInstance = null;
030    private Cache<String, Object> dataCache = null;
031
032    /** Creates a new instance of Caches */
033    public Caches() {
034    }
035
036    public Cache<String, Object> getSecurityCache() {
037        if(securityCache == null) {
038            securityCacheBeanInstance = unmanagedSecurityCacheBean.newInstance();
039            SecurityCacheBean securityCacheBean = securityCacheBeanInstance.produce().inject().postConstruct().get();
040            securityCache = securityCacheBean.getCache();
041        }
042
043        return securityCache;
044    }
045
046    public Cache<String, Object> getDataCache() {
047        if(dataCache == null) {
048            dataCacheBeanInstance = unmanagedDataCacheBean.newInstance();
049            DataCacheBean dataCacheBean = dataCacheBeanInstance.produce().inject().postConstruct().get();
050            dataCache = dataCacheBean.getCache();
051        }
052
053        return dataCache;
054    }
055
056    @SuppressWarnings("Finally")
057    public void close() {
058        if(securityCacheBeanInstance != null) {
059            securityCacheBeanInstance.preDestroy().dispose();
060            securityCacheBeanInstance = null;
061            securityCache = null;
062        }
063
064        if(dataCacheBeanInstance != null) {
065            dataCacheBeanInstance.preDestroy().dispose();
066            dataCacheBeanInstance = null;
067            dataCache = null;
068        }
069    }
070}