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