1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.http.nio.protocol;
29
30 import java.io.IOException;
31
32 import org.apache.http.HttpEntity;
33 import org.apache.http.HttpResponse;
34 import org.apache.http.nio.ContentEncoder;
35 import org.apache.http.nio.IOControl;
36 import org.apache.http.nio.entity.EntityAsyncContentProducer;
37 import org.apache.http.nio.entity.HttpAsyncContentProducer;
38 import org.apache.http.protocol.HttpContext;
39 import org.apache.http.util.Args;
40
41
42
43
44
45
46
47
48
49
50
51
52 public class BasicAsyncResponseProducer implements HttpAsyncResponseProducer {
53
54 private final HttpResponse response;
55 private final HttpAsyncContentProducer producer;
56
57
58
59
60
61
62
63
64
65
66
67 protected BasicAsyncResponseProducer(
68 final HttpResponse response,
69 final HttpAsyncContentProducer producer) {
70 super();
71 Args.notNull(response, "HTTP response");
72 Args.notNull(producer, "HTTP content producer");
73 this.response = response;
74 this.producer = producer;
75 }
76
77
78
79
80
81
82
83
84 public BasicAsyncResponseProducer(final HttpResponse response) {
85 super();
86 Args.notNull(response, "HTTP response");
87 this.response = response;
88 final HttpEntity entity = response.getEntity();
89 if (entity != null) {
90 if (entity instanceof HttpAsyncContentProducer) {
91 this.producer = (HttpAsyncContentProducer) entity;
92 } else {
93 this.producer = new EntityAsyncContentProducer(entity);
94 }
95 } else {
96 this.producer = null;
97 }
98 }
99
100 @Override
101 public HttpResponse generateResponse() {
102 return this.response;
103 }
104
105 @Override
106 public void produceContent(
107 final ContentEncoder encoder, final IOControl ioControl) throws IOException {
108 if (this.producer != null) {
109 this.producer.produceContent(encoder, ioControl);
110 if (encoder.isCompleted()) {
111 this.producer.close();
112 }
113 }
114 }
115
116 @Override
117 public void responseCompleted(final HttpContext context) {
118 }
119
120 @Override
121 public void failed(final Exception ex) {
122 }
123
124 @Override
125 public void close() throws IOException {
126 if (this.producer != null) {
127 this.producer.close();
128 }
129 }
130
131 @Override
132 public String toString() {
133 final StringBuilder buf = new StringBuilder();
134 buf.append(this.response);
135 if (this.producer != null) {
136 buf.append(" ").append(this.producer);
137 }
138 return buf.toString();
139 }
140
141 }