001// Copyright 2010 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007// http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry5.internal.services.assets;
016
017import java.io.ByteArrayInputStream;
018import java.io.ByteArrayOutputStream;
019import java.io.IOException;
020import java.io.InputStream;
021import java.io.OutputStream;
022
023/**
024 * A wrapper around a byte-stream, represented internally as a byte array. Part of the fix
025 * to TAP5-1116, avoiding a live lock due to ByteArrayOutputStream.writeTo() being a synchronized
026 * method.
027 * 
028 * @since 5.2.0
029 */
030public class BytestreamCache
031{
032    private final byte[] streamData;
033
034    public BytestreamCache(byte[] streamData)
035    {
036        this.streamData = streamData;
037    }
038
039    public BytestreamCache(ByteArrayOutputStream os)
040    {
041        this(os.toByteArray());
042    }
043
044    public void writeTo(OutputStream os) throws IOException
045    {
046        os.write(streamData, 0, streamData.length);
047    }
048
049    public int size()
050    {
051        return streamData.length;
052    }
053
054    public InputStream openStream()
055    {
056        return new ByteArrayInputStream(streamData);
057    }
058}