@Override
  protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
    if (log.isDebugEnabled()) log.debug("encode");
    if (msg instanceof SipMessage) {
      SipMessage m = (SipMessage) msg;

      ChannelBuffer header = dynamicBuffer(channel.getConfig().getBufferFactory());
      encodeInitialLine(header, m);
      encodeHeaders(header, m);

      // always add a single white line between headers and content
      header.writeByte(CR);
      header.writeByte(LF);

      ChannelBuffer content = m.getContent();
      if (content != null && !content.readable()) {
        if (log.isDebugEnabled()) log.debug("no content available");
        // no content available
        return header;
      } else {
        if (log.isDebugEnabled()) log.debug("content available");

        // TODO write content depending on content type
        return wrappedBuffer(header, content);
      }
    }

    // Unknown message type.
    return msg;
  }
 private static void encodeHeaders(ChannelBuffer buf, SipMessage message) {
   try {
     for (Map.Entry<String, List<String>> header : message.getHeaders().entrySet()) {
       encodeHeader(buf, header.getKey(), header.getValue());
     }
   } catch (UnsupportedEncodingException e) {
     throw (Error) new Error().initCause(e);
   }
 }