1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.esigate.parser.future;
16
17 import java.io.IOException;
18 import java.util.ArrayList;
19 import java.util.List;
20 import java.util.concurrent.CancellationException;
21 import java.util.concurrent.ExecutionException;
22 import java.util.concurrent.Future;
23 import java.util.concurrent.TimeUnit;
24 import java.util.concurrent.TimeoutException;
25
26 import org.esigate.HttpErrorPage;
27
28
29
30
31
32
33
34 public class FutureAppendableAdapter implements FutureAppendable {
35
36 private Appendable out;
37 private List<Future<CharSequence>> futureList;
38
39 public FutureAppendableAdapter(Appendable out) {
40 this.out = out;
41 this.futureList = new ArrayList<>();
42 }
43
44 @Override
45 public FutureAppendable enqueueAppend(Future<CharSequence> csq) {
46 this.futureList.add(csq);
47 return this;
48 }
49
50 @Override
51 public FutureAppendable performAppends(int timeout, TimeUnit unit) throws IOException, HttpErrorPage,
52 TimeoutException {
53
54 try {
55 for (Future<CharSequence> f : this.futureList) {
56 CharSequence csq = f.get(timeout, unit);
57 this.out.append(csq);
58 }
59 } catch (CancellationException | InterruptedException e) {
60 throw new IOException(e);
61 } catch (ExecutionException e) {
62
63 if (e.getCause() instanceof HttpErrorPage) {
64 throw (HttpErrorPage) e.getCause();
65 }
66 throw new IOException(e);
67 }
68
69 this.futureList.clear();
70 return this;
71 }
72
73 @Override
74 public boolean hasPending() {
75 return this.futureList.size() > 0;
76 }
77
78 @Override
79 public FutureAppendable performAppends() throws IOException, HttpErrorPage {
80 try {
81 for (Future<CharSequence> f : this.futureList) {
82 CharSequence csq = f.get();
83 this.out.append(csq);
84 }
85 } catch (CancellationException | InterruptedException e) {
86 throw new IOException(e);
87 } catch (ExecutionException e) {
88
89 if (e.getCause() instanceof HttpErrorPage) {
90 throw (HttpErrorPage) e.getCause();
91 }
92 throw new IOException(e);
93 }
94
95 this.futureList.clear();
96 return this;
97 }
98 }