001/*
002 *  Copyright 2019 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.ByteArrayOutputStream;
019import java.io.IOException;
020
021import org.apache.commons.codec.digest.DigestUtils;
022import org.slf4j.Logger;
023import org.slf4j.LoggerFactory;
024
025import org.ametys.plugins.repository.data.repositorydata.RepositoryData;
026
027/**
028 * Class representing a binary
029 */
030public class Binary extends NamedResource implements File
031{
032    /** The binary's logger */
033    protected static Logger __logger = LoggerFactory.getLogger(Binary.class);
034
035    /** the binary's hash */
036    protected String _hash;
037    
038    /**
039     * Default constructor
040     */
041    public Binary()
042    {
043        // Empty constructor
044    }
045    
046    /**
047     * Constructor to use when reading the binary from the repository
048     * @param repositoryData the repository data containing the resource's data
049     * @param hash the hash of the resource's data
050     */
051    public Binary(RepositoryData repositoryData, String hash)
052    {
053        super(repositoryData);
054        _hash = hash;
055    }
056    
057    @Override
058    protected void closeOutputStream(ByteArrayOutputStream outputStream) throws IOException
059    {
060        super.closeOutputStream(outputStream);
061        _hash = DigestUtils.sha1Hex(_buffer);
062    }
063
064    /**
065     * Retrieves the hash of the resource's data
066     * @return the hash of the resource's data
067     */
068    public String getHash()
069    {
070        return _hash;
071    }
072    
073    public String getName()
074    {
075        return getFilename();
076    }
077}