]> git.argeo.org Git - gpl/argeo-slc.git/blob - org.argeo.slc.core/src/org/argeo/slc/core/execution/http/ServiceChannel.java
3e6a1ab89cfe40d951b3ac4026cbcd1c97b15214
[gpl/argeo-slc.git] / org.argeo.slc.core / src / org / argeo / slc / core / execution / http / ServiceChannel.java
1 package org.argeo.slc.core.execution.http;
2
3 import java.io.IOException;
4 import java.nio.ByteBuffer;
5 import java.nio.channels.AsynchronousByteChannel;
6 import java.nio.channels.CompletionHandler;
7 import java.nio.channels.ReadableByteChannel;
8 import java.nio.channels.WritableByteChannel;
9 import java.util.concurrent.ExecutorService;
10 import java.util.concurrent.Future;
11
12 public class ServiceChannel implements AsynchronousByteChannel {
13 private final ReadableByteChannel in;
14 private final WritableByteChannel out;
15
16 private boolean open = true;
17
18 private ExecutorService executor;
19
20 public ServiceChannel(ReadableByteChannel in, WritableByteChannel out, ExecutorService executor) {
21 this.in = in;
22 this.out = out;
23 this.executor = executor;
24 }
25
26 @Override
27 public Future<Integer> read(ByteBuffer dst) {
28 return executor.submit(() -> in.read(dst));
29 }
30
31 @Override
32 public <A> void read(ByteBuffer dst, A attachment, CompletionHandler<Integer, ? super A> handler) {
33 try {
34 Future<Integer> res = read(dst);
35 handler.completed(res.get(), attachment);
36 } catch (Exception e) {
37 handler.failed(e, attachment);
38 }
39 }
40
41 @Override
42 public Future<Integer> write(ByteBuffer src) {
43 return executor.submit(() -> out.write(src));
44 }
45
46 @Override
47 public <A> void write(ByteBuffer src, A attachment, CompletionHandler<Integer, ? super A> handler) {
48 try {
49 Future<Integer> res = write(src);
50 handler.completed(res.get(), attachment);
51 } catch (Exception e) {
52 handler.failed(e, attachment);
53 }
54 }
55
56 @Override
57 /** NB: it does not close the underlying channels. */
58 public void close() throws IOException {
59 open = false;
60 notifyAll();
61 }
62
63 @Override
64 public boolean isOpen() {
65 return open;
66 }
67
68 }