

package gov.va.med.cds.socket.server;


import gov.va.med.cds.util.MllpUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;


public class MinaSimpleEchoDataHandler
    extends
        IoHandlerAdapter

{

    private static final Log LOGGER = LogFactory.getLog( MinaSimpleEchoDataHandler.class );


    @Override
    public void messageReceived( IoSession session, Object message )
        throws Exception
    {
        LOGGER.info( "Message received in Server.." );

        ByteBuffer buffer = ByteBuffer.allocate( ( ( ( IoBuffer )message ).limit() ) );

        int index = 0;

        do
        {
            buffer.put( index, ( ( IoBuffer )message ).get( index ) );
            index++ ;
        }
        while ( index < ( ( IoBuffer )message ).limit() );

        LOGGER.info( "Message is: " + new String( buffer.array() ) );

        buffer = MllpUtil.decode( new ByteBuffer[] { buffer }, Charset.forName( "ISO-8859-1" ), Charset.defaultCharset() );

        ByteBuffer responseMessage = MllpUtil.encode( buffer, Charset.forName( "ISO-8859-1" ), Charset.defaultCharset() );

        session.write( responseMessage );
    }

}
