NIONetSocketBase.java

/*
** Module   : NIONetSocketBase.java
** Abstract : Implements NetSocket operations which are common for all NIO-based implementations. 
**
** Copyright (c) 2016-2021, Golden Code Development Corporation.
**
** -#- -I- --Date--  ---------------------------------------Description---------------------------------------
** 001 IAS 20160805  Initial version
** 002 IAS 20200729  Process large messages
** 003 IAS 20210329  Re-worked logging configuration
*/ 
/*
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU Affero General Public License as
** published by the Free Software Foundation, either version 3 of the
** License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU Affero General Public License for more details.
**
** You may find a copy of the GNU Affero GPL version 3 at the following
** location: https://www.gnu.org/licenses/agpl-3.0.en.html
** 
** Additional terms under GNU Affero GPL version 3 section 7:
** 
**   Under Section 7 of the GNU Affero GPL version 3, the following additional
**   terms apply to the works covered under the License.  These additional terms
**   are non-permissive additional terms allowed under Section 7 of the GNU
**   Affero GPL version 3 and may not be removed by you.
** 
**   0. Attribution Requirement.
** 
**     You must preserve all legal notices or author attributions in the covered
**     work or Appropriate Legal Notices displayed by works containing the covered
**     work.  You may not remove from the covered work any author or developer
**     credit already included within the covered work.
** 
**   1. No License To Use Trademarks.
** 
**     This license does not grant any license or rights to use the trademarks
**     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
**     of Golden Code Development Corporation. You are not authorized to use the
**     name Golden Code, FWD, or the names of any author or contributor, for
**     publicity purposes without written authorization.
** 
**   2. No Misrepresentation of Affiliation.
** 
**     You may not represent yourself as Golden Code Development Corporation or FWD.
** 
**     You may not represent yourself for publicity purposes as associated with
**     Golden Code Development Corporation, FWD, or any author or contributor to
**     the covered work, without written authorization.
** 
**   3. No Misrepresentation of Source or Origin.
** 
**     You may not represent the covered work as solely your work.  All modified
**     versions of the covered work must be marked in a reasonable way to make it
**     clear that the modified work is not originating from Golden Code Development
**     Corporation or FWD.  All modified versions must contain the notices of
**     attribution required in this license.
*/

package com.goldencode.p2j.net;

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.logging.*;

import com.goldencode.p2j.util.*;


/**
 * Implements NetSocket operations which are common for all NIO-based implementations.
 */
