001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
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    }