001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 * 019 */ 020package org.apache.mina.http; 021 022import java.nio.ByteBuffer; 023import java.nio.charset.Charset; 024import java.nio.charset.CharsetEncoder; 025import java.util.Map; 026 027import org.apache.mina.core.buffer.IoBuffer; 028import org.apache.mina.core.session.IoSession; 029import org.apache.mina.filter.codec.ProtocolEncoder; 030import org.apache.mina.filter.codec.ProtocolEncoderOutput; 031import org.apache.mina.http.api.HttpEndOfContent; 032import org.apache.mina.http.api.HttpResponse; 033import org.slf4j.Logger; 034import org.slf4j.LoggerFactory; 035 036public class HttpServerEncoder implements ProtocolEncoder { 037 private static final Logger LOG = LoggerFactory.getLogger(HttpServerCodec.class); 038 private static final CharsetEncoder ENCODER = Charset.forName("UTF-8").newEncoder(); 039 040 public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { 041 LOG.debug("encode {}", message.getClass().getCanonicalName()); 042 if (message instanceof HttpResponse) { 043 LOG.debug("HttpResponse"); 044 HttpResponse msg = (HttpResponse) message; 045 StringBuilder sb = new StringBuilder(msg.getStatus().line()); 046 047 for (Map.Entry<String, String> header : msg.getHeaders().entrySet()) { 048 sb.append(header.getKey()); 049 sb.append(": "); 050 sb.append(header.getValue()); 051 sb.append("\r\n"); 052 } 053 sb.append("\r\n"); 054 IoBuffer buf = IoBuffer.allocate(sb.length()).setAutoExpand(true); 055 buf.putString(sb.toString(), ENCODER); 056 buf.flip(); 057 out.write(buf); 058 } else if (message instanceof ByteBuffer) { 059 LOG.debug("Body {}", message); 060 out.write(message); 061 } else if (message instanceof HttpEndOfContent) { 062 LOG.debug("End of Content"); 063 // end of HTTP content 064 // keep alive ? 065 } 066 067 } 068 069 public void dispose(IoSession session) throws Exception { 070 // TODO Auto-generated method stub 071 } 072}