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.content;
017
018import java.io.IOException;
019import java.net.MalformedURLException;
020import java.util.Map;
021import java.util.stream.Stream;
022
023import org.apache.avalon.framework.context.Context;
024import org.apache.avalon.framework.context.ContextException;
025import org.apache.avalon.framework.context.Contextualizable;
026import org.apache.avalon.framework.service.ServiceException;
027import org.apache.avalon.framework.service.ServiceManager;
028import org.apache.avalon.framework.service.Serviceable;
029import org.apache.avalon.framework.thread.ThreadSafe;
030import org.apache.cocoon.components.ContextHelper;
031import org.apache.cocoon.environment.Request;
032import org.apache.excalibur.source.Source;
033import org.apache.excalibur.source.SourceFactory;
034
035import org.ametys.cms.data.Binary;
036import org.ametys.cms.data.BinarySource;
037import org.ametys.cms.repository.Content;
038import org.ametys.core.util.FilenameUtils;
039import org.ametys.plugins.repository.AmetysObjectResolver;
040import org.ametys.plugins.repository.data.ametysobject.ModelAwareDataAwareAmetysObject;
041import org.ametys.runtime.plugin.component.AbstractLogEnabled;
042
043/**
044 * {@link SourceFactory} for content attributes.
045 */
046public class AttributeSourceFactory extends AbstractLogEnabled implements SourceFactory, ThreadSafe, Serviceable, Contextualizable
047{
048    /** source scheme */
049    public static final String ATTRIBUTE_SCHEME = "attribute";
050    
051    /** The context */
052    protected Context _context;
053    
054    /** The resolver */
055    protected AmetysObjectResolver _resolver;
056    
057    @Override
058    public void contextualize(Context context) throws ContextException
059    {
060        _context = context;
061    }
062    
063    public void service(ServiceManager manager) throws ServiceException
064    {
065        _resolver = (AmetysObjectResolver) manager.lookup(AmetysObjectResolver.ROLE);
066    }
067    
068    public Source getSource(String location, Map parameters) throws IOException, MalformedURLException
069    {
070        String uri = _getURI(location);
071        
072        // uri are like <contentPath>@<attributePath>;<filename>
073        int i = uri.indexOf('@');
074        int j = uri.indexOf(';', i);
075        String path = uri.substring(0, i);
076        String attribute = uri.substring(i + 1, j);
077        String filename = uri.substring(j + 1);
078        
079        ModelAwareDataAwareAmetysObject ametysObject = _getModelAwareDataAwareAmetysObject();
080        
081        try
082        {
083            if (ametysObject == null) 
084            {
085                ametysObject = _resolver.resolveByPath(FilenameUtils.decode(path));
086            }
087            
088            Binary binary = _getBinary(ametysObject, attribute, filename);
089    
090            return new BinarySource(binary, FilenameUtils.decode(filename), location, ATTRIBUTE_SCHEME);
091        }
092        catch (Exception e)
093        {
094            getLogger().error("Unable to resolve binary attribute for uri " + location, e);
095            
096            // returns an unexisting Source
097            return new BinarySource(null, FilenameUtils.decode(filename), location, ATTRIBUTE_SCHEME);
098        }
099    }
100
101    /**
102     * Get binary
103     * @param object the ametys object
104     * @param attribute the attribut
105     * @param filename the filename
106     * @return the binary
107     */
108    protected Binary _getBinary(ModelAwareDataAwareAmetysObject object, String attribute, String filename)
109    {
110        if (object.isMultiple(attribute))
111        {
112            // if multiple binary, take the first file with name equals to the filename
113            Binary[] binaries = object.getValue(attribute, false, new Binary[0]);
114            return Stream.of(binaries)
115                .filter(b -> b.getFilename().equals(filename))
116                .findFirst()
117                .orElse(null);
118        }
119        
120        return object.getValue(attribute);
121    }
122    
123    /**
124     * Get URI
125     * @param location the location
126     * @return the uri
127     */
128    protected String _getURI(String location)
129    {
130        return location.substring((ATTRIBUTE_SCHEME + "://").length());
131    }
132    
133    /**
134     * Get model aware data aware ametys object
135     * @return model aware data aware ametys object
136     */
137    protected ModelAwareDataAwareAmetysObject _getModelAwareDataAwareAmetysObject()
138    {
139        Request request = ContextHelper.getRequest(_context);
140        return (Content) request.getAttribute(Content.class.getName());
141    }
142    
143    public void release(Source source)
144    {
145        // nothing to do
146    }
147}