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.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   * 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 (Fri, 13 Jul 2007) $
    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          // Enable auto-expand for easier encoding
    61          buf.setAutoExpand(true);
    62
    63          try {
    64              // output all headers except the content length
    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              // now the content length is the body length
    86              buf.putString("Content-Length: ", encoder);
    87              buf.putString(String.valueOf(msg.getBodyLength()), encoder);
    88              buf.put(CRLF);
    89              buf.put(CRLF);
    90              // add body
    91              buf.put(msg.getBody());
    92              //System.out.println("\n+++++++");
    93              //for (int i=0; i<buf.position();i++)System.out.print(new String(new byte[]{buf.get(i)}));
    94              //System.out.println("\n+++++++");
    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 }