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.Objects;
019
020import org.apache.cocoon.components.LifecycleHelper;
021import org.apache.cocoon.util.log.SLF4JLoggerAdapter;
022
023import org.ametys.core.util.LambdaUtils;
024import org.ametys.runtime.plugin.component.AbstractThreadSafeComponentPrioritizableExtensionPoint;
025import org.ametys.runtime.plugin.component.LogEnabled;
026
027/**
028 * Extension point for {@link ResourceHandlerProvider}.
029 */
030public class ResourceHandlerProviderExtensionPoint extends AbstractThreadSafeComponentPrioritizableExtensionPoint<ResourceHandlerProvider>
031{
032    /** Avalon Role */
033    public static final String ROLE = ResourceHandlerProviderExtensionPoint.class.getName();
034
035    @Override
036    protected boolean sortPriorityAscending()
037    {
038        return false;
039    }
040    
041    /**
042     * Get the extension of max priority matching the provided source, based on the registered suffixes
043     * @param source The source
044     * @return The corresponding extension
045     * @throws Exception if an error occurs during ResourceHandler creation.
046     */
047    public ResourceHandler getResourceHandler(String source) throws Exception
048    {
049        return getExtensionsIds().stream()
050                                 .map(this::getExtension)
051                                 .map(LambdaUtils.wrap(provider -> provider.getResourceHandler(source)))
052                                 .filter(Objects::nonNull)
053                                 .findFirst()
054                                 .orElse(_getDefaultResourceHandler());
055    }
056    
057    private ResourceHandler _getDefaultResourceHandler() throws Exception
058    {
059        ResourceHandler handler = new DefaultResourceHandler();
060        LifecycleHelper.setupComponent(handler, new SLF4JLoggerAdapter(getLogger()), _context, _cocoonManager, null);
061        if (handler instanceof LogEnabled)
062        {
063            ((LogEnabled) handler).setLogger(getLogger());
064        }
065        
066        return handler;
067    }
068}