001/*
002 *  Copyright 2010 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.plugins.skineditor.readers;
017
018import java.io.IOException;
019import java.io.InputStream;
020import java.io.UnsupportedEncodingException;
021import java.net.URLDecoder;
022import java.util.Arrays;
023import java.util.Collection;
024import java.util.Map;
025
026import org.apache.avalon.framework.parameters.Parameters;
027import org.apache.avalon.framework.service.ServiceException;
028import org.apache.avalon.framework.service.ServiceManager;
029import org.apache.cocoon.ProcessingException;
030import org.apache.cocoon.environment.ObjectModelHelper;
031import org.apache.cocoon.environment.Response;
032import org.apache.cocoon.environment.SourceResolver;
033import org.apache.cocoon.reading.ServiceableReader;
034import org.apache.commons.io.IOUtils;
035import org.apache.excalibur.source.Source;
036import org.apache.excalibur.source.impl.FileSource;
037import org.xml.sax.SAXException;
038
039import org.ametys.core.util.ImageHelper;
040
041/**
042 * Reader for temporary skin resources
043 */
044public class SkinResourceReader extends ServiceableReader
045{
046    /** The source resolver */
047    protected org.apache.excalibur.source.SourceResolver _srcResolver;
048    /** The file source */
049    protected FileSource _file;
050    
051    private boolean _readForDownload;
052    
053    private int _width;
054    private int _height;
055    private int _maxWidth;
056    private int _maxHeight;
057    private Collection<String> _allowedFormats = Arrays.asList(new String[]{"png", "gif", "jpg", "jpeg"});
058    
059    @Override
060    public void service(ServiceManager smanager) throws ServiceException
061    {
062        _srcResolver = (org.apache.excalibur.source.SourceResolver) smanager.lookup(org.apache.excalibur.source.SourceResolver.ROLE);
063    }
064    
065    @Override
066    public void setup(SourceResolver res, Map objModel, String src, Parameters par) throws ProcessingException, SAXException, IOException
067    {
068        super.setup(res, objModel, src, par);
069        
070        String skin = par.getParameter("skin", null);
071        String path = par.getParameter("path", null);
072        
073        assert skin != null || path != null;
074        
075        _readForDownload = par.getParameterAsBoolean("download", false);
076        
077        // parameters for image resizing
078        _width = par.getParameterAsInteger("width", 0);
079        _height = par.getParameterAsInteger("height", 0);
080        _maxWidth = par.getParameterAsInteger("maxWidth", 0);
081        _maxHeight = par.getParameterAsInteger("maxHeight", 0);
082        
083        _file = (FileSource) _getSource(skin, path);
084    }
085    
086    @Override
087    public void generate() throws IOException, SAXException, ProcessingException
088    {
089        try (InputStream is = _file.getInputStream();)
090        {
091            String name = _file.getName();
092            name = name.replaceAll("\\\\", "\\\\\\\\");
093            name = name.replaceAll("\\\"", "\\\\\\\"");
094            
095            Response response = ObjectModelHelper.getResponse(objectModel);
096            
097            if (_readForDownload)
098            {
099                response.setHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");
100            }
101            
102            if (_width > 0 || _height > 0 || _maxHeight > 0 || _maxWidth > 0)
103            {
104                // it's an image, which must be resized
105                int i = name.lastIndexOf('.');
106                String format = i != -1 ? name.substring(i + 1) : "png";
107                format = _allowedFormats.contains(format) ? format : "png";
108                
109                ImageHelper.generateThumbnail(is, out, format, _height, _width, _maxHeight, _maxWidth);
110            }
111            else
112            {
113                response.setHeader("Content-Length", Long.toString(_file.getContentLength()));
114
115                IOUtils.copy(is, out);
116            }
117            
118        }
119        catch (Exception e)
120        {
121            throw new ProcessingException("Unable to download file of uri " + _file.getURI(), e);
122        }
123        finally
124        {
125            IOUtils.closeQuietly(out);
126        }
127    }
128    
129    private Source _getSource (String skinName, String path) throws IOException
130    { 
131        return _srcResolver.resolveURI("ametys-home://skins/temp/" + skinName + _decodePath(path));
132    }
133    
134    private String _decodePath (String path) throws UnsupportedEncodingException
135    {
136        StringBuffer sb = new StringBuffer();
137        
138        String[] parts = path.split("/");
139        for (String part : parts)
140        {
141            sb.append("/");
142            sb.append(URLDecoder.decode(part, "utf-8"));
143        }
144        return sb.toString();
145    }
146}