01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one
03: * or more contributor license agreements. See the NOTICE file
04: * distributed with this work for additional information
05: * regarding copyright ownership. The ASF licenses this file
06: * to you under the Apache License, Version 2.0 (the
07: * "License"); you may not use this file except in compliance
08: * with the License. You may obtain a copy of the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing,
13: * software distributed under the License is distributed on an
14: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15: * KIND, either express or implied. See the License for the
16: * specific language governing permissions and limitations
17: * under the License.
18: *
19: */
20: package org.apache.mina.handler.stream;
21:
22: import java.io.IOException;
23: import java.io.OutputStream;
24:
25: import org.apache.mina.common.IoBuffer;
26: import org.apache.mina.common.IoSession;
27: import org.apache.mina.common.WriteFuture;
28:
29: /**
30: * An {@link OutputStream} that forwards all write operations to
31: * the associated {@link IoSession}.
32: *
33: * @author The Apache MINA Project (dev@mina.apache.org)
34: * @version $Rev: 581234 $, $Date: 2007-10-02 07:39:48 -0600 (Tue, 02 Oct 2007) $
35: *
36: */
37: class IoSessionOutputStream extends OutputStream {
38: private final IoSession session;
39:
40: private WriteFuture lastWriteFuture;
41:
42: public IoSessionOutputStream(IoSession session) {
43: this .session = session;
44: }
45:
46: @Override
47: public void close() throws IOException {
48: try {
49: flush();
50: } finally {
51: session.close().awaitUninterruptibly();
52: }
53: }
54:
55: private void checkClosed() throws IOException {
56: if (!session.isConnected()) {
57: throw new IOException("The session has been closed.");
58: }
59: }
60:
61: private synchronized void write(IoBuffer buf) throws IOException {
62: checkClosed();
63: WriteFuture future = session.write(buf);
64: lastWriteFuture = future;
65: }
66:
67: @Override
68: public void write(byte[] b, int off, int len) throws IOException {
69: write(IoBuffer.wrap(b.clone(), off, len));
70: }
71:
72: @Override
73: public void write(int b) throws IOException {
74: IoBuffer buf = IoBuffer.allocate(1);
75: buf.put((byte) b);
76: buf.flip();
77: write(buf);
78: }
79:
80: @Override
81: public synchronized void flush() throws IOException {
82: if (lastWriteFuture == null) {
83: return;
84: }
85:
86: lastWriteFuture.awaitUninterruptibly();
87: if (!lastWriteFuture.isWritten()) {
88: throw new IOException(
89: "The bytes could not be written to the session");
90: }
91: }
92: }
|