1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.http;
21
22 import java.nio.ByteBuffer;
23 import java.nio.charset.CharsetEncoder;
24 import java.nio.charset.StandardCharsets;
25 import java.util.Map;
26
27 import org.apache.mina.core.buffer.IoBuffer;
28 import org.apache.mina.core.session.IoSession;
29 import org.apache.mina.filter.codec.ProtocolEncoder;
30 import org.apache.mina.filter.codec.ProtocolEncoderOutput;
31 import org.apache.mina.http.api.HttpEndOfContent;
32 import org.apache.mina.http.api.HttpResponse;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36
37
38
39
40
41 public class HttpServerEncoder implements ProtocolEncoder {
42 private static final Logger LOGGER = LoggerFactory.getLogger(HttpServerCodec.class);
43 private static final CharsetEncoder ENCODER = StandardCharsets.UTF_8.newEncoder();
44
45
46
47
48 @Override
49 public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
50 if (LOGGER.isDebugEnabled()) {
51 LOGGER.debug("encode {}", message.getClass().getCanonicalName());
52 }
53
54 if (message instanceof HttpResponse) {
55 if (LOGGER.isDebugEnabled()) {
56 LOGGER.debug("HttpResponse");
57 }
58
59 HttpResponse../../../org/apache/mina/http/api/HttpResponse.html#HttpResponse">HttpResponse msg = (HttpResponse) message;
60 StringBuilder sb = new StringBuilder(msg.getStatus().line());
61
62 for (Map.Entry<String, String> header : msg.getHeaders().entrySet()) {
63 sb.append(header.getKey());
64 sb.append(": ");
65 sb.append(header.getValue());
66 sb.append("\r\n");
67 }
68
69 sb.append("\r\n");
70 IoBuffer buf = IoBuffer.allocate(sb.length()).setAutoExpand(true);
71 buf.putString(sb.toString(), ENCODER);
72 buf.flip();
73 out.write(buf);
74 } else if (message instanceof ByteBuffer) {
75 if (LOGGER.isDebugEnabled()) {
76 LOGGER.debug("Body {}", message);
77 }
78
79 out.write(message);
80 } else if (message instanceof HttpEndOfContent) {
81 if (LOGGER.isDebugEnabled()) {
82 LOGGER.debug("End of Content");
83 }
84
85
86 }
87 }
88
89
90
91
92 @Override
93 public void dispose(IoSession session) throws Exception {
94
95 }
96 }