001/*
002 *  Copyright 2013 Chris Pheby
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.jadira.lang.io.io2nio;
017
018import java.io.IOException;
019import java.io.OutputStream;
020import java.nio.BufferOverflowException;
021import java.nio.ByteBuffer;
022
023/**
024 * An OutputStream that writes to a ByteBuffer. This can be used to adapt the NIO type to standard Java IO.
025 */
026public class ByteBufferBackedOutputStream extends OutputStream {
027
028    private boolean isClosed = false;
029
030    ByteBuffer buf;
031
032    public ByteBufferBackedOutputStream(ByteBuffer buf) {
033        this.buf = buf;
034    }
035
036    @Override
037    public void write(int b) throws IOException {
038
039        if (isClosed) {
040            throw new IOException("ByteBufferOutputStream was already closed");
041        }
042        try {
043            buf.put((byte) b);
044        } catch (BufferOverflowException e) {
045            throw new IOException("Buffer is full: " + e.getMessage(), e);
046        }
047    }
048
049    @Override
050    public void write(byte[] bytes, int off, int len) throws IOException {
051
052        if (isClosed) {
053            throw new IOException("ByteBufferOutputStream was already closed");
054        }
055        try {
056            buf.put(bytes, off, len);
057        } catch (BufferOverflowException e) {
058            throw new IOException("Buffer is full: " + e.getMessage(), e);
059        }
060    }
061
062    @Override
063    public void close() {
064        isClosed = true;
065    }
066}