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.repository.metadata.jcr;
017
018import java.io.ByteArrayInputStream;
019import java.io.ByteArrayOutputStream;
020import java.io.IOException;
021import java.io.InputStream;
022
023import javax.jcr.Binary;
024import javax.jcr.Node;
025import javax.jcr.RepositoryException;
026
027import org.apache.commons.codec.digest.DigestUtils;
028import org.slf4j.Logger;
029import org.slf4j.LoggerFactory;
030
031import org.ametys.plugins.repository.RepositoryConstants;
032
033/**
034 * @deprecated org.ametys.cms.data.Resource new class doesn't use JCROutputStream anymore
035 */
036@Deprecated
037class JCROutputStream extends ByteArrayOutputStream
038{
039    private static Logger __logger = LoggerFactory.getLogger(JCROutputStream.class);
040
041    private Node _node;
042    private boolean _storeHash;
043    
044    JCROutputStream(Node node, boolean storeHash)
045    {
046        _node = node;
047        _storeHash = storeHash;
048    }
049
050    @Override
051    public void close() throws IOException
052    {
053        super.close();
054
055        try
056        {
057            Binary binary = _node.getSession().getValueFactory().createBinary(new ByteArrayInputStream(toByteArray()));
058            _node.setProperty("jcr:data", binary);
059            
060            if (_storeHash)
061            {
062                try (InputStream binaryStream = binary.getStream())
063                {
064                    String sha1Hex = DigestUtils.sha1Hex(binaryStream);
065                    
066                    _node.setProperty(RepositoryConstants.NAMESPACE_PREFIX_INTERNAL + ":hash" , sha1Hex);
067                }
068                catch (IOException e)
069                {
070                    __logger.warn("An error occurred setting the hash of binary", e);
071                }
072            }
073        }
074        catch (RepositoryException e)
075        {
076            throw new IOException("Cannot save primary content", e);
077        }
078    }
079}