1 /**********************************************************************
2 * ChannelInputStream.java
3 * created on 16.08.2004 by netseeker
4 * $Source: /cvsroot/ejoe/EJOE/src/de/netseeker/ejoe/io/ByteBufferInputStream.java,v $
5 * $Date: 2006/11/05 16:31:15 $
6 * $Revision: 1.8 $
7 *
8 * ====================================================================
9 *
10 * Copyright 2005-2006 netseeker aka Michael Manske
11 *
12 * Licensed under the Apache License, Version 2.0 (the "License");
13 * you may not use this file except in compliance with the License.
14 * You may obtain a copy of the License at
15 *
16 * http://www.apache.org/licenses/LICENSE-2.0
17 *
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
23 * ====================================================================
24 *
25 * This file is part of the ejoe framework.
26 * For more information on the author, please see
27 * <http://www.manskes.de/>.
28 *
29 *********************************************************************/
30
31 package de.netseeker.ejoe.io;
32
33 import java.io.InputStream;
34 import java.nio.ByteBuffer;
35
36 /***
37 * Implements an input stream over a NIO ByteBuffer. The ByteBuffer is replacable, and is supplied by an external
38 * source. This class is based on an article found at the homepage of Michael W. Spille.
39 *
40 * @author Michael W. Spille
41 * @author netseeker aka Michael Manske
42 * @link http://www.krisnmike.com/mike/nio.html
43 */
44 public class ByteBufferInputStream extends InputStream
45 {
46 private ByteBuffer buffer;
47
48 /***
49 * Constructs a new ByteBufferInputStream which reads from specified buffer
50 */
51 public ByteBufferInputStream(ByteBuffer buffer)
52 {
53 this.buffer = buffer;
54 }
55
56 /***
57 * @param buffer
58 */
59 public void setByteBuffer( ByteBuffer buffer )
60 {
61 this.buffer = buffer;
62 }
63
64
65
66
67
68
69 public int available()
70 {
71 return (buffer.remaining());
72 }
73
74
75
76
77
78
79 public void close()
80 {
81 }
82
83
84
85
86
87
88 public boolean markSupported()
89 {
90 return (false);
91 }
92
93
94
95
96
97
98 public int read()
99 {
100 if ( buffer.hasRemaining() )
101 {
102 return (buffer.get() & 0xff);
103 }
104 else
105 {
106 return (-1);
107 }
108 }
109
110
111
112
113
114
115 public int read( byte[] b )
116 {
117 return (read( b, 0, b.length ));
118 }
119
120
121
122
123
124
125 public int read( byte[] b, int offset, int length )
126 {
127 if ( !buffer.hasRemaining() )
128 {
129 return (-1);
130 }
131 if ( length > buffer.remaining() )
132 {
133 length = buffer.remaining();
134 }
135 buffer.get( b, offset, length );
136 return (length);
137 }
138 }