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.Charset;
24 import java.nio.charset.CharsetEncoder;
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 public class HttpServerEncoder implements ProtocolEncoder {
37 private static final Logger LOG = LoggerFactory.getLogger(HttpServerCodec.class);
38 private static final CharsetEncoder ENCODER = Charset.forName("UTF-8").newEncoder();
39
40 public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
41 LOG.debug("encode {}", message.getClass().getCanonicalName());
42 if (message instanceof HttpResponse) {
43 LOG.debug("HttpResponse");
44 HttpResponse msg = (HttpResponse) message;
45 StringBuilder sb = new StringBuilder(msg.getStatus().line());
46
47 for (Map.Entry<String, String> header : msg.getHeaders().entrySet()) {
48 sb.append(header.getKey());
49 sb.append(": ");
50 sb.append(header.getValue());
51 sb.append("\r\n");
52 }
53 sb.append("\r\n");
54
55
56
57 IoBuffer buf = IoBuffer.allocate(sb.length()).setAutoExpand(true);
58 buf.putString(sb.toString(), ENCODER);
59 buf.flip();
60 out.write(buf);
61 } else if (message instanceof ByteBuffer) {
62 LOG.debug("Body {}", message);
63 out.write(message);
64 } else if (message instanceof HttpEndOfContent) {
65 LOG.debug("End of Content");
66
67
68 }
69
70 }
71
72 public void dispose(IoSession session) throws Exception {
73
74 }
75 }