View Javadoc

1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *  
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *  
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License. 
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   * A {@link MessageEncoder} that encodes {@link HttpResponseMessage}.
38   * 
39   * @author The Apache Directory Project (mina-dev@directory.apache.org)
40   * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (금, 13  7월 2007) $
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          // Enable auto-expand for easier encoding
61          buf.setAutoExpand(true);
62  
63          try {
64              // output all headers except the content length
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              // now the content length is the body length
87              buf.putString("Content-Length: ", encoder);
88              buf.putString(String.valueOf(msg.getBodyLength()), encoder);
89              buf.put(CRLF);
90              buf.put(CRLF);
91              // add body
92              buf.put(msg.getBody());
93              //System.out.println("\n+++++++");
94              //for (int i=0; i<buf.position();i++)System.out.print(new String(new byte[]{buf.get(i)}));
95              //System.out.println("\n+++++++");
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 }