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.cms.data;
017
018import java.io.IOException;
019import java.net.MalformedURLException;
020import java.util.Map;
021
022import org.apache.avalon.framework.context.Context;
023import org.apache.avalon.framework.context.ContextException;
024import org.apache.avalon.framework.context.Contextualizable;
025import org.apache.avalon.framework.thread.ThreadSafe;
026import org.apache.cocoon.components.ContextHelper;
027import org.apache.cocoon.environment.Request;
028import org.apache.excalibur.source.Source;
029import org.apache.excalibur.source.SourceFactory;
030
031import org.ametys.core.util.FilenameUtils;
032import org.ametys.runtime.plugin.component.AbstractLogEnabled;
033
034/**
035 * {@link SourceFactory} for site parameters.
036 */
037public class BinarySourceFactory extends AbstractLogEnabled implements SourceFactory, ThreadSafe, Contextualizable
038{
039    /** source scheme */
040    public static final String SCHEME = "binary";
041    
042    private Context _context;
043    
044    @Override
045    public void contextualize(Context context) throws ContextException
046    {
047        _context = context;
048    }
049    
050    public Source getSource(String location, Map parameters) throws IOException, MalformedURLException
051    {
052        String filename = location.substring((SCHEME + "://").length());
053        
054        Request request = ContextHelper.getRequest(_context);
055        
056        try
057        {
058            Binary binary = (Binary) request.getAttribute(Binary.class.getName());
059    
060            return new BinarySource(binary, FilenameUtils.decode(filename), location, SCHEME);
061        }
062        catch (Exception e)
063        {
064            getLogger().error("Unable to resolve binary data for uri " + location, e);
065            
066            // returns an unexisting Source
067            return new BinarySource(null, FilenameUtils.decode(filename), location, SCHEME);
068        }
069    }
070
071    public void release(Source source)
072    {
073        // nothing to do
074    }
075}