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.explorer;
017
018import java.io.IOException;
019import java.io.InputStream;
020
021import org.apache.excalibur.source.Source;
022import org.apache.excalibur.source.SourceNotFoundException;
023import org.apache.excalibur.source.SourceValidity;
024import org.apache.excalibur.source.impl.validity.TimeStampValidity;
025
026import org.ametys.core.cocoon.source.NamedSource;
027import org.ametys.plugins.explorer.resources.Resource;
028
029/**
030 * {@link Source} representing a {@link Resource}.
031 */
032public class AmetysResourceSource implements NamedSource
033{
034    private String _filename;
035    private Resource _resource;
036    
037    private String _uri;
038    
039    /**
040     * Constructor.
041     * @param resource the {@link Resource}.
042     * @param filename the local file name.
043     * @param uri this source's uri.
044     */
045    public AmetysResourceSource(Resource resource, String filename, String uri)
046    {
047        _resource = resource;
048        _filename = filename;
049        _uri = uri;
050    }
051    
052    public boolean exists()
053    {
054        return _resource != null;
055    }
056
057    public InputStream getInputStream() throws IOException, SourceNotFoundException
058    {
059        if (_resource == null)
060        {
061            throw new SourceNotFoundException("No resource found at " + _uri);
062        }
063        
064        return _resource.getInputStream();
065    }
066
067    public String getURI()
068    {
069        return _uri;
070    }
071
072    public String getScheme()
073    {
074        return AmetysResourceSourceFactory.RESOURCE_SCHEME;
075    }
076
077    public SourceValidity getValidity()
078    {
079        return new TimeStampValidity(getLastModified());
080    }
081    
082    public String getName()
083    {
084        return _filename;
085    }
086
087    public void refresh()
088    {
089        // does nothing
090    }
091
092    public String getMimeType()
093    {
094        return _resource.getMimeType();
095    }
096
097    public long getContentLength()
098    {
099        return _resource.getLength();
100    }
101
102    public long getLastModified()
103    {
104        return _resource != null ? _resource.getLastModified().getTime() : 0;
105    }
106}