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.Charset;
24 import java.nio.charset.CharsetEncoder;
25 import java.util.Collections;
26 import java.util.HashSet;
27 import java.util.Iterator;
28 import java.util.Set;
29 import java.util.Map.Entry;
30
31 import org.apache.mina.common.ByteBuffer;
32 import org.apache.mina.common.IoSession;
33 import org.apache.mina.filter.codec.ProtocolEncoderOutput;
34 import org.apache.mina.filter.codec.demux.MessageEncoder;
35
36
37
38
39
40
41
42 public class HttpResponseEncoder implements MessageEncoder {
43 private static final Set<Class<?>> TYPES;
44
45 static {
46 Set<Class<?>> types = new HashSet<Class<?>>();
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 = Charset.defaultCharset().newEncoder();
66 buf.putString("HTTP/1.1 ", encoder);
67 buf.putString(String.valueOf(msg.getResponseCode()), encoder);
68 switch (msg.getResponseCode()) {
69 case HttpResponseMessage.HTTP_STATUS_SUCCESS:
70 buf.putString(" OK", encoder);
71 break;
72 case HttpResponseMessage.HTTP_STATUS_NOT_FOUND:
73 buf.putString(" Not Found", encoder);
74 break;
75 }
76 buf.put(CRLF);
77 for (Iterator it = msg.getHeaders().entrySet().iterator(); it
78 .hasNext();) {
79 Entry entry = (Entry) it.next();
80 buf.putString((String) entry.getKey(), encoder);
81 buf.putString(": ", encoder);
82 buf.putString((String) entry.getValue(), encoder);
83 buf.put(CRLF);
84 }
85
86 buf.putString("Content-Length: ", encoder);
87 buf.putString(String.valueOf(msg.getBodyLength()), encoder);
88 buf.put(CRLF);
89 buf.put(CRLF);
90
91 buf.put(msg.getBody());
92
93
94
95 } catch (CharacterCodingException ex) {
96 ex.printStackTrace();
97 }
98
99 buf.flip();
100 out.write(buf);
101 }
102
103 public Set<Class<?>> getMessageTypes() {
104 return TYPES;
105 }
106 }