01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17:
18: package org.apache.harmony.luni.net;
19:
20: import java.io.IOException;
21: import java.io.InputStream;
22: import java.net.Socket;
23: import java.net.SocketImpl;
24:
25: import org.apache.harmony.luni.util.Msg;
26:
27: /**
28: * The SocketInputStream supports the streamed reading of bytes from a socket.
29: * Multiple streams may be opened on a socket, so care should be taken to manage
30: * opened streams and coordinate read operations between threads.
31: */
32: class SocketInputStream extends InputStream {
33:
34: private final PlainSocketImpl socket;
35:
36: /**
37: * Constructs a SocketInputStream for the <code>socket</code>. Read
38: * operations are forwarded to the <code>socket</code>.
39: *
40: * @param socket the socket to be read
41: * @see Socket
42: */
43: public SocketInputStream(SocketImpl socket) {
44: super ();
45: this .socket = (PlainSocketImpl) socket;
46: }
47:
48: @Override
49: public int available() throws IOException {
50: return socket.available();
51: }
52:
53: @Override
54: public void close() throws IOException {
55: socket.close();
56: }
57:
58: @Override
59: public int read() throws IOException {
60: byte[] buffer = new byte[1];
61: int result = socket.read(buffer, 0, 1);
62: return (-1 == result) ? result : buffer[0] & 0xFF;
63: }
64:
65: @Override
66: public int read(byte[] buffer) throws IOException {
67: return read(buffer, 0, buffer.length);
68: }
69:
70: @Override
71: public int read(byte[] buffer, int offset, int count)
72: throws IOException {
73: if (null == buffer) {
74: throw new IOException(Msg.getString("K0047"));//$NON-NLS-1$
75: }
76:
77: if (0 == count) {
78: return 0;
79: }
80:
81: if (0 > offset || offset >= buffer.length) {
82: throw new ArrayIndexOutOfBoundsException(Msg
83: .getString("K002e"));//$NON-NLS-1$
84: }
85: if (0 > count || offset + count > buffer.length) {
86: throw new ArrayIndexOutOfBoundsException(Msg
87: .getString("K002f"));//$NON-NLS-1$
88: }
89:
90: return socket.read(buffer, offset, count);
91: }
92:
93: @Override
94: public long skip(long n) throws IOException {
95: return (0 == n) ? 0 : super.skip(n);
96: }
97: }
|