001/*
002 *  Copyright 2021 Anyware Services
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 */
016package org.ametys.core.cache;
017
018import java.util.List;
019import java.util.Map;
020import java.util.Optional;
021import java.util.function.Predicate;
022import java.util.stream.Collectors;
023
024import org.apache.avalon.framework.service.ServiceException;
025import org.apache.avalon.framework.service.ServiceManager;
026import org.apache.avalon.framework.service.Serviceable;
027
028import org.ametys.core.cache.AbstractCacheManager.CacheType;
029import org.ametys.runtime.i18n.I18nizableText;
030import org.ametys.runtime.model.Enumerator;
031
032/**
033 * {@link Enumerator} for the memory caches.
034 */
035public class MemoryCacheEnumerator implements Enumerator<String>, Serviceable
036{
037    /** The cache manager */
038    protected AbstractCacheManager _cacheManager;
039    
040    @Override
041    public void service(ServiceManager manager) throws ServiceException
042    {
043        _cacheManager = (AbstractCacheManager) manager.lookup(AbstractCacheManager.ROLE);
044    }
045
046    @Override
047    public I18nizableText getEntry(String value) throws Exception
048    {
049        try
050        {
051            return Optional.ofNullable(value)
052                    .map(_cacheManager::get)
053                    // FIXME Impossible to filter on CacheType for now
054                    .map(Cache::getLabel)
055                    .orElse(null);
056        }
057        catch (CacheException e)
058        {
059            // Ignore.
060        }
061        
062        return null;
063    }
064
065    @Override
066    public Map<String, I18nizableText> getTypedEntries() throws Exception
067    {
068        return _cacheManager.getAllCaches()
069            .entrySet()
070            .stream()
071            .filter(entry -> entry.getKey().getRight() == CacheType.MEMORY)
072            .map(Map.Entry::getValue)
073            .filter(Predicate.not(List::isEmpty))
074            .map(list -> list.get(0))
075            .collect(Collectors.toMap(Cache::getId, Cache::getLabel));
076    }
077}