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.hc.core5.http.impl.io;
29
30 import java.io.IOException;
31 import java.io.OutputStream;
32 import java.util.Iterator;
33
34 import org.apache.hc.core5.http.FormattedHeader;
35 import org.apache.hc.core5.http.Header;
36 import org.apache.hc.core5.http.HttpException;
37 import org.apache.hc.core5.http.HttpMessage;
38 import org.apache.hc.core5.http.io.HttpMessageWriter;
39 import org.apache.hc.core5.http.io.SessionOutputBuffer;
40 import org.apache.hc.core5.http.message.BasicLineFormatter;
41 import org.apache.hc.core5.http.message.LineFormatter;
42 import org.apache.hc.core5.util.Args;
43 import org.apache.hc.core5.util.CharArrayBuffer;
44
45
46
47
48
49
50
51 public abstract class AbstractMessageWriter<T extends HttpMessage> implements HttpMessageWriter<T> {
52
53 private final CharArrayBuffer lineBuf;
54 private final LineFormatter lineFormatter;
55
56
57
58
59
60
61
62
63
64 public AbstractMessageWriter(final LineFormatter formatter) {
65 super();
66 this.lineFormatter = formatter != null ? formatter : BasicLineFormatter.INSTANCE;
67 this.lineBuf = new CharArrayBuffer(128);
68 }
69
70 LineFormatter getLineFormatter() {
71 return this.lineFormatter;
72 }
73
74
75
76
77
78
79
80
81
82 protected abstract void writeHeadLine(T message, CharArrayBuffer lineBuf) throws IOException;
83
84 @Override
85 public void write(final T message, final SessionOutputBuffer buffer, final OutputStream outputStream) throws IOException, HttpException {
86 Args.notNull(message, "HTTP message");
87 Args.notNull(buffer, "Session output buffer");
88 Args.notNull(outputStream, "Output stream");
89 writeHeadLine(message, this.lineBuf);
90 buffer.writeLine(this.lineBuf, outputStream);
91 for (final Iterator<Header> it = message.headerIterator(); it.hasNext(); ) {
92 final Header header = it.next();
93 if (header instanceof FormattedHeader) {
94 final CharArrayBuffer chbuffer = ((FormattedHeader) header).getBuffer();
95 buffer.writeLine(chbuffer, outputStream);
96 } else {
97 this.lineBuf.clear();
98 lineFormatter.formatHeader(this.lineBuf, header);
99 buffer.writeLine(this.lineBuf, outputStream);
100 }
101 }
102 this.lineBuf.clear();
103 buffer.writeLine(this.lineBuf, outputStream);
104 }
105
106 }