001/**
002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
003 * <p>
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 * <p>
008 * http://www.apache.org/licenses/LICENSE-2.0
009 * <p>
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 */
016package io.jboot.support.shiro.cache;
017
018import io.jboot.Jboot;
019import org.apache.shiro.cache.Cache;
020import org.apache.shiro.cache.CacheException;
021import org.apache.shiro.util.CollectionUtils;
022
023import java.util.*;
024
025/**
026 * 自定义 shiro cache
027 *
028 * @param <K>
029 * @param <V>
030 */
031public class JbootShiroCache<K, V> implements Cache<K, V> {
032
033    private String cacheName;
034
035    public JbootShiroCache(String cacheName) {
036        this.cacheName = "shiroCache:" + cacheName;
037    }
038
039    @Override
040    public V get(K key) throws CacheException {
041        return Jboot.getCache().get(cacheName, key);
042    }
043
044    @Override
045    public V put(K key, V value) throws CacheException {
046        Jboot.getCache().put(cacheName, key, value);
047        return value;
048    }
049
050    @Override
051    public V remove(K key) throws CacheException {
052        V value = Jboot.getCache().get(cacheName, key);
053        Jboot.getCache().remove(cacheName, key);
054        return value;
055    }
056
057    @Override
058    public void clear() throws CacheException {
059        Jboot.getCache().removeAll(cacheName);
060    }
061
062    @Override
063    public int size() {
064        Set<K> keys = keys();
065        return keys == null ? 0 : keys.size();
066    }
067
068    @Override
069    public Set<K> keys() {
070        List list = Jboot.getCache().getKeys(cacheName);
071        return list == null ? null : new HashSet<>(list);
072    }
073
074    @Override
075    public Collection<V> values() {
076        Collection<V> values = Collections.emptyList();
077        List keys = Jboot.getCache().getKeys(cacheName);
078
079        if (!CollectionUtils.isEmpty(keys)) {
080            values = new ArrayList<>(keys.size());
081            for (Object key : keys) {
082                V value = Jboot.getCache().get(cacheName, key);
083                if (value != null) {
084                    values.add(value);
085                }
086            }
087        }
088
089        return values;
090    }
091
092}