1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.example.httpserver.codec;
21
22 import java.nio.charset.CharacterCodingException;
23 import java.nio.charset.CharsetEncoder;
24 import java.util.Collections;
25 import java.util.HashSet;
26 import java.util.Iterator;
27 import java.util.Map.Entry;
28 import java.util.Set;
29
30 import org.apache.mina.common.ByteBuffer;
31 import org.apache.mina.common.IoSession;
32 import org.apache.mina.filter.codec.ProtocolEncoderOutput;
33 import org.apache.mina.filter.codec.demux.MessageEncoder;
34 import org.apache.mina.util.CharsetUtil;
35
36
37
38
39
40
41
42 public class HttpResponseEncoder implements MessageEncoder {
43 private static final Set TYPES;
44
45 static {
46 Set types = new HashSet();
47 types.add(HttpResponseMessage.class);
48 TYPES = Collections.unmodifiableSet(types);
49 }
50
51 private static final byte[] CRLF = new byte[] { 0x0D, 0x0A };
52
53 public HttpResponseEncoder() {
54 }
55
56 public void encode(IoSession session, Object message,
57 ProtocolEncoderOutput out) throws Exception {
58 HttpResponseMessage msg = (HttpResponseMessage) message;
59 ByteBuffer buf = ByteBuffer.allocate(256);
60
61 buf.setAutoExpand(true);
62
63 try {
64
65 CharsetEncoder encoder = CharsetUtil.getDefaultCharset()
66 .newEncoder();
67 buf.putString("HTTP/1.1 ", encoder);
68 buf.putString(String.valueOf(msg.getResponseCode()), encoder);
69 switch (msg.getResponseCode()) {
70 case HttpResponseMessage.HTTP_STATUS_SUCCESS:
71 buf.putString(" OK", encoder);
72 break;
73 case HttpResponseMessage.HTTP_STATUS_NOT_FOUND:
74 buf.putString(" Not Found", encoder);
75 break;
76 }
77 buf.put(CRLF);
78 for (Iterator it = msg.getHeaders().entrySet().iterator(); it
79 .hasNext();) {
80 Entry entry = (Entry) it.next();
81 buf.putString((String) entry.getKey(), encoder);
82 buf.putString(": ", encoder);
83 buf.putString((String) entry.getValue(), encoder);
84 buf.put(CRLF);
85 }
86
87 buf.putString("Content-Length: ", encoder);
88 buf.putString(String.valueOf(msg.getBodyLength()), encoder);
89 buf.put(CRLF);
90 buf.put(CRLF);
91
92 buf.put(msg.getBody());
93
94
95
96 } catch (CharacterCodingException ex) {
97 ex.printStackTrace();
98 }
99
100 buf.flip();
101 out.write(buf);
102 }
103
104 public Set getMessageTypes() {
105 return TYPES;
106 }
107 }