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.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.core.util.DateUtils;
028
029/**
030 * {@link Source} representing a binary.
031 */
032public class BinarySource implements NamedSource
033{
034    private Binary _binary;
035    private String _filename;
036    private String _uri;
037    private String _scheme;
038    
039    /**
040     * Constructor.
041     * @param binary the {@link Binary}.
042     * @param filename the filename.
043     * @param uri this source's uri.
044     * @param scheme this source's uri's scheme
045     */
046    public BinarySource(Binary binary, String filename, String uri, String scheme)
047    {
048        _binary = binary;
049        _filename = filename;
050        _uri = uri;
051        _scheme = scheme;
052    }
053    
054    public boolean exists()
055    {
056        return _binary != null && _binary.getFilename().equals(_filename);
057    }
058
059    public InputStream getInputStream() throws IOException, SourceNotFoundException
060    {
061        return _binary.getInputStream();
062    }
063
064    public String getURI()
065    {
066        return _uri;
067    }
068
069    public String getScheme()
070    {
071        return _scheme;
072    }
073
074    public SourceValidity getValidity()
075    {
076        return new TimeStampValidity(getLastModified());
077    }
078    
079    public String getName()
080    {
081        return _binary.getFilename();
082    }
083
084    public void refresh()
085    {
086        // does nothing
087    }
088
089    public String getMimeType()
090    {
091        return _binary.getMimeType();
092    }
093
094    public long getContentLength()
095    {
096        return _binary.getLength();
097    }
098
099    public long getLastModified()
100    {
101        return _binary != null ? DateUtils.asDate(_binary.getLastModificationDate()).getTime() : 0;
102    }
103}