public abstract class NIONetSocketBase 
extends NetSocketBase 
implements NetSocket
{

   /** Underlying SocketChannel instance */
   protected final SocketChannel channel;

   /**
    * Constructor
    * 
    * @param channel
    *        underlying SocketChannel instance
    * @throws   IOException
    *           on error
    */
   NIONetSocketBase(SocketChannel channel)
   throws IOException
   {
      this.channel = channel;

//      this.channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
      this.channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
      this.channel.setOption(StandardSocketOptions.SO_SNDBUF, BUF_SIZE);
      this.channel.setOption(StandardSocketOptions.SO_RCVBUF, BUF_SIZE);
   }

   /**
    * Closes the socket. 
    */
   @Override
   public void close()
   {
      try
      {
         channel.close();
      }
      catch (IOException ex)
      {
         // best efforts
      }
   }

   /**
    * Reports if the socket is closed (and thus can no longer be used).
    *
    * @return   <code>true</code> if the socket is closed. 
    */
   @Override
   public boolean isClosed()
   {
      return !channel.isOpen();
   }
   
   /**
    * Access the address of the local system, through which we are connecting.
    *
    * @return   The local address.
    */
   @Override
   public InetAddress getLocalAddr()
   {
      return channel.socket().getLocalAddress();
   }
   
   /**
    * Access the address of the local system, through which we are connecting.
    *
    * @return   The local socket address.
    */
   @Override
   public InetSocketAddress getLocalSockAddr()
   {
      return new InetSocketAddress(channel.socket().getLocalAddress(), channel.socket().getLocalPort());
   }
   
   /**
    * Access the address of the remote system, to which we are connecting.
    *
    * @return   The remote address.
    */
   @Override
   public InetAddress getRemoteAddr()
   {
      return channel.socket().getInetAddress();
   }
   
   /**
    * Access the address of the remote system, to which we are connecting.
    *
    * @return   The remote socket address.
    */
   @Override
   public InetSocketAddress getRemoteSockAddr()
   {
      return new InetSocketAddress(channel.socket().getInetAddress(), channel.socket().getPort());
   }

   /**
    * Write byte array to the output
    *  
    * @param data
    *        byte array
    * @throws IOException 
    */
   public void write(byte[] data)
   throws IOException
   {
      ByteBuffer wbuf;
      int maxMessageSize = getMaxMessageSize();
      int total = data.length;
      if (total + 4 < maxMessageSize)
      {
         wbuf = ByteBuffer.allocate(4 + data.length);
         wbuf.putInt(data.length);
         wbuf.put(data);
         wbuf.flip();
         write(wbuf);
         return;
      }
      if (TRACE_LM)
      {
         NetSocketBase.LOG.finest(
               String.format("Long message to be sent. length: %d", data.length));
      }
      wbuf = ByteBuffer.allocate(4);
      wbuf.putInt(-total);
      wbuf.flip();
      write(wbuf);
      
      int pos = 0;
      while (total > 0)
      {
         int msgSize = Math.min(4 + total, maxMessageSize);
         wbuf = ByteBuffer.allocate(msgSize);
         msgSize -= 4;
         wbuf.putInt(msgSize);
         wbuf.put(data, pos, msgSize);
         wbuf.flip();
         write(wbuf);
         pos += msgSize;
         total -= msgSize;
         if (TRACE_LM)
         {
            NetSocketBase.LOG.finest(
                  String.format("Next chunk of long message sent. length: %d; remains: %d", 
                        msgSize, total));
         }
      }
      if (TRACE_LM)
      {
         NetSocketBase.LOG.finest(
               String.format("Long message sent. length: %d", data.length));
      }
 }

   /**
    * Read the next portion of raw data (byte array) to the output
    * 
    * @return byte array
    */
   @Override
   public byte[] read()
   throws IOException
   {
      try
      {
         return readFully();
      }
      catch (ClosedChannelException e)
      {
         throw new EOFException();
      }
   }

   /**
    * Read the integer from the input
    *  
    * @return integer data
    */
   @Override
   public int readInt()
   throws IOException
   {
      byte[] b = readFully();
      if (b.length != 4)
      {
         throw new IllegalStateException(String.format("Unexpected byte array length: %s instead of %s ",
                                                       b.length, 4));
      }
      return ByteBuffer.wrap(b).getInt();
   }

   /**
    * Write an integer to the output
    *  
    * @param val
    *        integer data to be written
    */
   @Override
   public void writeInt(int val)
   throws IOException
   {
      ByteBuffer bb = ByteBuffer.allocate(8);
      bb.putInt(4).putInt(val);
      bb.flip();
      write(bb);
   }

   /**
    * Read the byte sequence from the input
    *  
    * @param bytes
    *        byte array to be filled by the input bytes 
    */
   @Override
   public void readBytes(byte[] bytes)
   throws IOException
   {
      try
      {
         byte[] b = readFully();
         if (b.length != bytes.length)
         {
            throw new IllegalStateException(String.format("Unexpected byte array length: %s instead of %s ",
                                                          b.length, bytes.length));
         }
         System.arraycopy(b, 0, bytes, 0, bytes.length);
      }
      catch (ClosedChannelException e)
      {
         throw new EOFException();
      }

   }

   /**
    * Write a byte sequence to the output
    *  
    * @param bytes
    *        byte sequence to be written
    */
   @Override
   public void writeBytes(byte[] bytes)
   throws IOException
   {
      write(bytes);
   }

   /**
    * Read the boolean from the input
    *  
    * @return boolean data
    */
   @Override
   public boolean readBoolean()
   throws IOException
   {
      byte[] b = readFully();
      if (b.length != 1)
      {
         throw new IllegalStateException(String.format("Unexpected byte array length: %s instead of %s ",
                                                       b.length, 1));
      }
      return b[0] != 0;
   }

   /**
    * Write a boolean to the output
    *  
    * @param val
    *        boolean data to be written
    */
   @Override
   public void writeBoolean(boolean val)
   throws IOException
   {
      ByteBuffer bb = ByteBuffer.allocate(5);
      bb.putInt(1).put((byte)(val ? 1 : 0));
      bb.flip();
      write(bb);
   }

   /**
    * Read the UTF string from the input
    *  
    * @return UTF string
    */
   @Override
   public String readUTF()
   throws IOException
   {
      byte[] data = readFully();
      ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
      return ois.readUTF();
   }

   /**
    * Write an UTF String to the output
    *  
    * @param val
    *        UTF String to be written
    */
   @Override
   public void writeUTF(String val)
   throws IOException
   {
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(bos);
      oos.writeUTF(val);
      oos.flush();
      oos.close();
      write(bos.toByteArray());
   }

   /**
    * Send the data to the channel
    * 
    * @param bb
    *        data to be sent
    * @throws   IOException
    *           on error
    */
   protected abstract void write(ByteBuffer bb)
   throws IOException;
   
   /**
    * Read next data chunk from the channel
    *  
    * @return next data chunk
    * @throws   IOException
    *           on error
    * @throws   EOFException
    *           if no data can be read 
    */
   protected abstract byte[] readFully() 
   throws IOException, 
          EOFException;

   /**
    * Get maximal message size
    * 
    * @return maximal message size;
    */
   protected int getMaxMessageSize()
   {
      return Integer.MAX_VALUE;
   }
}