1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.core.buffer.IoBuffer;
26 import org.apache.mina.core.future.WriteFuture;
27 import org.apache.mina.core.session.IoSession;
28
29
30
31
32
33
34
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 }