001    /**
002     * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.kernel.io.delta;
016    
017    import java.io.IOException;
018    
019    import java.nio.ByteBuffer;
020    import java.nio.channels.WritableByteChannel;
021    
022    /**
023     * @author Connor McKay
024     */
025    public class ByteChannelWriter {
026    
027            public ByteChannelWriter(WritableByteChannel writableByteChannel) {
028                    this(writableByteChannel, 1024);
029            }
030    
031            public ByteChannelWriter(
032                    WritableByteChannel writableByteChannel, int bufferLength) {
033    
034                    _writableByteChannel = writableByteChannel;
035    
036                    _byteBuffer = ByteBuffer.allocate(bufferLength);
037            }
038    
039            public void ensureSpace(int length) throws IOException {
040                    if (_byteBuffer.remaining() < length) {
041                            write();
042                    }
043            }
044    
045            public void finish() throws IOException {
046                    _byteBuffer.flip();
047    
048                    _writableByteChannel.write(_byteBuffer);
049            }
050    
051            public ByteBuffer getBuffer() {
052                    return _byteBuffer;
053            }
054    
055            public void resizeBuffer(int minBufferLength) {
056                    if (_byteBuffer.capacity() >= minBufferLength) {
057                            return;
058                    }
059    
060                    ByteBuffer newBuffer = ByteBuffer.allocate(minBufferLength);
061    
062                    _byteBuffer.flip();
063    
064                    newBuffer.put(_byteBuffer);
065    
066                    _byteBuffer = newBuffer;
067            }
068    
069            protected void write() throws IOException {
070                    _byteBuffer.flip();
071    
072                    _writableByteChannel.write(_byteBuffer);
073    
074                    _byteBuffer.clear();
075            }
076    
077            private ByteBuffer _byteBuffer;
078            private WritableByteChannel _writableByteChannel;
079    
080    }