View Javadoc

1   /*
2    *  Copyright 2006 Simon Raess
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  package net.sf.beep4j.internal.util;
17  
18  import java.io.IOException;
19  import java.io.InputStream;
20  import java.nio.ByteBuffer;
21  
22  /**
23   * InputStream implementation that reads from a ByteBuffer.
24   * 
25   * @author Simon Raess
26   */
27  public class ByteBufferInputStream extends InputStream {
28  	
29  	/**
30  	 * The buffer from which the data is read.
31  	 */
32  	private ByteBuffer buffer;
33  	
34  	/**
35  	 * Creates a new ByteBufferInputStream that reads from the given
36  	 * ByteBuffer. The stream creates a read only view of the buffer.
37  	 * Changes to the underlying buffer will be visible through
38  	 * this stream.
39  	 * 
40  	 * @param buffer the buffer from which data is read
41  	 */
42  	public ByteBufferInputStream(ByteBuffer buffer) {
43  		Assert.notNull("buffer", buffer);
44  		this.buffer = buffer.asReadOnlyBuffer();
45  	}
46  	
47  	/*
48  	 * Ensures that the buffer has not been closed.
49  	 */
50  	private void checkClosed() throws IOException {
51  		if (buffer == null) {
52  			throw new IOException("stream is closed");
53  		}
54  	}
55  	
56  	@Override
57  	public boolean markSupported() {
58  		return true;
59  	}
60  	
61  	@Override
62  	public synchronized void mark(int readlimit) {
63  		if (buffer != null) {
64  			buffer.mark();			
65  		}
66  	}
67  	
68  	@Override
69  	public synchronized void reset() throws IOException {
70  		checkClosed();
71  		buffer.reset();
72  	}
73  	
74  	@Override
75  	public int read() throws IOException {
76  		checkClosed();
77  		return buffer.hasRemaining() ? buffer.get() : -1;
78  	}
79  	
80  	@Override
81  	public int read(byte[] b) throws IOException {
82  		return read(b, 0, b.length);
83  	}
84  	
85  	@Override
86  	public int read(byte[] b, int off, int len) throws IOException {
87  		checkClosed();
88  		int length = Math.min(available(), len);
89  		if (length == 0) {
90  			return -1;
91  		} else {
92  			buffer.get(b, off, length);
93  			return length;
94  		}
95  	}
96  	
97  	@Override
98  	public int available() throws IOException {
99  		checkClosed();
100 		return buffer.remaining();
101 	}
102 
103 	@Override
104 	public void close() throws IOException {
105 		buffer = null;
106 	}
107 	
108 }