001/*
002 *  Copyright 2020 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.resources;
017
018import java.util.HashSet;
019import java.util.Set;
020
021import org.apache.avalon.framework.configuration.Configurable;
022import org.apache.avalon.framework.configuration.Configuration;
023import org.apache.avalon.framework.configuration.ConfigurationException;
024import org.apache.commons.lang3.StringUtils;
025
026/**
027 * Simple {@link ResourceHandlerProvider} based on source suffixes (mainly file extensions).
028 */
029public abstract class AbstractSimpleResourceHandlerProvider extends AbstractResourceHandlerProvider implements Configurable
030{
031    /** The supported suffixes */
032    protected Set<String> _supportedSuffixes;
033    
034    @Override
035    public void configure(Configuration configuration) throws ConfigurationException
036    {
037        _supportedSuffixes = new HashSet<>();
038        
039        Configuration[] suffixConf = configuration.getChild("suffixes").getChildren("suffix");
040        for (Configuration suffix : suffixConf)
041        {
042            _supportedSuffixes.add(StringUtils.lowerCase(suffix.getValue()));
043        }
044    }
045    
046    public ResourceHandler getResourceHandler(String source) throws Exception
047    {
048        String lcSource = StringUtils.lowerCase(source);
049        
050        if (_supportedSuffixes.stream().anyMatch(suffix -> StringUtils.endsWith(lcSource, suffix)))
051        {
052            return setup(createResourceHandler(source));            
053        }
054        
055        return null;
056    }
057    
058    /**
059     * Actually creates the {@link ResourceHandler}.
060     * @param source the requested resource.
061     * @return the created {@link ResourceHandler}.
062     */
063    protected abstract ResourceHandler createResourceHandler(String source);
064}